blob: 1790f112cfa41ac9904c75a3b868b6ee05eb48d4 [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 // Disable all haptic playback for all other active tracks when haptic playback is supported
2368 // and the track contains haptic channels. Enable haptic playback for current track.
2369 // TODO: Request actual haptic playback status from vibrator service
2370 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2371 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2372 for (auto &t : mActiveTracks) {
2373 t->setHapticPlaybackEnabled(false);
2374 }
2375 track->setHapticPlaybackEnabled(true);
2376 }
2377
Eric Laurent81784c32012-11-19 14:55:58 -08002378 track->mResetDone = false;
2379 track->mPresentationCompleteFrames = 0;
2380 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002381 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2382 if (chain != 0) {
2383 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2384 track->sessionId());
2385 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002386 }
2387
2388 status = NO_ERROR;
2389 }
2390
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002391 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002392 return status;
2393}
2394
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002396{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002397 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002398 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002399 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2400 track->mState = TrackBase::STOPPED;
2401 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002402 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002403 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002404 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002405 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002406
2407 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002408}
2409
2410void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2411{
2412 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002413
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002414 String8 result;
2415 track->appendDump(result, false /* active */);
2416 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002417
Eric Laurent81784c32012-11-19 14:55:58 -08002418 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002419 if (track->isFastTrack()) {
2420 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002421 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002422 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2423 mFastTrackAvailMask |= 1 << index;
2424 // redundant as track is about to be destroyed, for dumpsys only
2425 track->mFastIndex = -1;
2426 }
2427 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2428 if (chain != 0) {
2429 chain->decTrackCnt();
2430 }
2431}
2432
2433String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2434{
Eric Laurent81784c32012-11-19 14:55:58 -08002435 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002436 String8 out_s8;
2437 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2438 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002439 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002440 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002441}
2442
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002443status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2444 Mutex::Autolock _l(mLock);
2445 if (mOutput == nullptr || mOutput->stream == nullptr) {
2446 return NO_INIT;
2447 }
2448 return mOutput->stream->selectPresentation(presentationId, programId);
2449}
2450
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002451void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002452 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2453 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002454
Eric Laurent73e26b62015-04-27 16:55:58 -07002455 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002456
2457 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002458 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002459 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002460 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002461 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002462 desc->mChannelMask = mChannelMask;
2463 desc->mSamplingRate = mSampleRate;
2464 desc->mFormat = mFormat;
2465 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002466 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002467 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002468 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002469 break;
2470
Eric Laurent73e26b62015-04-27 16:55:58 -07002471 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002472 default:
2473 break;
2474 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002475 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002476}
2477
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002478void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002479{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002480 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481}
2482
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002483void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002484{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002485 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002486}
2487
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002488void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002489{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002490 mCallbackThread->setAsyncError();
2491}
2492
Eric Laurent3b4529e2013-09-05 18:09:19 -07002493void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002494{
2495 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002496 // reject out of sequence requests
2497 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2498 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002499 mWaitWorkCV.signal();
2500 }
2501}
2502
Eric Laurent3b4529e2013-09-05 18:09:19 -07002503void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002504{
2505 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002506 // reject out of sequence requests
2507 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002508 // Register discontinuity when HW drain is completed because that can cause
2509 // the timestamp frame position to reset to 0 for direct and offload threads.
2510 // (Out of sequence requests are ignored, since the discontinuity would be handled
2511 // elsewhere, e.g. in flush).
2512 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002513 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002514 mWaitWorkCV.signal();
2515 }
2516}
2517
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002518void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002519{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002520 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002521 mSampleRate = mOutput->getSampleRate();
2522 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002523 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002524 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002525 }
Andy Hung9a592762014-07-21 21:56:01 -07002526 if ((mType == MIXER || mType == DUPLICATING)
2527 && !isValidPcmSinkChannelMask(mChannelMask)) {
2528 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2529 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002530 }
Andy Hunge5412692014-05-16 11:25:07 -07002531 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002532 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002533
2534 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002535 status_t result = mOutput->stream->getFormat(&mHALFormat);
2536 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002537 // Get format from the shim, which will be different than the HAL format
2538 // if playing compressed audio over HDMI passthrough.
2539 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002540 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002541 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002542 }
Andy Hung6146c082014-03-18 11:56:15 -07002543 if ((mType == MIXER || mType == DUPLICATING)
2544 && !isValidPcmSinkFormat(mFormat)) {
2545 LOG_FATAL("HAL format %#x not supported for mixed output",
2546 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002547 }
Phil Burk062e67a2015-02-11 13:40:50 -08002548 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002549 result = mOutput->stream->getBufferSize(&mBufferSize);
2550 LOG_ALWAYS_FATAL_IF(result != OK,
2551 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002552 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002553 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002554 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002555 mFrameCount);
2556 }
2557
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002558 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2559 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002561 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002562 }
2563 }
2564
Eric Laurentd1f69b02014-12-15 14:33:13 -08002565 mHwSupportsPause = false;
2566 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002567 bool supportsPause = false, supportsResume = false;
2568 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2569 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002570 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002571 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002572 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002573 } else if (supportsResume) {
2574 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002575 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002576 }
2577 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002578 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2579 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2580 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002581
Andy Hungfbfc3952015-01-15 13:33:51 -08002582 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2583 // For best precision, we use float instead of the associated output
2584 // device format (typically PCM 16 bit).
2585
2586 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2587 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2588 mBufferSize = mFrameSize * mFrameCount;
2589
2590 // TODO: We currently use the associated output device channel mask and sample rate.
2591 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2592 // (if a valid mask) to avoid premature downmix.
2593 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2594 // instead of the output device sample rate to avoid loss of high frequency information.
2595 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2596 }
2597
Andy Hung09a50072014-02-27 14:30:47 -08002598 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002599 double multiplier = 1.0;
2600 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2601 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002602 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2603 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002604
Eric Laurent81784c32012-11-19 14:55:58 -08002605 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2606 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2607 maxNormalFrameCount = maxNormalFrameCount & ~15;
2608 if (maxNormalFrameCount < minNormalFrameCount) {
2609 maxNormalFrameCount = minNormalFrameCount;
2610 }
2611 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2612 if (multiplier <= 1.0) {
2613 multiplier = 1.0;
2614 } else if (multiplier <= 2.0) {
2615 if (2 * mFrameCount <= maxNormalFrameCount) {
2616 multiplier = 2.0;
2617 } else {
2618 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2619 }
2620 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002621 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002622 }
2623 }
2624 mNormalFrameCount = multiplier * mFrameCount;
2625 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002626 if (mType == MIXER || mType == DUPLICATING) {
2627 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2628 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002629 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002630 mNormalFrameCount);
2631
Andy Hung08fb1742015-05-31 23:22:10 -07002632 // Check if we want to throttle the processing to no more than 2x normal rate
2633 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002634 mThreadThrottleTimeMs = 0;
2635 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002636 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2637
Andy Hung010a1a12014-03-13 13:57:33 -07002638 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2639 // Originally this was int16_t[] array, need to remove legacy implications.
2640 free(mSinkBuffer);
2641 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002642 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2643 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2644 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002645 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002646
Andy Hung69aed5f2014-02-25 17:24:40 -08002647 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2648 // drives the output.
2649 free(mMixerBuffer);
2650 mMixerBuffer = NULL;
2651 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002652 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002653 mMixerBufferSize = mNormalFrameCount * mChannelCount
2654 * audio_bytes_per_sample(mMixerBufferFormat);
2655 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2656 }
Andy Hung98ef9782014-03-04 14:46:50 -08002657 free(mEffectBuffer);
2658 mEffectBuffer = NULL;
2659 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002660 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002661 mEffectBufferSize = mNormalFrameCount * mChannelCount
2662 * audio_bytes_per_sample(mEffectBufferFormat);
2663 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2664 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002665
jiabin245cdd92018-12-07 17:55:15 -08002666 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2667 mChannelMask &= ~mHapticChannelMask;
2668 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2669 mChannelCount -= mHapticChannelCount;
2670
Eric Laurent81784c32012-11-19 14:55:58 -08002671 // force reconfiguration of effect chains and engines to take new buffer size and audio
2672 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002673 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002674 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2675 // matter.
2676 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2677 Vector< sp<EffectChain> > effectChains = mEffectChains;
2678 for (size_t i = 0; i < effectChains.size(); i ++) {
2679 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2680 }
2681}
2682
Kevin Rocard069c2712018-03-29 19:09:14 -07002683void AudioFlinger::PlaybackThread::updateMetadata_l()
2684{
Kevin Rocard12381092018-04-11 09:19:59 -07002685 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2686 return; // That should not happen
2687 }
2688 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2689 for (const sp<Track> &track : mActiveTracks) {
2690 // Do not short-circuit as all hasChanged states must be reset
2691 // as all the metadata are going to be sent
2692 hasChanged |= track->readAndClearHasChanged();
2693 }
2694 if (!hasChanged) {
2695 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002696 }
2697 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002698 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002699 for (const sp<Track> &track : mActiveTracks) {
2700 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002701 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002702 }
Kevin Rocard12381092018-04-11 09:19:59 -07002703 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002704}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002705
Kevin Rocard12381092018-04-11 09:19:59 -07002706void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2707 const StreamOutHalInterface::SourceMetadata& metadata)
2708{
2709 mOutput->stream->updateSourceMetadata(metadata);
2710};
2711
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002712status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002713{
2714 if (halFrames == NULL || dspFrames == NULL) {
2715 return BAD_VALUE;
2716 }
2717 Mutex::Autolock _l(mLock);
2718 if (initCheck() != NO_ERROR) {
2719 return INVALID_OPERATION;
2720 }
Andy Hung818e7a32016-02-16 18:08:07 -08002721 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002722 *halFrames = framesWritten;
2723
2724 if (isSuspended()) {
2725 // return an estimation of rendered frames when the output is suspended
2726 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002727 *dspFrames = (uint32_t)
2728 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002729 return NO_ERROR;
2730 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002731 status_t status;
2732 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002733 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002734 *dspFrames = (size_t)frames;
2735 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002736 }
2737}
2738
Eric Laurent4c415062016-06-17 16:14:16 -07002739// hasAudioSession_l() must be called with ThreadBase::mLock held
2740uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002741{
Eric Laurent81784c32012-11-19 14:55:58 -08002742 uint32_t result = 0;
2743 if (getEffectChain_l(sessionId) != 0) {
2744 result = EFFECT_SESSION;
2745 }
2746
2747 for (size_t i = 0; i < mTracks.size(); ++i) {
2748 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002749 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002750 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002751 if (track->isFastTrack()) {
2752 result |= FAST_SESSION;
2753 }
Eric Laurent81784c32012-11-19 14:55:58 -08002754 break;
2755 }
2756 }
2757
2758 return result;
2759}
2760
Glenn Kastend848eb42016-03-08 13:42:11 -08002761uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002762{
2763 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2764 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2765 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2766 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2767 }
2768 for (size_t i = 0; i < mTracks.size(); i++) {
2769 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002770 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002771 return AudioSystem::getStrategyForStream(track->streamType());
2772 }
2773 }
2774 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2775}
2776
2777
Phil Burk062e67a2015-02-11 13:40:50 -08002778AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002779{
2780 Mutex::Autolock _l(mLock);
2781 return mOutput;
2782}
2783
Phil Burk062e67a2015-02-11 13:40:50 -08002784AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002785{
2786 Mutex::Autolock _l(mLock);
2787 AudioStreamOut *output = mOutput;
2788 mOutput = NULL;
2789 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2790 // must push a NULL and wait for ack
2791 mOutputSink.clear();
2792 mPipeSink.clear();
2793 mNormalSink.clear();
2794 return output;
2795}
2796
2797// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002798sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002799{
2800 if (mOutput == NULL) {
2801 return NULL;
2802 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002803 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002804}
2805
2806uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2807{
2808 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2809}
2810
2811status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2812{
2813 if (!isValidSyncEvent(event)) {
2814 return BAD_VALUE;
2815 }
2816
2817 Mutex::Autolock _l(mLock);
2818
2819 for (size_t i = 0; i < mTracks.size(); ++i) {
2820 sp<Track> track = mTracks[i];
2821 if (event->triggerSession() == track->sessionId()) {
2822 (void) track->setSyncEvent(event);
2823 return NO_ERROR;
2824 }
2825 }
2826
2827 return NAME_NOT_FOUND;
2828}
2829
2830bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2831{
2832 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2833}
2834
2835void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2836 const Vector< sp<Track> >& tracksToRemove)
2837{
Andy Hungfe726a62018-09-27 15:17:25 -07002838 // Miscellaneous track cleanup when removed from the active list,
2839 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002840#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002841 for (const auto& track : tracksToRemove) {
2842 if (track->isExternalTrack()) {
2843 // to track the speaker usage
2844 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002845 }
2846 }
Andy Hungfe726a62018-09-27 15:17:25 -07002847#else
2848 (void)tracksToRemove; // suppress unused warning
2849#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002850}
2851
2852void AudioFlinger::PlaybackThread::checkSilentMode_l()
2853{
2854 if (!mMasterMute) {
2855 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002856 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2857 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2858 return;
2859 }
Eric Laurent81784c32012-11-19 14:55:58 -08002860 if (property_get("ro.audio.silent", value, "0") > 0) {
2861 char *endptr;
2862 unsigned long ul = strtoul(value, &endptr, 0);
2863 if (*endptr == '\0' && ul != 0) {
2864 ALOGD("Silence is golden");
2865 // The setprop command will not allow a property to be changed after
2866 // the first time it is set, so we don't have to worry about un-muting.
2867 setMasterMute_l(true);
2868 }
2869 }
2870 }
2871}
2872
2873// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002875{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002876 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002877 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002879 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002880
2881 // If an NBAIO sink is present, use it to write the normal mixer's submix
2882 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002883
Andy Hung010a1a12014-03-13 13:57:33 -07002884 const size_t count = mBytesRemaining / mFrameSize;
2885
Simon Wilson2d590962012-11-29 15:18:50 -08002886 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002887 // update the setpoint when AudioFlinger::mScreenState changes
2888 uint32_t screenState = AudioFlinger::mScreenState;
2889 if (screenState != mScreenState) {
2890 mScreenState = screenState;
2891 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2892 if (pipe != NULL) {
2893 pipe->setAvgFrames((mScreenState & 1) ?
2894 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2895 }
2896 }
Andy Hung010a1a12014-03-13 13:57:33 -07002897 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002898 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002899 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002900 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002901#ifdef TEE_SINK
2902 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2903#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002904 } else {
2905 bytesWritten = framesWritten;
2906 }
2907 // otherwise use the HAL / AudioStreamOut directly
2908 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002909 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002910
Eric Laurentbfb1b832013-01-07 09:53:42 -08002911 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002912 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2913 mWriteAckSequence += 2;
2914 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002916 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002917 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002918 // FIXME We should have an implementation of timestamps for direct output threads.
2919 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002920 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002921
Eric Laurentbfb1b832013-01-07 09:53:42 -08002922 if (mUseAsyncWrite &&
2923 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2924 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002925 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002926 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002927 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002928 }
Eric Laurent81784c32012-11-19 14:55:58 -08002929 }
2930
Eric Laurent81784c32012-11-19 14:55:58 -08002931 mNumWrites++;
2932 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002933 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002934 return bytesWritten;
2935}
2936
2937void AudioFlinger::PlaybackThread::threadLoop_drain()
2938{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002939 bool supportsDrain = false;
2940 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002941 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2942 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002943 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2944 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002945 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002946 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002947 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002948 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002949 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950 }
2951}
2952
2953void AudioFlinger::PlaybackThread::threadLoop_exit()
2954{
Eric Laurent275e8e92014-11-30 15:14:47 -08002955 {
2956 Mutex::Autolock _l(mLock);
2957 for (size_t i = 0; i < mTracks.size(); i++) {
2958 sp<Track> track = mTracks[i];
2959 track->invalidate();
2960 }
Andy Hungdae27702016-10-31 14:01:16 -07002961 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2962 // After we exit there are no more track changes sent to BatteryNotifier
2963 // because that requires an active threadLoop.
2964 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2965 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002966 }
Eric Laurent81784c32012-11-19 14:55:58 -08002967}
2968
2969/*
2970The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002971 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002972 - mActiveSleepTimeUs from activeSleepTimeUs()
2973 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002974 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2975 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002976 - maxPeriod from frame count and sample rate (MIXER only)
2977
2978The parameters that affect these derived values are:
2979 - frame count
2980 - frame size
2981 - sample rate
2982 - device type: A2DP or not
2983 - device latency
2984 - format: PCM or not
2985 - active sleep time
2986 - idle sleep time
2987*/
2988
2989void AudioFlinger::PlaybackThread::cacheParameters_l()
2990{
Andy Hung25c2dac2014-02-27 14:56:00 -08002991 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002992 mActiveSleepTimeUs = activeSleepTimeUs();
2993 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002994
2995 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2996 // truncating audio when going to standby.
2997 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2998 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2999 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3000 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3001 }
3002 }
Eric Laurent81784c32012-11-19 14:55:58 -08003003}
3004
Eric Laurent13084622016-05-17 10:51:49 -07003005bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003006{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003007 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003008 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003009 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003010 size_t size = mTracks.size();
3011 for (size_t i = 0; i < size; i++) {
3012 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003013 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003014 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003015 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003016 }
3017 }
Eric Laurent13084622016-05-17 10:51:49 -07003018 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003019}
3020
Haynes Mathew George05317d22016-05-03 16:34:26 -07003021void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3022{
3023 Mutex::Autolock _l(mLock);
3024 invalidateTracks_l(streamType);
3025}
3026
Eric Laurent81784c32012-11-19 14:55:58 -08003027status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3028{
Glenn Kastend848eb42016-03-08 13:42:11 -08003029 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003030 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003031 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003032 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3033 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3034 &halInBuffer);
3035 if (result != OK) return result;
3036 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003037 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003038 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003039 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003040 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003041 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003042 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003043 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003044 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003045 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003046 &halInBuffer);
3047 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003048#ifdef FLOAT_EFFECT_CHAIN
3049 buffer = halInBuffer->audioBuffer()->f32;
3050#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003051 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003052#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003053 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3054 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003055 }
3056
3057 // Attach all tracks with same session ID to this chain.
3058 for (size_t i = 0; i < mTracks.size(); ++i) {
3059 sp<Track> track = mTracks[i];
3060 if (session == track->sessionId()) {
3061 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3062 buffer);
3063 track->setMainBuffer(buffer);
3064 chain->incTrackCnt();
3065 }
3066 }
3067
3068 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003069 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003070 if (session == track->sessionId()) {
3071 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3072 chain->incActiveTrackCnt();
3073 }
3074 }
3075 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003076 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003077 chain->setInBuffer(halInBuffer);
3078 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003079 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003080 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003081 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3082 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003083 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003084 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003085 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003086 // Effect chain for other sessions are inserted at beginning of effect
3087 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003088 // sessions is not important.
3089 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3090 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3091 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003092 size_t size = mEffectChains.size();
3093 size_t i = 0;
3094 for (i = 0; i < size; i++) {
3095 if (mEffectChains[i]->sessionId() < session) {
3096 break;
3097 }
3098 }
3099 mEffectChains.insertAt(chain, i);
3100 checkSuspendOnAddEffectChain_l(chain);
3101
3102 return NO_ERROR;
3103}
3104
3105size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3106{
Glenn Kastend848eb42016-03-08 13:42:11 -08003107 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003108
3109 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3110
3111 for (size_t i = 0; i < mEffectChains.size(); i++) {
3112 if (chain == mEffectChains[i]) {
3113 mEffectChains.removeAt(i);
3114 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003115 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003116 if (session == track->sessionId()) {
3117 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3118 chain.get(), session);
3119 chain->decActiveTrackCnt();
3120 }
3121 }
3122
3123 // detach all tracks with same session ID from this chain
3124 for (size_t i = 0; i < mTracks.size(); ++i) {
3125 sp<Track> track = mTracks[i];
3126 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003127 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003128 chain->decTrackCnt();
3129 }
3130 }
3131 break;
3132 }
3133 }
3134 return mEffectChains.size();
3135}
3136
3137status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003138 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003139{
3140 Mutex::Autolock _l(mLock);
3141 return attachAuxEffect_l(track, EffectId);
3142}
3143
3144status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003145 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003146{
3147 status_t status = NO_ERROR;
3148
3149 if (EffectId == 0) {
3150 track->setAuxBuffer(0, NULL);
3151 } else {
3152 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3153 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3154 if (effect != 0) {
3155 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3156 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3157 } else {
3158 status = INVALID_OPERATION;
3159 }
3160 } else {
3161 status = BAD_VALUE;
3162 }
3163 }
3164 return status;
3165}
3166
3167void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3168{
3169 for (size_t i = 0; i < mTracks.size(); ++i) {
3170 sp<Track> track = mTracks[i];
3171 if (track->auxEffectId() == effectId) {
3172 attachAuxEffect_l(track, 0);
3173 }
3174 }
3175}
3176
3177bool AudioFlinger::PlaybackThread::threadLoop()
3178{
Glenn Kasten388d5712017-04-07 14:38:41 -07003179 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003180
Eric Laurent81784c32012-11-19 14:55:58 -08003181 Vector< sp<Track> > tracksToRemove;
3182
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003183 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003184 nsecs_t lastWriteFinished = -1; // time last server write completed
3185 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003186
3187 // MIXER
3188 nsecs_t lastWarning = 0;
3189
3190 // DUPLICATING
3191 // FIXME could this be made local to while loop?
3192 writeFrames = 0;
3193
3194 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003195 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003196
3197 if (mType == MIXER) {
3198 sleepTimeShift = 0;
3199 }
3200
3201 CpuStats cpuStats;
3202 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3203
3204 acquireWakeLock();
3205
Glenn Kasteneef598c2017-04-03 14:41:13 -07003206 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3207 // thread associated with this PlaybackThread.
3208 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3209 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003210 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3211 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003212 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003213 const char *logString = NULL;
3214
rago1bb90822017-05-02 18:31:48 -07003215 // Estimated time for next buffer to be written to hal. This is used only on
3216 // suspended mode (for now) to help schedule the wait time until next iteration.
3217 nsecs_t timeLoopNextNs = 0;
3218
Eric Laurent664539d2013-09-23 18:24:31 -07003219 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003220
Andy Hungf3234512018-07-03 14:51:47 -07003221 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3222 // TODO: add confirmation checks:
3223 // 1) DIRECT threads and linear PCM format really resets to 0?
3224 // 2) Is frame count really valid if not linear pcm?
3225 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3226 if (mType == OFFLOAD || mType == DIRECT) {
3227 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3228 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003229 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003230
Eric Laurent81784c32012-11-19 14:55:58 -08003231 while (!exitPending())
3232 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003233 // Log merge requests are performed during AudioFlinger binder transactions, but
3234 // that does not cover audio playback. It's requested here for that reason.
3235 mAudioFlinger->requestLogMerge();
3236
Eric Laurent81784c32012-11-19 14:55:58 -08003237 cpuStats.sample(myName);
3238
3239 Vector< sp<EffectChain> > effectChains;
3240
Andy Hung2dbffc22018-08-08 18:50:41 -07003241 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3242 //
3243 // Note: we access outDevice() outside of mLock.
3244 if (isMsdDevice() && (outDevice() & AUDIO_DEVICE_OUT_BUS) != 0) {
3245 // Here, we try for the AF lock, but do not block on it as the latency
3246 // is more informational.
3247 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3248 std::vector<PatchPanel::SoftwarePatch> swPatches;
3249 double latencyMs;
3250 status_t status = INVALID_OPERATION;
3251 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3252 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3253 && swPatches.size() > 0) {
3254 status = swPatches[0].getLatencyMs_l(&latencyMs);
3255 downstreamPatchHandle = swPatches[0].getPatchHandle();
3256 }
3257 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003258 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003259 lastDownstreamPatchHandle = downstreamPatchHandle;
3260 }
3261 if (status == OK) {
3262 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003263 // latency of 5 seconds).
3264 const double minLatency = 0., maxLatency = 5000.;
3265 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003266 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003267 } else {
3268 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003269 if (latencyMs < minLatency) latencyMs = minLatency;
3270 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003271 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003272 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003273 }
3274 mAudioFlinger->mLock.unlock();
3275 }
3276 } else {
3277 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3278 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003279 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003280 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3281 }
3282 }
3283
Eric Laurent81784c32012-11-19 14:55:58 -08003284 { // scope for mLock
3285
3286 Mutex::Autolock _l(mLock);
3287
Eric Laurent021cf962014-05-13 10:18:14 -07003288 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003289
Glenn Kasteneef598c2017-04-03 14:41:13 -07003290 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003291 if (logString != NULL) {
3292 mNBLogWriter->logTimestamp();
3293 mNBLogWriter->log(logString);
3294 logString = NULL;
3295 }
3296
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003297 // Collect timestamp statistics for the Playback Thread types that support it.
3298 if (mType == MIXER
3299 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003300 || mType == DIRECT
3301 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003302 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003303 // and associate with the sink frames written out. We need
3304 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003305 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003306 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003307 if (mStandby) {
3308 mTimestampVerifier.discontinuity();
3309 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3310 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3311 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3312 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003313
3314 if (isTimestampCorrectionEnabled()) {
3315 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3316 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3317 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3318 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3319 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3320 = correctedTimestamp.mFrames;
3321 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3322 = correctedTimestamp.mTimeNs;
3323 ALOGV("TS_AFTER: %d %lld %lld", id(),
3324 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3325 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003326
3327 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003328 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003329 const int64_t newPosition =
3330 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003331 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003332 // prevent retrograde
3333 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3334 newPosition,
3335 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3336 - mSuspendedFrames));
3337 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003338 }
3339
Andy Hung818e7a32016-02-16 18:08:07 -08003340 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003341 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003342
3343 // We keep track of the last valid kernel position in case we are in underrun
3344 // and the normal mixer period is the same as the fast mixer period, or there
3345 // is some error from the HAL.
3346 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3347 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3348 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3349 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3350 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3351
3352 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3353 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3354 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3355 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003356 }
3357
3358 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3359 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003360 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003361 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003362 }
3363
Andy Hung818e7a32016-02-16 18:08:07 -08003364 // copy over kernel info
3365 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003366 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3367 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003368 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3369 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003370 } else {
3371 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003372 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003373
Andy Hungc54b1ff2016-02-23 14:07:07 -08003374 // mFramesWritten for non-offloaded tracks are contiguous
3375 // even after standby() is called. This is useful for the track frame
3376 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003377 bool serverLocationUpdate = false;
3378 if (mFramesWritten != lastFramesWritten) {
3379 serverLocationUpdate = true;
3380 lastFramesWritten = mFramesWritten;
3381 }
3382 // Only update timestamps if there is a meaningful change.
3383 // Either the kernel timestamp must be valid or we have written something.
3384 if (kernelLocationUpdate || serverLocationUpdate) {
3385 if (serverLocationUpdate) {
3386 // use the time before we called the HAL write - it is a bit more accurate
3387 // to when the server last read data than the current time here.
3388 //
3389 // If we haven't written anything, mLastWriteTime will be -1
3390 // and we use systemTime().
3391 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3392 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3393 ? systemTime() : mLastWriteTime;
3394 }
Andy Hungdae27702016-10-31 14:01:16 -07003395
3396 for (const sp<Track> &t : mActiveTracks) {
3397 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003398 t->updateTrackFrameInfo(
3399 t->mAudioTrackServerProxy->framesReleased(),
3400 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003401 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003402 mTimestamp);
3403 }
Andy Hunge10393e2015-06-12 13:59:33 -07003404 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003405 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003406 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003407#if 0
3408 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003409 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003410 timespec ts;
3411 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003412 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003413 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003414 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003415 }
3416 ++z;
3417#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003418 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003419 if (mSignalPending) {
3420 // A signal was raised while we were unlocked
3421 mSignalPending = false;
3422 } else if (waitingAsyncCallback_l()) {
3423 if (exitPending()) {
3424 break;
3425 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003426 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003427 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003428 releaseWakeLock_l();
3429 released = true;
3430 }
Andy Hung10cbff12017-02-21 17:30:14 -08003431
3432 const int64_t waitNs = computeWaitTimeNs_l();
3433 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3434 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3435 if (status == TIMED_OUT) {
3436 mSignalPending = true; // if timeout recheck everything
3437 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003438 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003439 if (released) {
3440 acquireWakeLock_l();
3441 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003442 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3443 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003444
3445 continue;
3446 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003447 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003448 isSuspended()) {
3449 // put audio hardware into standby after short delay
3450 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003451
3452 threadLoop_standby();
3453
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003454 // This is where we go into standby
3455 if (!mStandby) {
3456 LOG_AUDIO_STATE();
3457 }
Eric Laurent81784c32012-11-19 14:55:58 -08003458 mStandby = true;
3459 }
3460
Eric Tan39ec8d62018-07-24 09:49:29 -07003461 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003462 // we're about to wait, flush the binder command buffer
3463 IPCThreadState::self()->flushCommands();
3464
3465 clearOutputTracks();
3466
3467 if (exitPending()) {
3468 break;
3469 }
3470
3471 releaseWakeLock_l();
3472 // wait until we have something to do...
3473 ALOGV("%s going to sleep", myName.string());
3474 mWaitWorkCV.wait(mLock);
3475 ALOGV("%s waking up", myName.string());
3476 acquireWakeLock_l();
3477
3478 mMixerStatus = MIXER_IDLE;
3479 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3480 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003481 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003482 checkSilentMode_l();
3483
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003484 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3485 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003486 if (mType == MIXER) {
3487 sleepTimeShift = 0;
3488 }
3489
3490 continue;
3491 }
3492 }
Eric Laurent81784c32012-11-19 14:55:58 -08003493 // mMixerStatusIgnoringFastTracks is also updated internally
3494 mMixerStatus = prepareTracks_l(&tracksToRemove);
3495
Andy Hungdae27702016-10-31 14:01:16 -07003496 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003497
Kevin Rocard069c2712018-03-29 19:09:14 -07003498 updateMetadata_l();
3499
Eric Laurent81784c32012-11-19 14:55:58 -08003500 // prevent any changes in effect chain list and in each effect chain
3501 // during mixing and effect process as the audio buffers could be deleted
3502 // or modified if an effect is created or deleted
3503 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003504 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003505
Eric Laurentbfb1b832013-01-07 09:53:42 -08003506 if (mBytesRemaining == 0) {
3507 mCurrentWriteLength = 0;
3508 if (mMixerStatus == MIXER_TRACKS_READY) {
3509 // threadLoop_mix() sets mCurrentWriteLength
3510 threadLoop_mix();
3511 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3512 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003513 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003514 // must be written to HAL
3515 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003516 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003517 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003518 }
3519 }
Andy Hung98ef9782014-03-04 14:46:50 -08003520 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003521 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003522 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3523 // or mSinkBuffer (if there are no effects).
3524 //
3525 // This is done pre-effects computation; if effects change to
3526 // support higher precision, this needs to move.
3527 //
3528 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003529 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003530 if (mMixerBufferValid) {
3531 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3532 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3533
Andy Hung2ddee192015-12-18 17:34:44 -08003534 // mono blend occurs for mixer threads only (not direct or offloaded)
3535 // and is handled here if we're going directly to the sink.
3536 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003537 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3538 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003539 }
3540
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003541 if (!hasFastMixer()) {
3542 // Balance must take effect after mono conversion.
3543 // We do it here if there is no FastMixer.
3544 // mBalance detects zero balance within the class for speed (not needed here).
3545 mBalance.setBalance(mMasterBalance.load());
3546 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3547 }
3548
Andy Hung98ef9782014-03-04 14:46:50 -08003549 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003550 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3551
3552 // If we're going directly to the sink and there are haptic channels,
3553 // we should adjust channels as the sample data is partially interleaved
3554 // in this case.
3555 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3556 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3557 mChannelCount + mHapticChannelCount,
3558 audio_bytes_per_sample(format),
3559 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3560 }
Andy Hung98ef9782014-03-04 14:46:50 -08003561 }
3562
Eric Laurentbfb1b832013-01-07 09:53:42 -08003563 mBytesRemaining = mCurrentWriteLength;
3564 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003565 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3566 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3567 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3568 mBytesWritten += mBytesRemaining;
3569 mFramesWritten += framesRemaining;
3570 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 mBytesRemaining = 0;
3572 }
Eric Laurent81784c32012-11-19 14:55:58 -08003573
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003575 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003576 for (size_t i = 0; i < effectChains.size(); i ++) {
3577 effectChains[i]->process_l();
3578 }
Eric Laurent81784c32012-11-19 14:55:58 -08003579 }
3580 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003581 // Process effect chains for offloaded thread even if no audio
3582 // was read from audio track: process only updates effect state
3583 // and thus does have to be synchronized with audio writes but may have
3584 // to be called while waiting for async write callback
3585 if (mType == OFFLOAD) {
3586 for (size_t i = 0; i < effectChains.size(); i ++) {
3587 effectChains[i]->process_l();
3588 }
3589 }
Eric Laurent81784c32012-11-19 14:55:58 -08003590
Andy Hung98ef9782014-03-04 14:46:50 -08003591 // Only if the Effects buffer is enabled and there is data in the
3592 // Effects buffer (buffer valid), we need to
3593 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003594 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003595 if (mEffectBufferValid) {
3596 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003597
3598 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003599 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3600 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003601 }
3602
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003603 if (!hasFastMixer()) {
3604 // Balance must take effect after mono conversion.
3605 // We do it here if there is no FastMixer.
3606 // mBalance detects zero balance within the class for speed (not needed here).
3607 mBalance.setBalance(mMasterBalance.load());
3608 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3609 }
3610
Andy Hung98ef9782014-03-04 14:46:50 -08003611 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003612 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3613 // The sample data is partially interleaved when haptic channels exist,
3614 // we need to adjust channels here.
3615 if (mHapticChannelCount > 0) {
3616 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3617 mChannelCount + mHapticChannelCount,
3618 audio_bytes_per_sample(mFormat),
3619 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3620 }
Andy Hung98ef9782014-03-04 14:46:50 -08003621 }
3622
Eric Laurent81784c32012-11-19 14:55:58 -08003623 // enable changes in effect chain
3624 unlockEffectChains(effectChains);
3625
Eric Laurentbfb1b832013-01-07 09:53:42 -08003626 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003627 // mSleepTimeUs == 0 means we must write to audio hardware
3628 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003629 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003630 // We save lastWriteFinished here, as previousLastWriteFinished,
3631 // for throttling. On thread start, previousLastWriteFinished will be
3632 // set to -1, which properly results in no throttling after the first write.
3633 nsecs_t previousLastWriteFinished = lastWriteFinished;
3634 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003635 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003636 // FIXME rewrite to reduce number of system calls
3637 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003638 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003639 lastWriteFinished = systemTime();
3640 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003641 if (ret < 0) {
3642 mBytesRemaining = 0;
3643 } else {
3644 mBytesWritten += ret;
3645 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003646 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003647 }
3648 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3649 (mMixerStatus == MIXER_DRAIN_ALL)) {
3650 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003651 }
Andy Hung08fb1742015-05-31 23:22:10 -07003652 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003653 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003654 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003655 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003656 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003657 ATRACE_NAME("underrun");
3658 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003659 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003660 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003661 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003662 }
Andy Hung08fb1742015-05-31 23:22:10 -07003663
3664 if (mThreadThrottle
3665 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3666 && ret > 0) { // we wrote something
3667 // Limit MixerThread data processing to no more than twice the
3668 // expected processing rate.
3669 //
3670 // This helps prevent underruns with NuPlayer and other applications
3671 // which may set up buffers that are close to the minimum size, or use
3672 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3673 //
3674 // The throttle smooths out sudden large data drains from the device,
3675 // e.g. when it comes out of standby, which often causes problems with
3676 // (1) mixer threads without a fast mixer (which has its own warm-up)
3677 // (2) minimum buffer sized tracks (even if the track is full,
3678 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003679 //
3680 // Total time spent in last processing cycle equals time spent in
3681 // 1. threadLoop_write, as well as time spent in
3682 // 2. threadLoop_mix (significant for heavy mixing, especially
3683 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003684
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003685 // it's OK if deltaMs (and deltaNs) is an overestimate.
3686 nsecs_t deltaNs;
3687 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3688 __builtin_sub_overflow(
3689 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3690 const int32_t deltaMs = deltaNs / 1000000;
3691
Ivan Lozanoea04d392017-11-07 14:37:07 -08003692 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003693 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3694 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003695 // notify of throttle start on verbose log
3696 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3697 "mixer(%p) throttle begin:"
3698 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003699 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003700 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003701 // Throttle must be attributed to the previous mixer loop's write time
3702 // to allow back-to-back throttling.
3703 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003704 } else {
3705 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3706 if (diff > 0) {
3707 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003708 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003709 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3710 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003711 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003712 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3713 }
Andy Hung08fb1742015-05-31 23:22:10 -07003714 }
3715 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003716 }
Eric Laurent81784c32012-11-19 14:55:58 -08003717
Eric Laurentbfb1b832013-01-07 09:53:42 -08003718 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003719 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003720 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003721 // suspended requires accurate metering of sleep time.
3722 if (isSuspended()) {
3723 // advance by expected sleepTime
3724 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3725 const nsecs_t nowNs = systemTime();
3726
3727 // compute expected next time vs current time.
3728 // (negative deltas are treated as delays).
3729 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3730 if (deltaNs < -kMaxNextBufferDelayNs) {
3731 // Delays longer than the max allowed trigger a reset.
3732 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3733 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3734 timeLoopNextNs = nowNs + deltaNs;
3735 } else if (deltaNs < 0) {
3736 // Delays within the max delay allowed: zero the delta/sleepTime
3737 // to help the system catch up in the next iteration(s)
3738 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3739 deltaNs = 0;
3740 }
3741 // update sleep time (which is >= 0)
3742 mSleepTimeUs = deltaNs / 1000;
3743 }
Eric Laurente93cc032016-05-05 10:15:10 -07003744 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3745 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003746 }
Glenn Kastene7754022014-10-31 12:11:26 -07003747 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003748 }
Eric Laurent81784c32012-11-19 14:55:58 -08003749 }
3750
3751 // Finally let go of removed track(s), without the lock held
3752 // since we can't guarantee the destructors won't acquire that
3753 // same lock. This will also mutate and push a new fast mixer state.
3754 threadLoop_removeTracks(tracksToRemove);
3755 tracksToRemove.clear();
3756
3757 // FIXME I don't understand the need for this here;
3758 // it was in the original code but maybe the
3759 // assignment in saveOutputTracks() makes this unnecessary?
3760 clearOutputTracks();
3761
3762 // Effect chains will be actually deleted here if they were removed from
3763 // mEffectChains list during mixing or effects processing
3764 effectChains.clear();
3765
3766 // FIXME Note that the above .clear() is no longer necessary since effectChains
3767 // is now local to this block, but will keep it for now (at least until merge done).
3768 }
3769
Eric Laurentbfb1b832013-01-07 09:53:42 -08003770 threadLoop_exit();
3771
Eric Laurentcf817a22014-08-04 20:36:31 -07003772 if (!mStandby) {
3773 threadLoop_standby();
3774 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003775 }
3776
3777 releaseWakeLock();
3778
3779 ALOGV("Thread %p type %d exiting", this, mType);
3780 return false;
3781}
3782
Eric Laurentbfb1b832013-01-07 09:53:42 -08003783// removeTracks_l() must be called with ThreadBase::mLock held
3784void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3785{
jiabin245cdd92018-12-07 17:55:15 -08003786 bool enabledHapticTracksRemoved = false;
Andy Hungfe726a62018-09-27 15:17:25 -07003787 for (const auto& track : tracksToRemove) {
3788 mActiveTracks.remove(track);
3789 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3790 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3791 if (chain != 0) {
3792 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3793 __func__, track->id(), chain.get(), track->sessionId());
3794 chain->decActiveTrackCnt();
3795 }
3796 // If an external client track, inform APM we're no longer active, and remove if needed.
3797 // We do this under lock so that the state is consistent if the Track is destroyed.
3798 if (track->isExternalTrack()) {
3799 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003800 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003801 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003802 }
3803 }
Andy Hungfe726a62018-09-27 15:17:25 -07003804 if (track->isTerminated()) {
3805 // remove from our tracks vector
3806 removeTrack_l(track);
3807 }
jiabin245cdd92018-12-07 17:55:15 -08003808 enabledHapticTracksRemoved |= track->getHapticPlaybackEnabled();
3809 }
3810 // If the thread supports haptic playback and the track playing haptic data was removed,
3811 // enable haptic playback on the first active track that contains haptic channels.
3812 // TODO: Query vibrator service to know which track should enable haptic playback.
3813 if (enabledHapticTracksRemoved && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
3814 for (auto &t : mActiveTracks) {
3815 if (t->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) {
3816 t->setHapticPlaybackEnabled(true);
3817 break;
3818 }
3819 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003820 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003821}
Eric Laurent81784c32012-11-19 14:55:58 -08003822
Eric Laurentaccc1472013-09-20 09:36:34 -07003823status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3824{
3825 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003826 ExtendedTimestamp ets;
3827 status_t status = mNormalSink->getTimestamp(ets);
3828 if (status == NO_ERROR) {
3829 status = ets.getBestTimestamp(&timestamp);
3830 }
3831 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003832 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003833 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003834 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003835 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003836 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11003837 if (mDownstreamLatencyStatMs.getN() > 0) {
3838 const uint32_t positionOffset =
3839 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3840 if (positionOffset > timestamp.mPosition) {
3841 timestamp.mPosition = 0;
3842 } else {
3843 timestamp.mPosition -= positionOffset;
3844 }
3845 }
Eric Laurentaccc1472013-09-20 09:36:34 -07003846 return NO_ERROR;
3847 }
3848 }
3849 return INVALID_OPERATION;
3850}
Eric Laurent1c333e22014-05-20 10:48:17 -07003851
Eric Laurent054d9d32015-04-24 08:48:48 -07003852status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3853 audio_patch_handle_t *handle)
3854{
Andy Hungf60abce2016-08-26 11:37:54 -07003855 status_t status;
3856 if (property_get_bool("af.patch_park", false /* default_value */)) {
3857 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3858 // or if HAL does not properly lock against access.
3859 AutoPark<FastMixer> park(mFastMixer);
3860 status = PlaybackThread::createAudioPatch_l(patch, handle);
3861 } else {
3862 status = PlaybackThread::createAudioPatch_l(patch, handle);
3863 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003864 return status;
3865}
3866
Eric Laurent1c333e22014-05-20 10:48:17 -07003867status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3868 audio_patch_handle_t *handle)
3869{
3870 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003871
3872 // store new device and send to effects
3873 audio_devices_t type = AUDIO_DEVICE_NONE;
3874 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3875 type |= patch->sinks[i].ext.device.type;
3876 }
3877
François Gaffie0c280aa2018-07-25 10:02:15 +02003878 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07003879#ifdef ADD_BATTERY_DATA
3880 // when changing the audio output device, call addBatteryData to notify
3881 // the change
3882 if (mOutDevice != type) {
3883 uint32_t params = 0;
3884 // check whether speaker is on
3885 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3886 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003887 }
3888
Eric Laurent054d9d32015-04-24 08:48:48 -07003889 audio_devices_t deviceWithoutSpeaker
3890 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3891 // check if any other device (except speaker) is on
3892 if (type & deviceWithoutSpeaker) {
3893 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3894 }
3895
3896 if (params != 0) {
3897 addBatteryData(params);
3898 }
3899 }
3900#endif
3901
3902 for (size_t i = 0; i < mEffectChains.size(); i++) {
3903 mEffectChains[i]->setDevice_l(type);
3904 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003905
3906 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3907 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
François Gaffie0c280aa2018-07-25 10:02:15 +02003908 bool configChanged = (mPrevOutDevice != type) || (mDeviceId != sinkPortId);
Eric Laurent054d9d32015-04-24 08:48:48 -07003909 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003910 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003911
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003912 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003913 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3914 status = hwDevice->createAudioPatch(patch->num_sources,
3915 patch->sources,
3916 patch->num_sinks,
3917 patch->sinks,
3918 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003919 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003920 char *address;
3921 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3922 //FIXME: we only support address on first sink with HAL version < 3.0
3923 address = audio_device_address_to_parameter(
3924 patch->sinks[0].ext.device.type,
3925 patch->sinks[0].ext.device.address);
3926 } else {
3927 address = (char *)calloc(1, 1);
3928 }
3929 AudioParameter param = AudioParameter(String8(address));
3930 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003931 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003932 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003933 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003934 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003935 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003936 mPrevOutDevice = type;
François Gaffie0c280aa2018-07-25 10:02:15 +02003937 mDeviceId = sinkPortId;
Eric Laurente8726fe2015-06-26 09:39:24 -07003938 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3939 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003940 return status;
3941}
3942
Eric Laurent054d9d32015-04-24 08:48:48 -07003943status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3944{
Andy Hungf60abce2016-08-26 11:37:54 -07003945 status_t status;
3946 if (property_get_bool("af.patch_park", false /* default_value */)) {
3947 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3948 // or if HAL does not properly lock against access.
3949 AutoPark<FastMixer> park(mFastMixer);
3950 status = PlaybackThread::releaseAudioPatch_l(handle);
3951 } else {
3952 status = PlaybackThread::releaseAudioPatch_l(handle);
3953 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003954 return status;
3955}
3956
Eric Laurent1c333e22014-05-20 10:48:17 -07003957status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3958{
3959 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003960
3961 mOutDevice = AUDIO_DEVICE_NONE;
3962
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003963 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003964 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3965 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003966 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003967 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003968 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003969 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003970 }
3971 return status;
3972}
3973
Eric Laurent83b88082014-06-20 18:31:16 -07003974void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3975{
3976 Mutex::Autolock _l(mLock);
3977 mTracks.add(track);
3978}
3979
3980void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3981{
3982 Mutex::Autolock _l(mLock);
3983 destroyTrack_l(track);
3984}
3985
Mikhail Naganovdc769682018-05-04 15:34:08 -07003986void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003987{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003988 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003989 config->role = AUDIO_PORT_ROLE_SOURCE;
3990 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3991 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003992 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3993 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3994 config->flags.output = mOutput->flags;
3995 }
Eric Laurent83b88082014-06-20 18:31:16 -07003996}
3997
Eric Laurent81784c32012-11-19 14:55:58 -08003998// ----------------------------------------------------------------------------
3999
4000AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07004001 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
4002 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004003 // mAudioMixer below
4004 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004005 mFastMixerFutex(0),
4006 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004007 // mOutputSink below
4008 // mPipeSink below
4009 // mNormalSink below
4010{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004011 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08004012 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004013 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004014 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004015 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4016 mNormalFrameCount);
4017 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4018
Andy Hungfbfc3952015-01-15 13:33:51 -08004019 if (type == DUPLICATING) {
4020 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4021 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4022 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4023 return;
4024 }
Eric Laurent81784c32012-11-19 14:55:58 -08004025 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004026 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004027 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004028 const NBAIO_Format offers[1] = {Format_from_SR_C(
4029 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004030#if !LOG_NDEBUG
4031 ssize_t index =
4032#else
4033 (void)
4034#endif
4035 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004036 ALOG_ASSERT(index == 0);
4037
4038 // initialize fast mixer depending on configuration
4039 bool initFastMixer;
4040 switch (kUseFastMixer) {
4041 case FastMixer_Never:
4042 initFastMixer = false;
4043 break;
4044 case FastMixer_Always:
4045 initFastMixer = true;
4046 break;
4047 case FastMixer_Static:
4048 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004049 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4050 // where the period is less than an experimentally determined threshold that can be
4051 // scheduled reliably with CFS. However, the BT A2DP HAL is
4052 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4053 initFastMixer = mFrameCount < mNormalFrameCount
4054 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004055 break;
4056 }
Andy Hungfda69402017-02-15 14:33:12 -08004057 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4058 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4059 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004060 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004061 audio_format_t fastMixerFormat;
4062 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4063 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4064 } else {
4065 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4066 }
4067 if (mFormat != fastMixerFormat) {
4068 // change our Sink format to accept our intermediate precision
4069 mFormat = fastMixerFormat;
4070 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004071 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004072 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4073 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4074 }
Eric Laurent81784c32012-11-19 14:55:58 -08004075
4076 // create a MonoPipe to connect our submix to FastMixer
4077 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004078
Andy Hung1258c1a2014-05-23 21:22:17 -07004079 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004080 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004081 format.mFormat = fastMixerFormat;
4082 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4083
Eric Laurent81784c32012-11-19 14:55:58 -08004084 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4085 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4086 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4087 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4088 const NBAIO_Format offers[1] = {format};
4089 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004090#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004091 ssize_t index =
4092#else
4093 (void)
4094#endif
4095 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004096 ALOG_ASSERT(index == 0);
4097 monoPipe->setAvgFrames((mScreenState & 1) ?
4098 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4099 mPipeSink = monoPipe;
4100
Eric Laurent81784c32012-11-19 14:55:58 -08004101 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004102 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004103 FastMixerStateQueue *sq = mFastMixer->sq();
4104#ifdef STATE_QUEUE_DUMP
4105 sq->setObserverDump(&mStateQueueObserverDump);
4106 sq->setMutatorDump(&mStateQueueMutatorDump);
4107#endif
4108 FastMixerState *state = sq->begin();
4109 FastTrack *fastTrack = &state->mFastTracks[0];
4110 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4111 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4112 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004113 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4114 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004115 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004116 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004117 fastTrack->mGeneration++;
4118 state->mFastTracksGen++;
4119 state->mTrackMask = 1;
4120 // fast mixer will use the HAL output sink
4121 state->mOutputSink = mOutputSink.get();
4122 state->mOutputSinkGen++;
4123 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004124 // specify sink channel mask when haptic channel mask present as it can not
4125 // be calculated directly from channel count
4126 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4127 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004128 state->mCommand = FastMixerState::COLD_IDLE;
4129 // already done in constructor initialization list
4130 //mFastMixerFutex = 0;
4131 state->mColdFutexAddr = &mFastMixerFutex;
4132 state->mColdGen++;
4133 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004134 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4135 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004136 sq->end();
4137 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4138
Eric Tan0513b5d2018-09-17 10:32:48 -07004139 NBLog::thread_info_t info;
4140 info.id = mId;
4141 info.type = NBLog::FASTMIXER;
4142 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4143
Eric Laurent81784c32012-11-19 14:55:58 -08004144 // start the fast mixer
4145 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4146 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004147 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004148 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004149
4150#ifdef AUDIO_WATCHDOG
4151 // create and start the watchdog
4152 mAudioWatchdog = new AudioWatchdog();
4153 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4154 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4155 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004156 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004157#endif
Andy Hung8946a282018-04-19 20:04:56 -07004158 } else {
4159#ifdef TEE_SINK
4160 // Only use the MixerThread tee if there is no FastMixer.
4161 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4162 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4163#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004164 }
4165
4166 switch (kUseFastMixer) {
4167 case FastMixer_Never:
4168 case FastMixer_Dynamic:
4169 mNormalSink = mOutputSink;
4170 break;
4171 case FastMixer_Always:
4172 mNormalSink = mPipeSink;
4173 break;
4174 case FastMixer_Static:
4175 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4176 break;
4177 }
4178}
4179
4180AudioFlinger::MixerThread::~MixerThread()
4181{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004182 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004183 FastMixerStateQueue *sq = mFastMixer->sq();
4184 FastMixerState *state = sq->begin();
4185 if (state->mCommand == FastMixerState::COLD_IDLE) {
4186 int32_t old = android_atomic_inc(&mFastMixerFutex);
4187 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004188 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004189 }
4190 }
4191 state->mCommand = FastMixerState::EXIT;
4192 sq->end();
4193 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4194 mFastMixer->join();
4195 // Though the fast mixer thread has exited, it's state queue is still valid.
4196 // We'll use that extract the final state which contains one remaining fast track
4197 // corresponding to our sub-mix.
4198 state = sq->begin();
4199 ALOG_ASSERT(state->mTrackMask == 1);
4200 FastTrack *fastTrack = &state->mFastTracks[0];
4201 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4202 delete fastTrack->mBufferProvider;
4203 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004204 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004205#ifdef AUDIO_WATCHDOG
4206 if (mAudioWatchdog != 0) {
4207 mAudioWatchdog->requestExit();
4208 mAudioWatchdog->requestExitAndWait();
4209 mAudioWatchdog.clear();
4210 }
4211#endif
4212 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004213 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004214 delete mAudioMixer;
4215}
4216
4217
4218uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4219{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004220 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004221 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4222 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4223 }
4224 return latency;
4225}
4226
Eric Laurentbfb1b832013-01-07 09:53:42 -08004227ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004228{
4229 // FIXME we should only do one push per cycle; confirm this is true
4230 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004231 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004232 FastMixerStateQueue *sq = mFastMixer->sq();
4233 FastMixerState *state = sq->begin();
4234 if (state->mCommand != FastMixerState::MIX_WRITE &&
4235 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4236 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004237
4238 // FIXME workaround for first HAL write being CPU bound on some devices
4239 ATRACE_BEGIN("write");
4240 mOutput->write((char *)mSinkBuffer, 0);
4241 ATRACE_END();
4242
Eric Laurent81784c32012-11-19 14:55:58 -08004243 int32_t old = android_atomic_inc(&mFastMixerFutex);
4244 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004245 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004246 }
4247#ifdef AUDIO_WATCHDOG
4248 if (mAudioWatchdog != 0) {
4249 mAudioWatchdog->resume();
4250 }
4251#endif
4252 }
4253 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004254#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004255 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004256 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004257#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004258 sq->end();
4259 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4260 if (kUseFastMixer == FastMixer_Dynamic) {
4261 mNormalSink = mPipeSink;
4262 }
4263 } else {
4264 sq->end(false /*didModify*/);
4265 }
4266 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004267 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004268}
4269
4270void AudioFlinger::MixerThread::threadLoop_standby()
4271{
4272 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004273 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004274 FastMixerStateQueue *sq = mFastMixer->sq();
4275 FastMixerState *state = sq->begin();
4276 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004277 // Report any frames trapped in the Monopipe
4278 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4279 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4280 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4281 "monoPipeWritten:%lld monoPipeLeft:%lld",
4282 (long long)mFramesWritten, (long long)mSuspendedFrames,
4283 (long long)mPipeSink->framesWritten(), pipeFrames);
4284 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4285
Eric Laurent81784c32012-11-19 14:55:58 -08004286 state->mCommand = FastMixerState::COLD_IDLE;
4287 state->mColdFutexAddr = &mFastMixerFutex;
4288 state->mColdGen++;
4289 mFastMixerFutex = 0;
4290 sq->end();
4291 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4292 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4293 if (kUseFastMixer == FastMixer_Dynamic) {
4294 mNormalSink = mOutputSink;
4295 }
4296#ifdef AUDIO_WATCHDOG
4297 if (mAudioWatchdog != 0) {
4298 mAudioWatchdog->pause();
4299 }
4300#endif
4301 } else {
4302 sq->end(false /*didModify*/);
4303 }
4304 }
4305 PlaybackThread::threadLoop_standby();
4306}
4307
Eric Laurentbfb1b832013-01-07 09:53:42 -08004308bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4309{
4310 return false;
4311}
4312
4313bool AudioFlinger::PlaybackThread::shouldStandby_l()
4314{
4315 return !mStandby;
4316}
4317
4318bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4319{
4320 Mutex::Autolock _l(mLock);
4321 return waitingAsyncCallback_l();
4322}
4323
Eric Laurent81784c32012-11-19 14:55:58 -08004324// shared by MIXER and DIRECT, overridden by DUPLICATING
4325void AudioFlinger::PlaybackThread::threadLoop_standby()
4326{
4327 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004328 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004329 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004330 // discard any pending drain or write ack by incrementing sequence
4331 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4332 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004333 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004334 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4335 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004336 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004337 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004338}
4339
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004340void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4341{
4342 ALOGV("signal playback thread");
4343 broadcast_l();
4344}
4345
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004346void AudioFlinger::PlaybackThread::onAsyncError()
4347{
4348 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4349 invalidateTracks((audio_stream_type_t)i);
4350 }
4351}
4352
Eric Laurent81784c32012-11-19 14:55:58 -08004353void AudioFlinger::MixerThread::threadLoop_mix()
4354{
Eric Laurent81784c32012-11-19 14:55:58 -08004355 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004356 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004357 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004358 // increase sleep time progressively when application underrun condition clears.
4359 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4360 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4361 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004362 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004363 sleepTimeShift--;
4364 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004365 mSleepTimeUs = 0;
4366 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004367 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004368
Eric Laurent81784c32012-11-19 14:55:58 -08004369}
4370
4371void AudioFlinger::MixerThread::threadLoop_sleepTime()
4372{
4373 // If no tracks are ready, sleep once for the duration of an output
4374 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004375 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004376 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004377 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4378 // Using the Monopipe availableToWrite, we estimate the
4379 // sleep time to retry for more data (before we underrun).
4380 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4381 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4382 const size_t pipeFrames = monoPipe->maxFrames();
4383 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4384 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4385 const size_t framesDelay = std::min(
4386 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4387 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4388 pipeFrames, framesLeft, framesDelay);
4389 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4390 } else {
4391 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4392 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4393 mSleepTimeUs = kMinThreadSleepTimeUs;
4394 }
4395 // reduce sleep time in case of consecutive application underruns to avoid
4396 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4397 // duration we would end up writing less data than needed by the audio HAL if
4398 // the condition persists.
4399 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4400 sleepTimeShift++;
4401 }
Eric Laurent81784c32012-11-19 14:55:58 -08004402 }
4403 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004404 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004405 }
4406 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004407 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4408 // before effects processing or output.
4409 if (mMixerBufferValid) {
4410 memset(mMixerBuffer, 0, mMixerBufferSize);
4411 } else {
4412 memset(mSinkBuffer, 0, mSinkBufferSize);
4413 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004414 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004415 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4416 "anticipated start");
4417 }
4418 // TODO add standby time extension fct of effect tail
4419}
4420
4421// prepareTracks_l() must be called with ThreadBase::mLock held
4422AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4423 Vector< sp<Track> > *tracksToRemove)
4424{
Andy Hungc0691382018-09-12 18:01:57 -07004425 // clean up deleted track ids in AudioMixer before allocating new tracks
4426 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4427 // for each trackId, destroy it in the AudioMixer
4428 if (mAudioMixer->exists(trackId)) {
4429 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004430 }
4431 });
Andy Hungc0691382018-09-12 18:01:57 -07004432 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004433
4434 mixer_state mixerStatus = MIXER_IDLE;
4435 // find out which tracks need to be processed
4436 size_t count = mActiveTracks.size();
4437 size_t mixedTracks = 0;
4438 size_t tracksWithEffect = 0;
4439 // counts only _active_ fast tracks
4440 size_t fastTracks = 0;
4441 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4442
4443 float masterVolume = mMasterVolume;
4444 bool masterMute = mMasterMute;
4445
4446 if (masterMute) {
4447 masterVolume = 0;
4448 }
4449 // Delegate master volume control to effect in output mix effect chain if needed
4450 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4451 if (chain != 0) {
4452 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4453 chain->setVolume_l(&v, &v);
4454 masterVolume = (float)((v + (1 << 23)) >> 24);
4455 chain.clear();
4456 }
4457
4458 // prepare a new state to push
4459 FastMixerStateQueue *sq = NULL;
4460 FastMixerState *state = NULL;
4461 bool didModify = false;
4462 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004463 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004464 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004465 sq = mFastMixer->sq();
4466 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004467 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004468 }
4469
Andy Hung69aed5f2014-02-25 17:24:40 -08004470 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004471 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004472
Andy Hungbd3b2b02018-05-21 10:53:11 -07004473 // DeferredOperations handles statistics after setting mixerStatus.
4474 class DeferredOperations {
4475 public:
4476 DeferredOperations(mixer_state *mixerStatus)
4477 : mMixerStatus(mixerStatus) { }
4478
4479 // when leaving scope, tally frames properly.
4480 ~DeferredOperations() {
4481 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4482 // because that is when the underrun occurs.
4483 // We do not distinguish between FastTracks and NormalTracks here.
4484 if (*mMixerStatus == MIXER_TRACKS_READY) {
4485 for (const auto &underrun : mUnderrunFrames) {
4486 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4487 underrun.second);
4488 }
4489 }
4490 }
4491
4492 // tallyUnderrunFrames() is called to update the track counters
4493 // with the number of underrun frames for a particular mixer period.
4494 // We defer tallying until we know the final mixer status.
4495 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4496 mUnderrunFrames.emplace_back(track, underrunFrames);
4497 }
4498
4499 private:
4500 const mixer_state * const mMixerStatus;
4501 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4502 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4503
jiabin245cdd92018-12-07 17:55:15 -08004504 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004505 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004506 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004507
4508 // this const just means the local variable doesn't change
4509 Track* const track = t.get();
4510
4511 // process fast tracks
4512 if (track->isFastTrack()) {
jiabin245cdd92018-12-07 17:55:15 -08004513 if (track->getHapticPlaybackEnabled()) {
4514 noFastHapticTrack = false;
4515 }
Eric Laurent81784c32012-11-19 14:55:58 -08004516
4517 // It's theoretically possible (though unlikely) for a fast track to be created
4518 // and then removed within the same normal mix cycle. This is not a problem, as
4519 // the track never becomes active so it's fast mixer slot is never touched.
4520 // The converse, of removing an (active) track and then creating a new track
4521 // at the identical fast mixer slot within the same normal mix cycle,
4522 // is impossible because the slot isn't marked available until the end of each cycle.
4523 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004524 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004525 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4526 FastTrack *fastTrack = &state->mFastTracks[j];
4527
4528 // Determine whether the track is currently in underrun condition,
4529 // and whether it had a recent underrun.
4530 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4531 FastTrackUnderruns underruns = ftDump->mUnderruns;
4532 uint32_t recentFull = (underruns.mBitFields.mFull -
4533 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4534 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4535 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4536 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4537 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4538 uint32_t recentUnderruns = recentPartial + recentEmpty;
4539 track->mObservedUnderruns = underruns;
4540 // don't count underruns that occur while stopping or pausing
4541 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004542 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004543 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4544 recentUnderruns > 0) {
4545 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004546 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004547 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004548 // Immediately account for FastTrack underruns.
4549 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004550
4551 // This is similar to the state machine for normal tracks,
4552 // with a few modifications for fast tracks.
4553 bool isActive = true;
4554 switch (track->mState) {
4555 case TrackBase::STOPPING_1:
4556 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004557 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004558 track->mState = TrackBase::STOPPING_2;
4559 }
4560 break;
4561 case TrackBase::PAUSING:
4562 // ramp down is not yet implemented
4563 track->setPaused();
4564 break;
4565 case TrackBase::RESUMING:
4566 // ramp up is not yet implemented
4567 track->mState = TrackBase::ACTIVE;
4568 break;
4569 case TrackBase::ACTIVE:
4570 if (recentFull > 0 || recentPartial > 0) {
4571 // track has provided at least some frames recently: reset retry count
4572 track->mRetryCount = kMaxTrackRetries;
4573 }
4574 if (recentUnderruns == 0) {
4575 // no recent underruns: stay active
4576 break;
4577 }
4578 // there has recently been an underrun of some kind
4579 if (track->sharedBuffer() == 0) {
4580 // were any of the recent underruns "empty" (no frames available)?
4581 if (recentEmpty == 0) {
4582 // no, then ignore the partial underruns as they are allowed indefinitely
4583 break;
4584 }
4585 // there has recently been an "empty" underrun: decrement the retry counter
4586 if (--(track->mRetryCount) > 0) {
4587 break;
4588 }
4589 // indicate to client process that the track was disabled because of underrun;
4590 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004591 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004592 // remove from active list, but state remains ACTIVE [confusing but true]
4593 isActive = false;
4594 break;
4595 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004596 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004597 case TrackBase::STOPPING_2:
4598 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004599 case TrackBase::STOPPED:
4600 case TrackBase::FLUSHED: // flush() while active
4601 // Check for presentation complete if track is inactive
4602 // We have consumed all the buffers of this track.
4603 // This would be incomplete if we auto-paused on underrun
4604 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004605 uint32_t latency = 0;
4606 status_t result = mOutput->stream->getLatency(&latency);
4607 ALOGE_IF(result != OK,
4608 "Error when retrieving output stream latency: %d", result);
4609 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004610 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004611 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4612 // track stays in active list until presentation is complete
4613 break;
4614 }
4615 }
4616 if (track->isStopping_2()) {
4617 track->mState = TrackBase::STOPPED;
4618 }
4619 if (track->isStopped()) {
4620 // Can't reset directly, as fast mixer is still polling this track
4621 // track->reset();
4622 // So instead mark this track as needing to be reset after push with ack
4623 resetMask |= 1 << i;
4624 }
4625 isActive = false;
4626 break;
4627 case TrackBase::IDLE:
4628 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004629 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004630 }
4631
4632 if (isActive) {
4633 // was it previously inactive?
4634 if (!(state->mTrackMask & (1 << j))) {
4635 ExtendedAudioBufferProvider *eabp = track;
4636 VolumeProvider *vp = track;
4637 fastTrack->mBufferProvider = eabp;
4638 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004639 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004640 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08004641 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Eric Laurent81784c32012-11-19 14:55:58 -08004642 fastTrack->mGeneration++;
4643 state->mTrackMask |= 1 << j;
4644 didModify = true;
4645 // no acknowledgement required for newly active tracks
4646 }
Kevin Rocard12381092018-04-11 09:19:59 -07004647 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004648 // cache the combined master volume and stream type volume for fast mixer; this
4649 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004650 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004651 proxy->framesReleased()).first;
4652 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004653 * mStreamTypes[track->streamType()].volume
4654 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004655 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004656 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4657 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4658 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4659 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004660 ++fastTracks;
4661 } else {
4662 // was it previously active?
4663 if (state->mTrackMask & (1 << j)) {
4664 fastTrack->mBufferProvider = NULL;
4665 fastTrack->mGeneration++;
4666 state->mTrackMask &= ~(1 << j);
4667 didModify = true;
4668 // If any fast tracks were removed, we must wait for acknowledgement
4669 // because we're about to decrement the last sp<> on those tracks.
4670 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4671 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004672 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4673 // AudioTrack may start (which may not be with a start() but with a write()
4674 // after underrun) and immediately paused or released. In that case the
4675 // FastTrack state hasn't had time to update.
4676 // TODO Remove the ALOGW when this theory is confirmed.
4677 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004678 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4679 j, track->mState, state->mTrackMask, recentUnderruns,
4680 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004681 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004682 }
4683 tracksToRemove->add(track);
4684 // Avoids a misleading display in dumpsys
4685 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4686 }
jiabin245cdd92018-12-07 17:55:15 -08004687 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
4688 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
4689 didModify = true;
4690 }
Eric Laurent81784c32012-11-19 14:55:58 -08004691 continue;
4692 }
4693
4694 { // local variable scope to avoid goto warning
4695
4696 audio_track_cblk_t* cblk = track->cblk();
4697
4698 // The first time a track is added we wait
4699 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004700 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004701
4702 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004703 // use the trackId as the AudioMixer name.
4704 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004705 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004706 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004707 track->mChannelMask,
4708 track->mFormat,
4709 track->mSessionId);
4710 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004711 ALOGW("%s(): AudioMixer cannot create track(%d)"
4712 " mask %#x, format %#x, sessionId %d",
4713 __func__, trackId,
4714 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004715 tracksToRemove->add(track);
4716 track->invalidate(); // consider it dead.
4717 continue;
4718 }
4719 }
4720
Eric Laurent81784c32012-11-19 14:55:58 -08004721 // make sure that we have enough frames to mix one full buffer.
4722 // enforce this condition only once to enable draining the buffer in case the client
4723 // app does not call stop() and relies on underrun to stop:
4724 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4725 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004726 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004727 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004728 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004729
4730 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004731 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004732 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4733 // add frames already consumed but not yet released by the resampler
4734 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004735 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004736
Eric Laurent81784c32012-11-19 14:55:58 -08004737 uint32_t minFrames = 1;
4738 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4739 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004740 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004741 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004742
4743 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004744 if (ATRACE_ENABLED()) {
4745 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004746 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004747 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004748 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004749 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004750 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004751 !track->isPaused() && !track->isTerminated())
4752 {
Andy Hungc0691382018-09-12 18:01:57 -07004753 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004754
4755 mixedTracks++;
4756
Andy Hung69aed5f2014-02-25 17:24:40 -08004757 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4758 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004759 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004760 if (track->mainBuffer() != mSinkBuffer &&
4761 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004762 if (mEffectBufferEnabled) {
4763 mEffectBufferValid = true; // Later can set directly.
4764 }
Eric Laurent81784c32012-11-19 14:55:58 -08004765 chain = getEffectChain_l(track->sessionId());
4766 // Delegate volume control to effect in track effect chain if needed
4767 if (chain != 0) {
4768 tracksWithEffect++;
4769 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004770 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004771 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004772 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004773 }
4774 }
4775
4776
4777 int param = AudioMixer::VOLUME;
4778 if (track->mFillingUpStatus == Track::FS_FILLED) {
4779 // no ramp for the first volume setting
4780 track->mFillingUpStatus = Track::FS_ACTIVE;
4781 if (track->mState == TrackBase::RESUMING) {
4782 track->mState = TrackBase::ACTIVE;
4783 param = AudioMixer::RAMP_VOLUME;
4784 }
Andy Hungc0691382018-09-12 18:01:57 -07004785 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004786 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004787 // FIXME should not make a decision based on mServer
4788 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004789 // If the track is stopped before the first frame was mixed,
4790 // do not apply ramp
4791 param = AudioMixer::RAMP_VOLUME;
4792 }
4793
4794 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004795 uint32_t vl, vr; // in U8.24 integer format
4796 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004797 // read original volumes with volume control
4798 float typeVolume = mStreamTypes[track->streamType()].volume;
4799 float v = masterVolume * typeVolume;
4800
Glenn Kastene4756fe2012-11-29 13:38:14 -08004801 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004802 vl = vr = 0;
4803 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004804 if (track->isPausing()) {
4805 track->setPaused();
4806 }
4807 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004808 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004809 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004810 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4811 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004812 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004813 if (vlf > GAIN_FLOAT_UNITY) {
4814 ALOGV("Track left volume out of range: %.3g", vlf);
4815 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004816 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004817 if (vrf > GAIN_FLOAT_UNITY) {
4818 ALOGV("Track right volume out of range: %.3g", vrf);
4819 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004820 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004821 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004822 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004823 // now apply the master volume and stream type volume and shaper volume
4824 vlf *= v * vh;
4825 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004826 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004827 // then derive vl and vr as U8.24 versions for the effect chain
4828 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4829 vl = (uint32_t) (scaleto8_24 * vlf);
4830 vr = (uint32_t) (scaleto8_24 * vrf);
4831 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004832 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004833 // send level comes from shared memory and so may be corrupt
4834 if (sendLevel > MAX_GAIN_INT) {
4835 ALOGV("Track send level out of range: %04X", sendLevel);
4836 sendLevel = MAX_GAIN_INT;
4837 }
Andy Hung6be49402014-05-30 10:42:03 -07004838 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4839 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004840 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004841
Kevin Rocard12381092018-04-11 09:19:59 -07004842 track->setFinalVolume((vrf + vlf) / 2.f);
4843
Eric Laurent81784c32012-11-19 14:55:58 -08004844 // Delegate volume control to effect in track effect chain if needed
4845 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4846 // Do not ramp volume if volume is controlled by effect
4847 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004848 // Update remaining floating point volume levels
4849 vlf = (float)vl / (1 << 24);
4850 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004851 track->mHasVolumeController = true;
4852 } else {
4853 // force no volume ramp when volume controller was just disabled or removed
4854 // from effect chain to avoid volume spike
4855 if (track->mHasVolumeController) {
4856 param = AudioMixer::VOLUME;
4857 }
4858 track->mHasVolumeController = false;
4859 }
4860
Eric Laurent7c29ec92017-09-20 17:54:22 -07004861 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4862 // still applied by the mixer.
4863 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4864 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4865 if (v != mLeftVolFloat) {
4866 status_t result = mOutput->stream->setVolume(v, v);
4867 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4868 if (result == OK) {
4869 mLeftVolFloat = v;
4870 }
4871 }
4872 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4873 // remove stream volume contribution from software volume.
4874 if (v != 0.0f && mLeftVolFloat == v) {
4875 vlf = min(1.0f, vlf / v);
4876 vrf = min(1.0f, vrf / v);
4877 vaf = min(1.0f, vaf / v);
4878 }
4879 }
Eric Laurent81784c32012-11-19 14:55:58 -08004880 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07004881 mAudioMixer->setBufferProvider(trackId, track);
4882 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004883
Andy Hungc0691382018-09-12 18:01:57 -07004884 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
4885 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
4886 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004887 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004888 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004889 AudioMixer::TRACK,
4890 AudioMixer::FORMAT, (void *)track->format());
4891 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004892 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004893 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004894 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004895 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004896 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07004897 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08004898 AudioMixer::MIXER_CHANNEL_MASK,
4899 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08004900 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004901 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004902 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004903 if (reqSampleRate == 0) {
4904 reqSampleRate = mSampleRate;
4905 } else if (reqSampleRate > maxSampleRate) {
4906 reqSampleRate = maxSampleRate;
4907 }
Eric Laurent81784c32012-11-19 14:55:58 -08004908 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004909 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004910 AudioMixer::RESAMPLE,
4911 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004912 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004913
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004914 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004915 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004916 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07004917 AudioMixer::TIMESTRETCH,
4918 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004919 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004920
Andy Hung69aed5f2014-02-25 17:24:40 -08004921 /*
4922 * Select the appropriate output buffer for the track.
4923 *
Andy Hung98ef9782014-03-04 14:46:50 -08004924 * Tracks with effects go into their own effects chain buffer
4925 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004926 *
4927 * Other tracks can use mMixerBuffer for higher precision
4928 * channel accumulation. If this buffer is enabled
4929 * (mMixerBufferEnabled true), then selected tracks will accumulate
4930 * into it.
4931 *
4932 */
4933 if (mMixerBufferEnabled
4934 && (track->mainBuffer() == mSinkBuffer
4935 || track->mainBuffer() == mMixerBuffer)) {
4936 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004937 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004938 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004939 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004940 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004941 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004942 AudioMixer::TRACK,
4943 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4944 // TODO: override track->mainBuffer()?
4945 mMixerBufferValid = true;
4946 } else {
4947 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004948 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004949 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004950 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004951 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004952 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004953 AudioMixer::TRACK,
4954 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4955 }
Eric Laurent81784c32012-11-19 14:55:58 -08004956 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004957 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004958 AudioMixer::TRACK,
4959 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08004960 mAudioMixer->setParameter(
4961 trackId,
4962 AudioMixer::TRACK,
4963 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -08004964
4965 // reset retry count
4966 track->mRetryCount = kMaxTrackRetries;
4967
4968 // If one track is ready, set the mixer ready if:
4969 // - the mixer was not ready during previous round OR
4970 // - no other track is not ready
4971 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4972 mixerStatus != MIXER_TRACKS_ENABLED) {
4973 mixerStatus = MIXER_TRACKS_READY;
4974 }
4975 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004976 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004977 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07004978 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
4979 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004980 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004981 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004982 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004983
Eric Laurent81784c32012-11-19 14:55:58 -08004984 // clear effect chain input buffer if an active track underruns to avoid sending
4985 // previous audio buffer again to effects
4986 chain = getEffectChain_l(track->sessionId());
4987 if (chain != 0) {
4988 chain->clearInputBuffer();
4989 }
4990
Andy Hungc0691382018-09-12 18:01:57 -07004991 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004992 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4993 track->isStopped() || track->isPaused()) {
4994 // We have consumed all the buffers of this track.
4995 // Remove it from the list of active tracks.
4996 // TODO: use actual buffer filling status instead of latency when available from
4997 // audio HAL
4998 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004999 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005000 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5001 if (track->isStopped()) {
5002 track->reset();
5003 }
5004 tracksToRemove->add(track);
5005 }
5006 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005007 // No buffers for this track. Give it a few chances to
5008 // fill a buffer, then remove it from active list.
5009 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005010 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5011 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005012 tracksToRemove->add(track);
5013 // indicate to client process that the track was disabled because of underrun;
5014 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005015 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005016 // If one track is not ready, mark the mixer also not ready if:
5017 // - the mixer was ready during previous round OR
5018 // - no other track is ready
5019 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5020 mixerStatus != MIXER_TRACKS_READY) {
5021 mixerStatus = MIXER_TRACKS_ENABLED;
5022 }
5023 }
Andy Hungc0691382018-09-12 18:01:57 -07005024 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005025 }
5026
5027 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005028
5029 }
5030
jiabin245cdd92018-12-07 17:55:15 -08005031 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5032 // When there is no fast track playing haptic and FastMixer exists,
5033 // enabling the first FastTrack, which provides mixed data from normal
5034 // tracks, to play haptic data.
5035 FastTrack *fastTrack = &state->mFastTracks[0];
5036 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5037 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5038 didModify = true;
5039 }
5040 }
5041
Eric Laurent81784c32012-11-19 14:55:58 -08005042 // Push the new FastMixer state if necessary
5043 bool pauseAudioWatchdog = false;
5044 if (didModify) {
5045 state->mFastTracksGen++;
5046 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5047 if (kUseFastMixer == FastMixer_Dynamic &&
5048 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5049 state->mCommand = FastMixerState::COLD_IDLE;
5050 state->mColdFutexAddr = &mFastMixerFutex;
5051 state->mColdGen++;
5052 mFastMixerFutex = 0;
5053 if (kUseFastMixer == FastMixer_Dynamic) {
5054 mNormalSink = mOutputSink;
5055 }
5056 // If we go into cold idle, need to wait for acknowledgement
5057 // so that fast mixer stops doing I/O.
5058 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5059 pauseAudioWatchdog = true;
5060 }
Eric Laurent81784c32012-11-19 14:55:58 -08005061 }
5062 if (sq != NULL) {
5063 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005064 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5065 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5066 // when bringing the output sink into standby.)
5067 //
5068 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5069 //
5070 // This occurs with BT suspend when we idle the FastMixer with
5071 // active tracks, which may be added or removed.
5072 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005073 }
5074#ifdef AUDIO_WATCHDOG
5075 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5076 mAudioWatchdog->pause();
5077 }
5078#endif
5079
5080 // Now perform the deferred reset on fast tracks that have stopped
5081 while (resetMask != 0) {
5082 size_t i = __builtin_ctz(resetMask);
5083 ALOG_ASSERT(i < count);
5084 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005085 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005086 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5087 track->reset();
5088 }
5089
Andy Hung80d03d22018-04-10 10:32:11 -07005090 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5091 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5092 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5093 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5094 // See also the implementation of destroyTrack_l().
5095 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005096 const int trackId = track->id();
5097 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5098 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005099 }
5100 }
5101
Eric Laurent81784c32012-11-19 14:55:58 -08005102 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005103 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005104
Eric Laurent97d547d2014-09-02 14:45:53 -07005105 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5106 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005107 }
5108
5109 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005110 // as long as there are effects we should clear the effects buffer, to avoid
5111 // passing a non-clean buffer to the effect chain
5112 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005113 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005114 // sink or mix buffer must be cleared if all tracks are connected to an
5115 // effect chain as in this case the mixer will not write to the sink or mix buffer
5116 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005117 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5118 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005119 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005120 if (mMixerBufferValid) {
5121 memset(mMixerBuffer, 0, mMixerBufferSize);
5122 // TODO: In testing, mSinkBuffer below need not be cleared because
5123 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5124 // after mixing.
5125 //
5126 // To enforce this guarantee:
5127 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5128 // (mixedTracks == 0 && fastTracks > 0))
5129 // must imply MIXER_TRACKS_READY.
5130 // Later, we may clear buffers regardless, and skip much of this logic.
5131 }
Andy Hung98ef9782014-03-04 14:46:50 -08005132 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005133 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005134 }
5135
5136 // if any fast tracks, then status is ready
5137 mMixerStatusIgnoringFastTracks = mixerStatus;
5138 if (fastTracks > 0) {
5139 mixerStatus = MIXER_TRACKS_READY;
5140 }
5141 return mixerStatus;
5142}
5143
Eric Laurentad7dd962016-09-22 12:38:37 -07005144// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005145uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005146{
5147 uint32_t trackCount = 0;
5148 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005149 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005150 trackCount++;
5151 }
5152 }
5153 return trackCount;
5154}
5155
Andy Hung1bc088a2018-02-09 15:57:31 -08005156// isTrackAllowed_l() must be called with ThreadBase::mLock held
5157bool AudioFlinger::MixerThread::isTrackAllowed_l(
5158 audio_channel_mask_t channelMask, audio_format_t format,
5159 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005160{
Andy Hung1bc088a2018-02-09 15:57:31 -08005161 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5162 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005163 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005164 // Check validity as we don't call AudioMixer::create() here.
5165 if (!AudioMixer::isValidFormat(format)) {
5166 ALOGW("%s: invalid format: %#x", __func__, format);
5167 return false;
5168 }
5169 if (!AudioMixer::isValidChannelMask(channelMask)) {
5170 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5171 return false;
5172 }
5173 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005174}
5175
Eric Laurent10351942014-05-08 18:49:52 -07005176// checkForNewParameter_l() must be called with ThreadBase::mLock held
5177bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5178 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005179{
Eric Laurent81784c32012-11-19 14:55:58 -08005180 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005181 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005182
Eric Laurent10351942014-05-08 18:49:52 -07005183 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005184
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005185 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005186
Eric Laurent10351942014-05-08 18:49:52 -07005187 AudioParameter param = AudioParameter(keyValuePair);
5188 int value;
5189 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5190 reconfig = true;
5191 }
5192 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005193 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005194 status = BAD_VALUE;
5195 } else {
5196 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005197 reconfig = true;
5198 }
Eric Laurent10351942014-05-08 18:49:52 -07005199 }
5200 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005201 if (!isValidPcmSinkChannelMask((audio_channel_mask_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
5205 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005206 }
Eric Laurent10351942014-05-08 18:49:52 -07005207 }
5208 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5209 // do not accept frame count changes if tracks are open as the track buffer
5210 // size depends on frame count and correct behavior would not be guaranteed
5211 // if frame count is changed after track creation
5212 if (!mTracks.isEmpty()) {
5213 status = INVALID_OPERATION;
5214 } else {
5215 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005216 }
Eric Laurent10351942014-05-08 18:49:52 -07005217 }
5218 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005219#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005220 // when changing the audio output device, call addBatteryData to notify
5221 // the change
5222 if (mOutDevice != value) {
5223 uint32_t params = 0;
5224 // check whether speaker is on
5225 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5226 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005227 }
Eric Laurent10351942014-05-08 18:49:52 -07005228
5229 audio_devices_t deviceWithoutSpeaker
5230 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5231 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005232 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005233 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5234 }
5235
5236 if (params != 0) {
5237 addBatteryData(params);
5238 }
5239 }
Eric Laurent81784c32012-11-19 14:55:58 -08005240#endif
5241
Eric Laurent10351942014-05-08 18:49:52 -07005242 // forward device change to effects that have requested to be
5243 // aware of attached audio device.
5244 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005245 a2dpDeviceChanged =
5246 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005247 mOutDevice = value;
5248 for (size_t i = 0; i < mEffectChains.size(); i++) {
5249 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005250 }
5251 }
Eric Laurent10351942014-05-08 18:49:52 -07005252 }
Eric Laurent81784c32012-11-19 14:55:58 -08005253
Eric Laurent10351942014-05-08 18:49:52 -07005254 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005255 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005256 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005257 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005258 mStandby = true;
5259 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005260 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005261 }
Eric Laurent10351942014-05-08 18:49:52 -07005262 if (status == NO_ERROR && reconfig) {
5263 readOutputParameters_l();
5264 delete mAudioMixer;
5265 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005266 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005267 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005268 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005269 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005270 track->mChannelMask,
5271 track->mFormat,
5272 track->mSessionId);
5273 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005274 "%s(): AudioMixer cannot create track(%d)"
5275 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005276 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005277 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005278 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005279 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005280 }
Eric Laurent81784c32012-11-19 14:55:58 -08005281 }
5282
Eric Laurent42537be2016-01-08 17:16:42 -08005283 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005284}
5285
5286
5287void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5288{
Eric Laurent81784c32012-11-19 14:55:58 -08005289 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005290 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005291 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005292 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005293 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5294 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5295 : mBalance.toString()).c_str());
Andy Hungf6ab58d2018-05-25 12:50:39 -07005296 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005297 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005298 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005299 } else {
5300 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005301 }
Eric Laurent81784c32012-11-19 14:55:58 -08005302
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005303 if (hasFastMixer()) {
5304 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5305
5306 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5307 // while we are dumping it. It may be inconsistent, but it won't mutate!
5308 // This is a large object so we place it on the heap.
5309 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005310 const std::unique_ptr<FastMixerDumpState> copy =
5311 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005312 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005313
5314#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005315 // Similar for state queue
5316 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5317 observerCopy.dump(fd);
5318 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5319 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005320#endif
5321
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005322#ifdef AUDIO_WATCHDOG
5323 if (mAudioWatchdog != 0) {
5324 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5325 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5326 wdCopy.dump(fd);
5327 }
5328#endif
5329
5330 } else {
5331 dprintf(fd, " No FastMixer\n");
5332 }
Eric Laurent81784c32012-11-19 14:55:58 -08005333}
5334
5335uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5336{
5337 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5338}
5339
5340uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5341{
5342 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5343}
5344
5345void AudioFlinger::MixerThread::cacheParameters_l()
5346{
5347 PlaybackThread::cacheParameters_l();
5348
5349 // FIXME: Relaxed timing because of a certain device that can't meet latency
5350 // Should be reduced to 2x after the vendor fixes the driver issue
5351 // increase threshold again due to low power audio mode. The way this warning
5352 // threshold is calculated and its usefulness should be reconsidered anyway.
5353 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5354}
5355
5356// ----------------------------------------------------------------------------
5357
5358AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Andy Hung48f59ed2019-01-28 15:06:59 -08005359 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005360 ThreadBase::type_t type, bool systemReady)
5361 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005362{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005363 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005364}
5365
Eric Laurent81784c32012-11-19 14:55:58 -08005366AudioFlinger::DirectOutputThread::~DirectOutputThread()
5367{
5368}
5369
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005370void AudioFlinger::DirectOutputThread::dumpInternals(int fd, const Vector<String16>& args)
5371{
5372 PlaybackThread::dumpInternals(fd, args);
5373 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5374 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5375}
5376
5377void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5378{
5379 Mutex::Autolock _l(mLock);
5380 if (mMasterBalance != balance) {
5381 mMasterBalance.store(balance);
5382 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5383 broadcast_l();
5384 }
5385}
5386
Eric Laurent5850c4c2016-11-10 13:04:31 -08005387void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005388{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005389 float left, right;
5390
5391 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5392 left = right = 0;
5393 } else {
5394 float typeVolume = mStreamTypes[track->streamType()].volume;
5395 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005396 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005397
Andy Hung10cbff12017-02-21 17:30:14 -08005398 // Get volumeshaper scaling
5399 std::pair<float /* volume */, bool /* active */>
5400 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005401 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005402 v *= vh.first;
5403 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005404
Glenn Kastenc56f3422014-03-21 17:53:17 -07005405 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5406 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5407 if (left > GAIN_FLOAT_UNITY) {
5408 left = GAIN_FLOAT_UNITY;
5409 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005410 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005411 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5412 if (right > GAIN_FLOAT_UNITY) {
5413 right = GAIN_FLOAT_UNITY;
5414 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005415 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416 }
5417
5418 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005419 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005420 if (left != mLeftVolFloat || right != mRightVolFloat) {
5421 mLeftVolFloat = left;
5422 mRightVolFloat = right;
5423
Eric Laurentbfb1b832013-01-07 09:53:42 -08005424 // Delegate volume control to effect in track effect chain if needed
5425 // only one effect chain can be present on DirectOutputThread, so if
5426 // there is one, the track is connected to it
5427 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005428 // if effect chain exists, volume is handled by it.
5429 // Convert volumes from float to 8.24
5430 uint32_t vl = (uint32_t)(left * (1 << 24));
5431 uint32_t vr = (uint32_t)(right * (1 << 24));
5432 // Direct/Offload effect chains set output volume in setVolume_l().
5433 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5434 } else {
5435 // otherwise we directly set the volume.
5436 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005437 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005438 }
5439 }
5440}
5441
Phil Burk43b4dcc2015-06-09 16:53:44 -07005442void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5443{
5444 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005445 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005446
Eric Laurent0f0631e2015-07-06 18:01:25 -07005447 if (previousTrack != 0 && latestTrack != 0) {
5448 if (mType == DIRECT) {
5449 if (previousTrack.get() != latestTrack.get()) {
5450 mFlushPending = true;
5451 }
5452 } else /* mType == OFFLOAD */ {
5453 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5454 mFlushPending = true;
5455 }
5456 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005457 }
5458 PlaybackThread::onAddNewTrack_l();
5459}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005460
Eric Laurent81784c32012-11-19 14:55:58 -08005461AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5462 Vector< sp<Track> > *tracksToRemove
5463)
5464{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005465 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005466 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005467 bool doHwPause = false;
5468 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005469
5470 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005471 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005472 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005473 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005474 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005475 continue;
5476 }
5477
Eric Laurent5850c4c2016-11-10 13:04:31 -08005478 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005479#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005480 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005481#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005482 // Only consider last track started for volume and mixer state control.
5483 // In theory an older track could underrun and restart after the new one starts
5484 // but as we only care about the transition phase between two tracks on a
5485 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005486 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005487 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005488
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005489 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005490 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005491 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005492 doHwPause = true;
5493 mHwPaused = true;
5494 }
5495 tracksToRemove->add(track);
5496 } else if (track->isFlushPending()) {
5497 track->flushAck();
5498 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005499 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005500 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005501 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005502 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005503 if (last) {
5504 mLeftVolFloat = mRightVolFloat = -1.0;
5505 if (mHwPaused) {
5506 doHwResume = true;
5507 mHwPaused = false;
5508 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005509 }
5510 }
5511
Eric Laurent81784c32012-11-19 14:55:58 -08005512 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005513 // for all its buffers to be filled before processing it.
5514 // Allow draining the buffer in case the client
5515 // app does not call stop() and relies on underrun to stop:
5516 // hence the test on (track->mRetryCount > 1).
5517 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005518 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005519 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005520 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005521 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005522 minFrames = mNormalFrameCount;
5523 } else {
5524 minFrames = 1;
5525 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005526
Eric Laurentab5cdba2014-06-09 17:22:27 -07005527 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5528 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005529 {
Andy Hungc0691382018-09-12 18:01:57 -07005530 ALOGVV("track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005531
5532 if (track->mFillingUpStatus == Track::FS_FILLED) {
5533 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005534 if (last) {
5535 // make sure processVolume_l() will apply new volume even if 0
5536 mLeftVolFloat = mRightVolFloat = -1.0;
5537 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005538 if (!mHwSupportsPause) {
5539 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005540 }
5541 }
5542
5543 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005544 processVolume_l(track, last);
5545 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005546 sp<Track> previousTrack = mPreviousTrack.promote();
5547 if (previousTrack != 0) {
5548 if (track != previousTrack.get()) {
5549 // Flush any data still being written from last track
5550 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005551 // Invalidate previous track to force a seek when resuming.
5552 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005553 }
5554 }
5555 mPreviousTrack = track;
5556
Eric Laurentd595b7c2013-04-03 17:27:56 -07005557 // reset retry count
5558 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005559 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005560 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005561 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005562 doHwResume = true;
5563 mHwPaused = false;
5564 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005565 }
Eric Laurent81784c32012-11-19 14:55:58 -08005566 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005567 // clear effect chain input buffer if the last active track started underruns
5568 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005569 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005570 mEffectChains[0]->clearInputBuffer();
5571 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005572 if (track->isStopping_1()) {
5573 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005574 if (last && mHwPaused) {
5575 doHwResume = true;
5576 mHwPaused = false;
5577 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005578 }
5579 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5580 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005581 // We have consumed all the buffers of this track.
5582 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005583 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005584 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005585 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5586 } else {
5587 audioHALFrames = 0;
5588 }
5589
Andy Hung818e7a32016-02-16 18:08:07 -08005590 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005591 if (mStandby || !last ||
5592 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005593 if (track->isStopping_2()) {
5594 track->mState = TrackBase::STOPPED;
5595 }
Eric Laurent81784c32012-11-19 14:55:58 -08005596 if (track->isStopped()) {
5597 track->reset();
5598 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005599 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005600 }
5601 } else {
5602 // No buffers for this track. Give it a few chances to
5603 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005604 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005605 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005606 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", track->id());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005607 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005608 // indicate to client process that the track was disabled because of underrun;
5609 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005610 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005611 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005612 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5613 "minFrames = %u, mFormat = %#x",
5614 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005615 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005616 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005617 doHwPause = true;
5618 mHwPaused = true;
5619 }
Eric Laurent81784c32012-11-19 14:55:58 -08005620 }
5621 }
5622 }
5623 }
5624
Eric Laurentd1f69b02014-12-15 14:33:13 -08005625 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005626 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005627 for (size_t i = 0; i < mTracks.size(); i++) {
5628 if (mTracks[i]->isFlushPending()) {
5629 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005630 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005631 }
5632 }
5633 }
5634
5635 // make sure the pause/flush/resume sequence is executed in the right order.
5636 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5637 // before flush and then resume HW. This can happen in case of pause/flush/resume
5638 // if resume is received before pause is executed.
5639 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005640 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005641 status_t result = mOutput->stream->pause();
5642 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005643 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005644 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005645 flushHw_l();
5646 }
5647 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005648 status_t result = mOutput->stream->resume();
5649 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005650 }
Eric Laurent81784c32012-11-19 14:55:58 -08005651 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005652 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005653
5654 return mixerStatus;
5655}
5656
5657void AudioFlinger::DirectOutputThread::threadLoop_mix()
5658{
Eric Laurent81784c32012-11-19 14:55:58 -08005659 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005660 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005661 // output audio to hardware
5662 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005663 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005664 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005665 status_t status = mActiveTrack->getNextBuffer(&buffer);
5666 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005667 // no need to pad with 0 for compressed audio
5668 if (audio_has_proportional_frames(mFormat)) {
5669 memset(curBuf, 0, frameCount * mFrameSize);
5670 }
Eric Laurent81784c32012-11-19 14:55:58 -08005671 break;
5672 }
5673 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5674 frameCount -= buffer.frameCount;
5675 curBuf += buffer.frameCount * mFrameSize;
5676 mActiveTrack->releaseBuffer(&buffer);
5677 }
Andy Hung2098f272014-02-27 14:00:06 -08005678 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005679 mSleepTimeUs = 0;
5680 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005681 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005682}
5683
5684void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5685{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005686 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005687 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005688 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005689 return;
5690 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005691 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005692 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005693 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005694 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005695 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005696 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005697 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005698 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005699 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005700 }
5701}
5702
Eric Laurentd1f69b02014-12-15 14:33:13 -08005703void AudioFlinger::DirectOutputThread::threadLoop_exit()
5704{
5705 {
5706 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005707 for (size_t i = 0; i < mTracks.size(); i++) {
5708 if (mTracks[i]->isFlushPending()) {
5709 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005710 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005711 }
5712 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005713 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005714 flushHw_l();
5715 }
5716 }
5717 PlaybackThread::threadLoop_exit();
5718}
5719
5720// must be called with thread mutex locked
5721bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5722{
5723 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005724 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005725
vivek mehta9cd7ad12016-03-17 00:18:29 -07005726 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5727 return !mStandby;
5728 }
5729
Eric Laurentd1f69b02014-12-15 14:33:13 -08005730 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5731 // after a timeout and we will enter standby then.
5732 if (mTracks.size() > 0) {
5733 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005734 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5735 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005736 }
5737
Eric Laurent5cff4032015-05-26 13:49:58 -07005738 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005739}
5740
Eric Laurent10351942014-05-08 18:49:52 -07005741// checkForNewParameter_l() must be called with ThreadBase::mLock held
5742bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5743 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005744{
5745 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005746 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005747
Eric Laurent10351942014-05-08 18:49:52 -07005748 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005749
Eric Laurent10351942014-05-08 18:49:52 -07005750 AudioParameter param = AudioParameter(keyValuePair);
5751 int value;
5752 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5753 // forward device change to effects that have requested to be
5754 // aware of attached audio device.
5755 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005756 a2dpDeviceChanged =
5757 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005758 mOutDevice = value;
5759 for (size_t i = 0; i < mEffectChains.size(); i++) {
5760 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005761 }
5762 }
Eric Laurent81784c32012-11-19 14:55:58 -08005763 }
Eric Laurent10351942014-05-08 18:49:52 -07005764 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5765 // do not accept frame count changes if tracks are open as the track buffer
5766 // size depends on frame count and correct behavior would not be garantied
5767 // if frame count is changed after track creation
5768 if (!mTracks.isEmpty()) {
5769 status = INVALID_OPERATION;
5770 } else {
5771 reconfig = true;
5772 }
5773 }
5774 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005775 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005776 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005777 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005778 mStandby = true;
5779 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005780 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005781 }
5782 if (status == NO_ERROR && reconfig) {
5783 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005784 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005785 }
5786 }
5787
Eric Laurent42537be2016-01-08 17:16:42 -08005788 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005789}
5790
5791uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5792{
5793 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005794 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005795 time = PlaybackThread::activeSleepTimeUs();
5796 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005797 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005798 }
5799 return time;
5800}
5801
5802uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5803{
5804 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005805 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005806 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5807 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005808 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005809 }
5810 return time;
5811}
5812
5813uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5814{
5815 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005816 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005817 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5818 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005819 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005820 }
5821 return time;
5822}
5823
5824void AudioFlinger::DirectOutputThread::cacheParameters_l()
5825{
5826 PlaybackThread::cacheParameters_l();
5827
5828 // use shorter standby delay as on normal output to release
5829 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005830 // no delay on outputs with HW A/V sync
5831 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005832 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005833 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005834 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005835 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005836 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005837 }
Eric Laurent81784c32012-11-19 14:55:58 -08005838}
5839
Eric Laurente659ef42014-09-29 13:06:46 -07005840void AudioFlinger::DirectOutputThread::flushHw_l()
5841{
Phil Burk062e67a2015-02-11 13:40:50 -08005842 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005843 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005844 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005845 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005846}
5847
Andy Hung10cbff12017-02-21 17:30:14 -08005848int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5849 // If a VolumeShaper is active, we must wake up periodically to update volume.
5850 const int64_t NS_PER_MS = 1000000;
5851 return mVolumeShaperActive ?
5852 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5853}
5854
Eric Laurent81784c32012-11-19 14:55:58 -08005855// ----------------------------------------------------------------------------
5856
Eric Laurentbfb1b832013-01-07 09:53:42 -08005857AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005858 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005859 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005860 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005861 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005862 mDrainSequence(0),
5863 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005864{
5865}
5866
5867AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5868{
5869}
5870
5871void AudioFlinger::AsyncCallbackThread::onFirstRef()
5872{
5873 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5874}
5875
5876bool AudioFlinger::AsyncCallbackThread::threadLoop()
5877{
5878 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005879 uint32_t writeAckSequence;
5880 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005881 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005882
5883 {
5884 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005885 while (!((mWriteAckSequence & 1) ||
5886 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005887 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005888 exitPending())) {
5889 mWaitWorkCV.wait(mLock);
5890 }
5891
Eric Laurentbfb1b832013-01-07 09:53:42 -08005892 if (exitPending()) {
5893 break;
5894 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005895 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5896 mWriteAckSequence, mDrainSequence);
5897 writeAckSequence = mWriteAckSequence;
5898 mWriteAckSequence &= ~1;
5899 drainSequence = mDrainSequence;
5900 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005901 asyncError = mAsyncError;
5902 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005903 }
5904 {
Eric Laurent4de95592013-09-26 15:28:21 -07005905 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5906 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005907 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005908 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005909 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005910 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005911 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005912 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005913 if (asyncError) {
5914 playbackThread->onAsyncError();
5915 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005916 }
5917 }
5918 }
5919 return false;
5920}
5921
5922void AudioFlinger::AsyncCallbackThread::exit()
5923{
5924 ALOGV("AsyncCallbackThread::exit");
5925 Mutex::Autolock _l(mLock);
5926 requestExit();
5927 mWaitWorkCV.broadcast();
5928}
5929
Eric Laurent3b4529e2013-09-05 18:09:19 -07005930void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005931{
5932 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005933 // bit 0 is cleared
5934 mWriteAckSequence = sequence << 1;
5935}
5936
5937void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5938{
5939 Mutex::Autolock _l(mLock);
5940 // ignore unexpected callbacks
5941 if (mWriteAckSequence & 2) {
5942 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005943 mWaitWorkCV.signal();
5944 }
5945}
5946
Eric Laurent3b4529e2013-09-05 18:09:19 -07005947void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005948{
5949 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005950 // bit 0 is cleared
5951 mDrainSequence = sequence << 1;
5952}
5953
5954void AudioFlinger::AsyncCallbackThread::resetDraining()
5955{
5956 Mutex::Autolock _l(mLock);
5957 // ignore unexpected callbacks
5958 if (mDrainSequence & 2) {
5959 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005960 mWaitWorkCV.signal();
5961 }
5962}
5963
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005964void AudioFlinger::AsyncCallbackThread::setAsyncError()
5965{
5966 Mutex::Autolock _l(mLock);
5967 mAsyncError = true;
5968 mWaitWorkCV.signal();
5969}
5970
Eric Laurentbfb1b832013-01-07 09:53:42 -08005971
5972// ----------------------------------------------------------------------------
5973AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005974 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5975 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005976 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5977 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005978{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005979 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005980 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005981 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005982}
5983
Eric Laurentbfb1b832013-01-07 09:53:42 -08005984void AudioFlinger::OffloadThread::threadLoop_exit()
5985{
5986 if (mFlushPending || mHwPaused) {
5987 // If a flush is pending or track was paused, just discard buffered data
5988 flushHw_l();
5989 } else {
5990 mMixerStatus = MIXER_DRAIN_ALL;
5991 threadLoop_drain();
5992 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005993 if (mUseAsyncWrite) {
5994 ALOG_ASSERT(mCallbackThread != 0);
5995 mCallbackThread->exit();
5996 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005997 PlaybackThread::threadLoop_exit();
5998}
5999
6000AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6001 Vector< sp<Track> > *tracksToRemove
6002)
6003{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006004 size_t count = mActiveTracks.size();
6005
6006 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006007 bool doHwPause = false;
6008 bool doHwResume = false;
6009
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006010 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006011
Eric Laurentbfb1b832013-01-07 09:53:42 -08006012 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006013 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006014 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006015#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006016 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006017#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006018 // Only consider last track started for volume and mixer state control.
6019 // In theory an older track could underrun and restart after the new one starts
6020 // but as we only care about the transition phase between two tracks on a
6021 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006022 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006023 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006024
Haynes Mathew George7844f672014-01-15 12:32:55 -08006025 if (track->isInvalid()) {
6026 ALOGW("An invalidated track shouldn't be in active list");
6027 tracksToRemove->add(track);
6028 continue;
6029 }
6030
6031 if (track->mState == TrackBase::IDLE) {
6032 ALOGW("An idle track shouldn't be in active list");
6033 continue;
6034 }
6035
Eric Laurentbfb1b832013-01-07 09:53:42 -08006036 if (track->isPausing()) {
6037 track->setPaused();
6038 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006039 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006040 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006041 mHwPaused = true;
6042 }
6043 // If we were part way through writing the mixbuffer to
6044 // the HAL we must save this until we resume
6045 // BUG - this will be wrong if a different track is made active,
6046 // in that case we want to discard the pending data in the
6047 // mixbuffer and tell the client to present it again when the
6048 // track is resumed
6049 mPausedWriteLength = mCurrentWriteLength;
6050 mPausedBytesRemaining = mBytesRemaining;
6051 mBytesRemaining = 0; // stop writing
6052 }
6053 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006054 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006055 if (track->isStopping_1()) {
6056 track->mRetryCount = kMaxTrackStopRetriesOffload;
6057 } else {
6058 track->mRetryCount = kMaxTrackRetriesOffload;
6059 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006060 track->flushAck();
6061 if (last) {
6062 mFlushPending = true;
6063 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006064 } else if (track->isResumePending()){
6065 track->resumeAck();
6066 if (last) {
6067 if (mPausedBytesRemaining) {
6068 // Need to continue write that was interrupted
6069 mCurrentWriteLength = mPausedWriteLength;
6070 mBytesRemaining = mPausedBytesRemaining;
6071 mPausedBytesRemaining = 0;
6072 }
6073 if (mHwPaused) {
6074 doHwResume = true;
6075 mHwPaused = false;
6076 // threadLoop_mix() will handle the case that we need to
6077 // resume an interrupted write
6078 }
6079 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006080 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006081
Eric Laurent3df841a2016-07-15 15:15:40 -07006082 mLeftVolFloat = mRightVolFloat = -1.0;
6083
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006084 // Do not handle new data in this iteration even if track->framesReady()
6085 mixerStatus = MIXER_TRACKS_ENABLED;
6086 }
6087 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006088 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006089 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006090 if (track->mFillingUpStatus == Track::FS_FILLED) {
6091 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006092 if (last) {
6093 // make sure processVolume_l() will apply new volume even if 0
6094 mLeftVolFloat = mRightVolFloat = -1.0;
6095 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006096 }
6097
6098 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006099 sp<Track> previousTrack = mPreviousTrack.promote();
6100 if (previousTrack != 0) {
6101 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006102 // Flush any data still being written from last track
6103 mBytesRemaining = 0;
6104 if (mPausedBytesRemaining) {
6105 // Last track was paused so we also need to flush saved
6106 // mixbuffer state and invalidate track so that it will
6107 // re-submit that unwritten data when it is next resumed
6108 mPausedBytesRemaining = 0;
6109 // Invalidate is a bit drastic - would be more efficient
6110 // to have a flag to tell client that some of the
6111 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006112 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006113 }
6114 // flush data already sent to the DSP if changing audio session as audio
6115 // comes from a different source. Also invalidate previous track to force a
6116 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006117 if (previousTrack->sessionId() != track->sessionId()) {
6118 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006119 }
6120 }
6121 }
6122 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006123 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006124 if (track->isStopping_1()) {
6125 track->mRetryCount = kMaxTrackStopRetriesOffload;
6126 } else {
6127 track->mRetryCount = kMaxTrackRetriesOffload;
6128 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006129 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006130 mixerStatus = MIXER_TRACKS_READY;
6131 }
6132 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006133 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006134 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006135 if (--(track->mRetryCount) <= 0) {
6136 // Hardware buffer can hold a large amount of audio so we must
6137 // wait for all current track's data to drain before we say
6138 // that the track is stopped.
6139 if (mBytesRemaining == 0) {
6140 // Only start draining when all data in mixbuffer
6141 // has been written
6142 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6143 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6144 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6145 if (last && !mStandby) {
6146 // do not modify drain sequence if we are already draining. This happens
6147 // when resuming from pause after drain.
6148 if ((mDrainSequence & 1) == 0) {
6149 mSleepTimeUs = 0;
6150 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6151 mixerStatus = MIXER_DRAIN_TRACK;
6152 mDrainSequence += 2;
6153 }
6154 if (mHwPaused) {
6155 // It is possible to move from PAUSED to STOPPING_1 without
6156 // a resume so we must ensure hardware is running
6157 doHwResume = true;
6158 mHwPaused = false;
6159 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006160 }
6161 }
Eric Laurente93cc032016-05-05 10:15:10 -07006162 } else if (last) {
6163 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6164 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006165 }
6166 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006167 // Drain has completed or we are in standby, signal presentation complete
6168 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006169 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006170 uint32_t latency = 0;
6171 status_t result = mOutput->stream->getLatency(&latency);
6172 ALOGE_IF(result != OK,
6173 "Error when retrieving output stream latency: %d", result);
6174 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006175 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006176 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006177 track->presentationComplete(framesWritten, audioHALFrames);
6178 track->reset();
6179 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006180 // DIRECT and OFFLOADED stop resets frame counts.
6181 if (!mUseAsyncWrite) {
6182 // If we don't get explicit drain notification we must
6183 // register discontinuity regardless of whether this is
6184 // the previous (!last) or the upcoming (last) track
6185 // to avoid skipping the discontinuity.
6186 mTimestampVerifier.discontinuity();
6187 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006188 }
6189 } else {
6190 // No buffers for this track. Give it a few chances to
6191 // fill a buffer, then remove it from active list.
6192 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006193 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006194 uint64_t position = 0;
6195 struct timespec unused;
6196 // The running check restarts the retry counter at least once.
6197 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6198 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6199 running = true;
6200 mOffloadUnderrunPosition = position;
6201 }
6202 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006203 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6204 (long long)position, (long long)mOffloadUnderrunPosition);
6205 }
6206 if (running) { // still running, give us more time.
6207 track->mRetryCount = kMaxTrackRetriesOffload;
6208 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006209 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6210 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006211 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006212 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006213 // it will then automatically call start() when data is available
6214 track->disable();
6215 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006216 } else if (last){
6217 mixerStatus = MIXER_TRACKS_ENABLED;
6218 }
6219 }
6220 }
6221 // compute volume for this track
6222 processVolume_l(track, last);
6223 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006224
Eric Laurentea0fade2013-10-04 16:23:48 -07006225 // make sure the pause/flush/resume sequence is executed in the right order.
6226 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6227 // before flush and then resume HW. This can happen in case of pause/flush/resume
6228 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006229 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006230 status_t result = mOutput->stream->pause();
6231 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006232 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006233 if (mFlushPending) {
6234 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006235 }
Eric Laurentfd477972013-10-25 18:10:40 -07006236 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006237 status_t result = mOutput->stream->resume();
6238 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006239 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006240
Eric Laurentbfb1b832013-01-07 09:53:42 -08006241 // remove all the tracks that need to be...
6242 removeTracks_l(*tracksToRemove);
6243
6244 return mixerStatus;
6245}
6246
Eric Laurentbfb1b832013-01-07 09:53:42 -08006247// must be called with thread mutex locked
6248bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6249{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006250 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6251 mWriteAckSequence, mDrainSequence);
6252 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006253 return true;
6254 }
6255 return false;
6256}
6257
Eric Laurentbfb1b832013-01-07 09:53:42 -08006258bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6259{
6260 Mutex::Autolock _l(mLock);
6261 return waitingAsyncCallback_l();
6262}
6263
6264void AudioFlinger::OffloadThread::flushHw_l()
6265{
Eric Laurente659ef42014-09-29 13:06:46 -07006266 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006267 // Flush anything still waiting in the mixbuffer
6268 mCurrentWriteLength = 0;
6269 mBytesRemaining = 0;
6270 mPausedWriteLength = 0;
6271 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006272 // reset bytes written count to reflect that DSP buffers are empty after flush.
6273 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006274 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006275
Eric Laurentbfb1b832013-01-07 09:53:42 -08006276 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006277 // discard any pending drain or write ack by incrementing sequence
6278 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6279 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006280 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006281 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6282 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006283 }
6284}
6285
Haynes Mathew George05317d22016-05-03 16:34:26 -07006286void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6287{
6288 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006289 if (PlaybackThread::invalidateTracks_l(streamType)) {
6290 mFlushPending = true;
6291 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006292}
6293
Eric Laurentbfb1b832013-01-07 09:53:42 -08006294// ----------------------------------------------------------------------------
6295
Eric Laurent81784c32012-11-19 14:55:58 -08006296AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006297 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006298 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006299 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006300 mWaitTimeMs(UINT_MAX)
6301{
6302 addOutputTrack(mainThread);
6303}
6304
6305AudioFlinger::DuplicatingThread::~DuplicatingThread()
6306{
6307 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6308 mOutputTracks[i]->destroy();
6309 }
6310}
6311
6312void AudioFlinger::DuplicatingThread::threadLoop_mix()
6313{
6314 // mix buffers...
6315 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006316 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006317 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006318 if (mMixerBufferValid) {
6319 memset(mMixerBuffer, 0, mMixerBufferSize);
6320 } else {
6321 memset(mSinkBuffer, 0, mSinkBufferSize);
6322 }
Eric Laurent81784c32012-11-19 14:55:58 -08006323 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006324 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006325 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006326 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006327 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006328}
6329
6330void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6331{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006332 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006333 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006334 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006335 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006336 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006337 }
6338 } else if (mBytesWritten != 0) {
6339 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6340 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006341 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006342 } else {
6343 // flush remaining overflow buffers in output tracks
6344 writeFrames = 0;
6345 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006346 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006347 }
6348}
6349
Eric Laurentbfb1b832013-01-07 09:53:42 -08006350ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006351{
6352 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006353 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6354
6355 // Consider the first OutputTrack for timestamp and frame counting.
6356
6357 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6358 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6359 // we always claim success.
6360 if (i == 0) {
6361 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6362 ALOGD_IF(correction != 0 && writeFrames != 0,
6363 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6364 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6365 mFramesWritten -= correction;
6366 }
6367
6368 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006369 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006370 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006371 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006372}
6373
6374void AudioFlinger::DuplicatingThread::threadLoop_standby()
6375{
6376 // DuplicatingThread implements standby by stopping all tracks
6377 for (size_t i = 0; i < outputTracks.size(); i++) {
6378 outputTracks[i]->stop();
6379 }
6380}
6381
Andy Hung1bc088a2018-02-09 15:57:31 -08006382void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6383{
6384 MixerThread::dumpInternals(fd, args);
6385
6386 std::stringstream ss;
6387 const size_t numTracks = mOutputTracks.size();
6388 ss << " " << numTracks << " OutputTracks";
6389 if (numTracks > 0) {
6390 ss << ":";
6391 for (const auto &track : mOutputTracks) {
6392 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006393 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006394 if (thread.get() != nullptr) {
6395 ss << thread.get() << ", " << thread->id();
6396 } else {
6397 ss << "null";
6398 }
6399 ss << ")";
6400 }
6401 }
6402 ss << "\n";
6403 std::string result = ss.str();
6404 write(fd, result.c_str(), result.size());
6405}
6406
Eric Laurent81784c32012-11-19 14:55:58 -08006407void AudioFlinger::DuplicatingThread::saveOutputTracks()
6408{
6409 outputTracks = mOutputTracks;
6410}
6411
6412void AudioFlinger::DuplicatingThread::clearOutputTracks()
6413{
6414 outputTracks.clear();
6415}
6416
6417void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6418{
6419 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006420 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6421 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6422 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6423 const size_t frameCount =
6424 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6425 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6426 // from different OutputTracks and their associated MixerThreads (e.g. one may
6427 // nearly empty and the other may be dropping data).
6428
6429 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006430 this,
6431 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006432 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006433 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006434 frameCount,
6435 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006436 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6437 if (status != NO_ERROR) {
6438 ALOGE("addOutputTrack() initCheck failed %d", status);
6439 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006440 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006441 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6442 mOutputTracks.add(outputTrack);
6443 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6444 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006445}
6446
6447void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6448{
6449 Mutex::Autolock _l(mLock);
6450 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6451 if (mOutputTracks[i]->thread() == thread) {
6452 mOutputTracks[i]->destroy();
6453 mOutputTracks.removeAt(i);
6454 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006455 if (thread->getOutput() == mOutput) {
6456 mOutput = NULL;
6457 }
Eric Laurent81784c32012-11-19 14:55:58 -08006458 return;
6459 }
6460 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006461 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006462}
6463
6464// caller must hold mLock
6465void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6466{
6467 mWaitTimeMs = UINT_MAX;
6468 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6469 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6470 if (strong != 0) {
6471 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6472 if (waitTimeMs < mWaitTimeMs) {
6473 mWaitTimeMs = waitTimeMs;
6474 }
6475 }
6476 }
6477}
6478
6479
6480bool AudioFlinger::DuplicatingThread::outputsReady(
6481 const SortedVector< sp<OutputTrack> > &outputTracks)
6482{
6483 for (size_t i = 0; i < outputTracks.size(); i++) {
6484 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6485 if (thread == 0) {
6486 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6487 outputTracks[i].get());
6488 return false;
6489 }
6490 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6491 // see note at standby() declaration
6492 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6493 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6494 thread.get());
6495 return false;
6496 }
6497 }
6498 return true;
6499}
6500
Kevin Rocard12381092018-04-11 09:19:59 -07006501void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6502 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006503{
Kevin Rocard12381092018-04-11 09:19:59 -07006504 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6505 outputTrack->setMetadatas(metadata.tracks);
6506 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006507}
6508
Eric Laurent81784c32012-11-19 14:55:58 -08006509uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6510{
6511 return (mWaitTimeMs * 1000) / 2;
6512}
6513
6514void AudioFlinger::DuplicatingThread::cacheParameters_l()
6515{
6516 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6517 updateWaitTime_l();
6518
6519 MixerThread::cacheParameters_l();
6520}
6521
Eric Laurent6acd1d42017-01-04 14:23:29 -08006522
Eric Laurent81784c32012-11-19 14:55:58 -08006523// ----------------------------------------------------------------------------
6524// Record
6525// ----------------------------------------------------------------------------
6526
6527AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6528 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006529 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006530 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006531 audio_devices_t inDevice,
6532 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006533 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006534 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006535 mInput(input),
6536 mActiveTracks(&this->mLocalLog),
6537 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006538 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006539 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006540 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6541 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006542 // mFastCapture below
6543 , mFastCaptureFutex(0)
6544 // mInputSource
6545 // mPipeSink
6546 // mPipeSource
6547 , mPipeFramesP2(0)
6548 // mPipeMemory
6549 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006550 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006551 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006552{
Glenn Kastend7dca052015-03-05 16:05:54 -08006553 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6554 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006555
Andy Hungc8fddf32018-08-08 18:32:37 -07006556 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6557 mIsMsdDevice = strcmp(
6558 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6559 }
6560
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006561 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006562
Andy Hungc8fddf32018-08-08 18:32:37 -07006563 // TODO: We may also match on address as well as device type for
6564 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
6565 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
6566 "audio.timestamp.corrected_input_devices",
6567 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6568 : AUDIO_DEVICE_NONE));
6569
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006570 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006571 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006572 size_t numCounterOffers = 0;
6573 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006574#if !LOG_NDEBUG
6575 ssize_t index =
6576#else
6577 (void)
6578#endif
6579 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006580 ALOG_ASSERT(index == 0);
6581
6582 // initialize fast capture depending on configuration
6583 bool initFastCapture;
6584 switch (kUseFastCapture) {
6585 case FastCapture_Never:
6586 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006587 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006588 break;
6589 case FastCapture_Always:
6590 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006591 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006592 break;
6593 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006594 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006595 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6596 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6597 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006598 break;
6599 // case FastCapture_Dynamic:
6600 }
6601
6602 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006603 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006604 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006605 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6606 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006607 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006608 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006609 const sp<MemoryDealer> roHeap(readOnlyHeap());
6610 sp<IMemory> pipeMemory;
6611 if ((roHeap == 0) ||
6612 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006613 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6614 ALOGE("not enough memory for pipe buffer size=%zu; "
6615 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6616 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6617 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006618 goto failed;
6619 }
6620 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6621 memset(pipeBuffer, 0, pipeSize);
6622 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6623 const NBAIO_Format offers[1] = {format};
6624 size_t numCounterOffers = 0;
6625 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6626 ALOG_ASSERT(index == 0);
6627 mPipeSink = pipe;
6628 PipeReader *pipeReader = new PipeReader(*pipe);
6629 numCounterOffers = 0;
6630 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6631 ALOG_ASSERT(index == 0);
6632 mPipeSource = pipeReader;
6633 mPipeFramesP2 = pipeFramesP2;
6634 mPipeMemory = pipeMemory;
6635
6636 // create fast capture
6637 mFastCapture = new FastCapture();
6638 FastCaptureStateQueue *sq = mFastCapture->sq();
6639#ifdef STATE_QUEUE_DUMP
6640 // FIXME
6641#endif
6642 FastCaptureState *state = sq->begin();
6643 state->mCblk = NULL;
6644 state->mInputSource = mInputSource.get();
6645 state->mInputSourceGen++;
6646 state->mPipeSink = pipe;
6647 state->mPipeSinkGen++;
6648 state->mFrameCount = mFrameCount;
6649 state->mCommand = FastCaptureState::COLD_IDLE;
6650 // already done in constructor initialization list
6651 //mFastCaptureFutex = 0;
6652 state->mColdFutexAddr = &mFastCaptureFutex;
6653 state->mColdGen++;
6654 state->mDumpState = &mFastCaptureDumpState;
6655#ifdef TEE_SINK
6656 // FIXME
6657#endif
6658 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6659 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6660 sq->end();
6661 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6662
6663 // start the fast capture
6664 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6665 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006666 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006667 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006668#ifdef AUDIO_WATCHDOG
6669 // FIXME
6670#endif
6671
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006672 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006673 }
Andy Hung8946a282018-04-19 20:04:56 -07006674#ifdef TEE_SINK
6675 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6676 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6677#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006678failed: ;
6679
6680 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006681}
6682
Eric Laurent81784c32012-11-19 14:55:58 -08006683AudioFlinger::RecordThread::~RecordThread()
6684{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006685 if (mFastCapture != 0) {
6686 FastCaptureStateQueue *sq = mFastCapture->sq();
6687 FastCaptureState *state = sq->begin();
6688 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6689 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6690 if (old == -1) {
6691 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6692 }
6693 }
6694 state->mCommand = FastCaptureState::EXIT;
6695 sq->end();
6696 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6697 mFastCapture->join();
6698 mFastCapture.clear();
6699 }
6700 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006701 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006702 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006703}
6704
6705void AudioFlinger::RecordThread::onFirstRef()
6706{
Glenn Kastend7dca052015-03-05 16:05:54 -08006707 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006708}
6709
Eric Laurent555530a2017-02-07 18:17:24 -08006710void AudioFlinger::RecordThread::preExit()
6711{
6712 ALOGV(" preExit()");
6713 Mutex::Autolock _l(mLock);
6714 for (size_t i = 0; i < mTracks.size(); i++) {
6715 sp<RecordTrack> track = mTracks[i];
6716 track->invalidate();
6717 }
6718 mActiveTracks.clear();
6719 mStartStopCond.broadcast();
6720}
6721
Eric Laurent81784c32012-11-19 14:55:58 -08006722bool AudioFlinger::RecordThread::threadLoop()
6723{
Eric Laurent81784c32012-11-19 14:55:58 -08006724 nsecs_t lastWarning = 0;
6725
6726 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006727
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006728reacquire_wakelock:
6729 sp<RecordTrack> activeTrack;
6730 {
6731 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006732 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006733 }
6734
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006735 // used to request a deferred sleep, to be executed later while mutex is unlocked
6736 uint32_t sleepUs = 0;
6737
6738 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006739 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006740 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006741
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006742 // activeTracks accumulates a copy of a subset of mActiveTracks
6743 Vector< sp<RecordTrack> > activeTracks;
6744
Glenn Kasten735f45f2014-08-18 15:51:59 -07006745 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006746 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006747
Glenn Kasten735f45f2014-08-18 15:51:59 -07006748 // reference to a fast track which is about to be removed
6749 sp<RecordTrack> fastTrackToRemove;
6750
Eric Laurent81784c32012-11-19 14:55:58 -08006751 { // scope for mLock
6752 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006753
Eric Laurent021cf962014-05-13 10:18:14 -07006754 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006755
Eric Laurent000a4192014-01-29 15:17:32 -08006756 // check exitPending here because checkForNewParameters_l() and
6757 // checkForNewParameters_l() can temporarily release mLock
6758 if (exitPending()) {
6759 break;
6760 }
6761
Eric Laurent5c25d562016-07-13 17:17:45 -07006762 // sleep with mutex unlocked
6763 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006764 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006765 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6766 ATRACE_END();
6767 sleepUs = 0;
6768 continue;
6769 }
6770
Glenn Kasten2b806402013-11-20 16:37:38 -08006771 // if no active track(s), then standby and release wakelock
6772 size_t size = mActiveTracks.size();
6773 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006774 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006775 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006776 releaseWakeLock_l();
6777 ALOGV("RecordThread: loop stopping");
6778 // go to sleep
6779 mWaitWorkCV.wait(mLock);
6780 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006781 goto reacquire_wakelock;
6782 }
6783
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006784 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006785 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006786 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006787
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006788 activeTrack = mActiveTracks[i];
6789 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006790 if (activeTrack->isFastTrack()) {
6791 ALOG_ASSERT(fastTrackToRemove == 0);
6792 fastTrackToRemove = activeTrack;
6793 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006794 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006795 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006796 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006797 continue;
6798 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006799
6800 TrackBase::track_state activeTrackState = activeTrack->mState;
6801 switch (activeTrackState) {
6802
6803 case TrackBase::PAUSING:
6804 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006805 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006806 doBroadcast = true;
6807 size--;
6808 continue;
6809
6810 case TrackBase::STARTING_1:
6811 sleepUs = 10000;
6812 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006813 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006814 continue;
6815
6816 case TrackBase::STARTING_2:
6817 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006818 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006819 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006820 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006821 break;
6822
6823 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006824 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006825 break;
6826
Andy Hungce685402018-10-05 17:23:27 -07006827 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6828 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6829 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006830 default:
Andy Hungce685402018-10-05 17:23:27 -07006831 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6832 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006833 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006834
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006835 activeTracks.add(activeTrack);
6836 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006837
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006838 if (activeTrack->isFastTrack()) {
6839 ALOG_ASSERT(!mFastTrackAvail);
6840 ALOG_ASSERT(fastTrack == 0);
6841 fastTrack = activeTrack;
6842 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006843 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006844
Andy Hungdae27702016-10-31 14:01:16 -07006845 mActiveTracks.updatePowerState(this);
6846
Kevin Rocard069c2712018-03-29 19:09:14 -07006847 updateMetadata_l();
6848
Eric Laurent5c25d562016-07-13 17:17:45 -07006849 if (allStopped) {
6850 standbyIfNotAlreadyInStandby();
6851 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006852 if (doBroadcast) {
6853 mStartStopCond.broadcast();
6854 }
6855
6856 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006857 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006858 if (sleepUs == 0) {
6859 sleepUs = kRecordThreadSleepUs;
6860 }
6861 continue;
6862 }
6863 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006864
Eric Laurent81784c32012-11-19 14:55:58 -08006865 lockEffectChains_l(effectChains);
6866 }
6867
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006868 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006869
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006870 size_t size = effectChains.size();
6871 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006872 // thread mutex is not locked, but effect chain is locked
6873 effectChains[i]->process_l();
6874 }
6875
Glenn Kasten735f45f2014-08-18 15:51:59 -07006876 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006877 if (mFastCapture != 0) {
6878 FastCaptureStateQueue *sq = mFastCapture->sq();
6879 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006880 bool didModify = false;
6881 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006882 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6883 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6884 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6885 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6886 if (old == -1) {
6887 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6888 }
6889 }
6890 state->mCommand = FastCaptureState::READ_WRITE;
6891#if 0 // FIXME
6892 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006893 FastThreadDumpState::kSamplingNforLowRamDevice :
6894 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006895#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006896 didModify = true;
6897 }
6898 audio_track_cblk_t *cblkOld = state->mCblk;
6899 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6900 if (cblkNew != cblkOld) {
6901 state->mCblk = cblkNew;
6902 // block until acked if removing a fast track
6903 if (cblkOld != NULL) {
6904 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6905 }
6906 didModify = true;
6907 }
jiabin01c8f562018-07-19 17:47:28 -07006908 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
6909 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
6910 if (state->mFastPatchRecordBufferProvider != abp) {
6911 state->mFastPatchRecordBufferProvider = abp;
6912 state->mFastPatchRecordFormat = fastTrack == 0 ?
6913 AUDIO_FORMAT_INVALID : fastTrack->format();
6914 didModify = true;
6915 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07006916 sq->end(didModify);
6917 if (didModify) {
6918 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006919#if 0
6920 if (kUseFastCapture == FastCapture_Dynamic) {
6921 mNormalSource = mPipeSource;
6922 }
6923#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006924 }
6925 }
6926
Glenn Kasten735f45f2014-08-18 15:51:59 -07006927 // now run the fast track destructor with thread mutex unlocked
6928 fastTrackToRemove.clear();
6929
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006930 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6931 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6932 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6933 // If destination is non-contiguous, first read past the nominal end of buffer, then
6934 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006935
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006936 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006937 ssize_t framesRead;
6938
6939 // If an NBAIO source is present, use it to read the normal capture's data
6940 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07006941 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006942
6943 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6944 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6945 // we immediately retry the read() to get data and prevent another overflow.
6946 for (int retries = 0; retries <= 2; ++retries) {
6947 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6948 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6949 framesToRead);
6950 if (framesRead != OVERRUN) break;
6951 }
6952
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006953 const ssize_t availableToRead = mPipeSource->availableToRead();
6954 if (availableToRead >= 0) {
6955 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6956 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6957 "more frames to read than fifo size, %zd > %zu",
6958 availableToRead, mPipeFramesP2);
6959 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6960 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6961 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6962 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006963 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6964 }
6965 if (framesRead < 0) {
6966 status_t status = (status_t) framesRead;
6967 switch (status) {
6968 case OVERRUN:
6969 ALOGW("overrun on read from pipe");
6970 framesRead = 0;
6971 break;
6972 case NEGOTIATE:
6973 ALOGE("re-negotiation is needed");
6974 framesRead = -1; // Will cause an attempt to recover.
6975 break;
6976 default:
6977 ALOGE("unknown error %d on read from pipe", status);
6978 break;
6979 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006980 }
6981 // otherwise use the HAL / AudioStreamIn directly
6982 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006983 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006984 size_t bytesRead;
6985 status_t result = mInput->stream->read(
6986 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006987 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006988 if (result < 0) {
6989 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006990 } else {
6991 framesRead = bytesRead / mFrameSize;
6992 }
6993 }
6994
Andy Hung3f0c9022016-01-15 17:49:46 -08006995 // Update server timestamp with server stats
6996 // systemTime() is optional if the hardware supports timestamps.
6997 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6998 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6999
7000 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007001 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007002 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007003 if (mStandby) {
7004 mTimestampVerifier.discontinuity();
Andy Hungc8fddf32018-08-08 18:32:37 -07007005 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR
7006 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7007
7008 mTimestampVerifier.add(position, time, mSampleRate);
7009
7010 // Correct timestamps
7011 if (isTimestampCorrectionEnabled()) {
7012 ALOGV("TS_BEFORE: %d %lld %lld",
7013 id(), (long long)time, (long long)position);
7014 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7015 position = correctedTimestamp.mFrames;
7016 time = correctedTimestamp.mTimeNs;
7017 ALOGV("TS_AFTER: %d %lld %lld",
7018 id(), (long long)time, (long long)position);
7019 }
7020
Andy Hung3f0c9022016-01-15 17:49:46 -08007021 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7022 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7023 // Note: In general record buffers should tend to be empty in
7024 // a properly running pipeline.
7025 //
7026 // Also, it is not advantageous to call get_presentation_position during the read
7027 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007028 } else {
7029 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007030 }
7031 }
7032 // Use this to track timestamp information
7033 // ALOGD("%s", mTimestamp.toString().c_str());
7034
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007035 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007036 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007037 // Force input into standby so that it tries to recover at next read attempt
7038 inputStandBy();
7039 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007040 }
7041 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007042 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007043 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007044 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007045 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007046
Andy Hung8946a282018-04-19 20:04:56 -07007047#ifdef TEE_SINK
7048 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7049#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007050 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007051 {
7052 size_t part1 = mRsmpInFramesP2 - rear;
7053 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007054 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007055 (framesRead - part1) * mFrameSize);
7056 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007057 }
7058 rear = mRsmpInRear += framesRead;
7059
7060 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007061
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007062 // loop over each active track
7063 for (size_t i = 0; i < size; i++) {
7064 activeTrack = activeTracks[i];
7065
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007066 // skip fast tracks, as those are handled directly by FastCapture
7067 if (activeTrack->isFastTrack()) {
7068 continue;
7069 }
7070
Andy Hung73c02e42015-03-29 01:13:58 -07007071 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007072 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7073
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007074 enum {
7075 OVERRUN_UNKNOWN,
7076 OVERRUN_TRUE,
7077 OVERRUN_FALSE
7078 } overrun = OVERRUN_UNKNOWN;
7079
7080 // loop over getNextBuffer to handle circular sink
7081 for (;;) {
7082
7083 activeTrack->mSink.frameCount = ~0;
7084 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7085 size_t framesOut = activeTrack->mSink.frameCount;
7086 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7087
Andy Hung73c02e42015-03-29 01:13:58 -07007088 // check available frames and handle overrun conditions
7089 // if the record track isn't draining fast enough.
7090 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007091 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007092 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7093 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007094 overrun = OVERRUN_TRUE;
7095 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007096 if (framesOut == 0 || framesIn == 0) {
7097 break;
7098 }
7099
Andy Hung6770c6f2015-04-07 13:43:36 -07007100 // Don't allow framesOut to be larger than what is possible with resampling
7101 // from framesIn.
7102 // This isn't strictly necessary but helps limit buffer resizing in
7103 // RecordBufferConverter. TODO: remove when no longer needed.
7104 framesOut = min(framesOut,
7105 destinationFramesPossible(
7106 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007107
7108 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007109 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007110 // straight from RecordThread buffer to RecordTrack buffer.
7111 AudioBufferProvider::Buffer buffer;
7112 buffer.frameCount = framesOut;
7113 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7114 if (status == OK && buffer.frameCount != 0) {
7115 ALOGV_IF(buffer.frameCount != framesOut,
7116 "%s() read less than expected (%zu vs %zu)",
7117 __func__, buffer.frameCount, framesOut);
7118 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007119 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007120 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7121 } else {
7122 framesOut = 0;
7123 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7124 __func__, status, buffer.frameCount);
7125 }
7126 } else {
7127 // process frames from the RecordThread buffer provider to the RecordTrack
7128 // buffer
7129 framesOut = activeTrack->mRecordBufferConverter->convert(
7130 activeTrack->mSink.raw,
7131 activeTrack->mResamplerBufferProvider,
7132 framesOut);
7133 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007134
7135 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7136 overrun = OVERRUN_FALSE;
7137 }
7138
7139 if (activeTrack->mFramesToDrop == 0) {
7140 if (framesOut > 0) {
7141 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007142 // Sanitize before releasing if the track has no access to the source data
7143 // An idle UID receives silence from non virtual devices until active
7144 if (activeTrack->isSilenced()) {
7145 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
7146 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007147 activeTrack->releaseBuffer(&activeTrack->mSink);
7148 }
7149 } else {
7150 // FIXME could do a partial drop of framesOut
7151 if (activeTrack->mFramesToDrop > 0) {
7152 activeTrack->mFramesToDrop -= framesOut;
7153 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007154 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007155 }
7156 } else {
7157 activeTrack->mFramesToDrop += framesOut;
7158 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7159 activeTrack->mSyncStartEvent->isCancelled()) {
7160 ALOGW("Synced record %s, session %d, trigger session %d",
7161 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7162 activeTrack->sessionId(),
7163 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007164 activeTrack->mSyncStartEvent->triggerSession() :
7165 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007166 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007167 }
7168 }
7169 }
7170
7171 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007172 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007173 }
7174 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007175
7176 switch (overrun) {
7177 case OVERRUN_TRUE:
7178 // client isn't retrieving buffers fast enough
7179 if (!activeTrack->setOverflow()) {
7180 nsecs_t now = systemTime();
7181 // FIXME should lastWarning per track?
7182 if ((now - lastWarning) > kWarningThrottleNs) {
7183 ALOGW("RecordThread: buffer overflow");
7184 lastWarning = now;
7185 }
7186 }
7187 break;
7188 case OVERRUN_FALSE:
7189 activeTrack->clearOverflow();
7190 break;
7191 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007192 break;
7193 }
7194
Andy Hung3f0c9022016-01-15 17:49:46 -08007195 // update frame information and push timestamp out
7196 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007197 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007198 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7199 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007200 }
7201
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007202unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007203 // enable changes in effect chain
7204 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007205 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08007206 }
7207
Glenn Kasten93e471f2013-08-19 08:40:07 -07007208 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007209
7210 {
7211 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007212 for (size_t i = 0; i < mTracks.size(); i++) {
7213 sp<RecordTrack> track = mTracks[i];
7214 track->invalidate();
7215 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007216 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007217 mStartStopCond.broadcast();
7218 }
7219
7220 releaseWakeLock();
7221
7222 ALOGV("RecordThread %p exiting", this);
7223 return false;
7224}
7225
Glenn Kasten93e471f2013-08-19 08:40:07 -07007226void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007227{
7228 if (!mStandby) {
7229 inputStandBy();
7230 mStandby = true;
7231 }
7232}
7233
7234void AudioFlinger::RecordThread::inputStandBy()
7235{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007236 // Idle the fast capture if it's currently running
7237 if (mFastCapture != 0) {
7238 FastCaptureStateQueue *sq = mFastCapture->sq();
7239 FastCaptureState *state = sq->begin();
7240 if (!(state->mCommand & FastCaptureState::IDLE)) {
7241 state->mCommand = FastCaptureState::COLD_IDLE;
7242 state->mColdFutexAddr = &mFastCaptureFutex;
7243 state->mColdGen++;
7244 mFastCaptureFutex = 0;
7245 sq->end();
7246 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7247 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7248#if 0
7249 if (kUseFastCapture == FastCapture_Dynamic) {
7250 // FIXME
7251 }
7252#endif
7253#ifdef AUDIO_WATCHDOG
7254 // FIXME
7255#endif
7256 } else {
7257 sq->end(false /*didModify*/);
7258 }
7259 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007260 status_t result = mInput->stream->standby();
7261 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007262
7263 // If going into standby, flush the pipe source.
7264 if (mPipeSource.get() != nullptr) {
7265 const ssize_t flushed = mPipeSource->flush();
7266 if (flushed > 0) {
7267 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7268 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7269 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7270 }
7271 }
Eric Laurent81784c32012-11-19 14:55:58 -08007272}
7273
Glenn Kasten05997e22014-03-13 15:08:33 -07007274// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007275sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007276 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007277 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007278 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007279 audio_format_t format,
7280 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007281 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007282 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007283 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007284 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007285 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007286 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007287 status_t *status,
7288 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007289{
Glenn Kasten74935e42013-12-19 08:56:45 -08007290 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007291 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007292 sp<RecordTrack> track;
7293 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007294 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007295 audio_input_flags_t requestedFlags = *flags;
7296 uint32_t sampleRate;
7297
7298 lStatus = initCheck();
7299 if (lStatus != NO_ERROR) {
7300 ALOGE("createRecordTrack_l() audio driver not initialized");
7301 goto Exit;
7302 }
7303
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007304 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7305 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7306 lStatus = BAD_VALUE;
7307 goto Exit;
7308 }
7309
Eric Laurentf14db3c2017-12-08 14:20:36 -08007310 if (*pSampleRate == 0) {
7311 *pSampleRate = mSampleRate;
7312 }
7313 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007314
7315 // special case for FAST flag considered OK if fast capture is present
7316 if (hasFastCapture()) {
7317 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7318 }
7319
Eric Laurentf14db3c2017-12-08 14:20:36 -08007320 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007321 if ((*flags & inputFlags) != *flags) {
7322 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7323 " input flags (%08x)",
7324 *flags, inputFlags);
7325 *flags = (audio_input_flags_t)(*flags & inputFlags);
7326 }
Eric Laurent81784c32012-11-19 14:55:58 -08007327
Glenn Kasten90e58b12013-07-31 16:16:02 -07007328 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007329 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007330 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007331 // we formerly checked for a callback handler (non-0 tid),
7332 // but that is no longer required for TRANSFER_OBTAIN mode
7333 //
Glenn Kasten74105912014-07-03 12:28:53 -07007334 // frame count is not specified, or is exactly the pipe depth
7335 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007336 // PCM data
7337 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007338 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007339 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007340 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007341 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007342 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007343 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007344 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007345 hasFastCapture() &&
7346 // there are sufficient fast track slots available
7347 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007348 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007349 // check compatibility with audio effects.
7350 Mutex::Autolock _l(mLock);
7351 // Do not accept FAST flag if the session has software effects
7352 sp<EffectChain> chain = getEffectChain_l(sessionId);
7353 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007354 audio_input_flags_t old = *flags;
7355 chain->checkInputFlagCompatibility(flags);
7356 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007357 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7358 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007359 }
7360 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007361 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007362 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7363 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007364 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007365 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7366 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007367 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007368 this, frameCount, mFrameCount, mPipeFramesP2,
7369 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007370 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007371 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007372 }
7373 }
7374
Eric Laurentf14db3c2017-12-08 14:20:36 -08007375 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7376 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7377 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7378 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7379 lStatus = BAD_TYPE;
7380 goto Exit;
7381 }
7382
Glenn Kasten74105912014-07-03 12:28:53 -07007383 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007384 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007385 // fast track: frame count is exactly the pipe depth
7386 frameCount = mPipeFramesP2;
7387 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007388 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007389 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007390 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7391 // or 20 ms if there is a fast capture
7392 // TODO This could be a roundupRatio inline, and const
7393 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7394 * sampleRate + mSampleRate - 1) / mSampleRate;
7395 // minimum number of notification periods is at least kMinNotifications,
7396 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7397 static const size_t kMinNotifications = 3;
7398 static const uint32_t kMinMs = 30;
7399 // TODO This could be a roundupRatio inline
7400 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7401 // TODO This could be a roundupRatio inline
7402 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7403 maxNotificationFrames;
7404 const size_t minFrameCount = maxNotificationFrames *
7405 max(kMinNotifications, minNotificationsByMs);
7406 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007407 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7408 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007409 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007410 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007411 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007412 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007413
7414 { // scope for mLock
7415 Mutex::Autolock _l(mLock);
7416
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007417 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007418 format, channelMask, frameCount,
7419 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007420 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007421
Glenn Kasten03003332013-08-06 15:40:54 -07007422 lStatus = track->initCheck();
7423 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007424 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007425 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007426 goto Exit;
7427 }
7428 mTracks.add(track);
7429
Eric Laurent05067782016-06-01 18:27:28 -07007430 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007431 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7432 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7433 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007434 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007435 }
Eric Laurent81784c32012-11-19 14:55:58 -08007436 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007437
Eric Laurent81784c32012-11-19 14:55:58 -08007438 lStatus = NO_ERROR;
7439
7440Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007441 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007442 return track;
7443}
7444
7445status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7446 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007447 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007448{
7449 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7450 sp<ThreadBase> strongMe = this;
7451 status_t status = NO_ERROR;
7452
7453 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007454 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007455 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007456 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007457 triggerSession,
7458 recordTrack->sessionId(),
7459 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007460 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007461 // Sync event can be cancelled by the trigger session if the track is not in a
7462 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007463 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007464 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007465 } else {
7466 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007467 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007468 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007469 }
7470 }
7471
7472 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007473 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007474 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007475 if (recordTrack->isInvalid()) {
7476 recordTrack->clearSyncStartEvent();
7477 return INVALID_OPERATION;
7478 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007479 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7480 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007481 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7482 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007483 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007484 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007485 } else {
7486 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007487 }
7488 return status;
7489 }
7490
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007491 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7492 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7493 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007494 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007495 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007496 status_t status = NO_ERROR;
7497 if (recordTrack->isExternalTrack()) {
7498 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007499 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007500 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007501 if (recordTrack->isInvalid()) {
7502 recordTrack->clearSyncStartEvent();
7503 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7504 recordTrack->mState = TrackBase::STARTING_2;
7505 // STARTING_2 forces destroy to call stopInput.
7506 }
7507 return INVALID_OPERATION;
7508 }
7509 if (recordTrack->mState != TrackBase::STARTING_1) {
7510 ALOGW("%s(%d): unsynchronized mState:%d change",
7511 __func__, recordTrack->id(), recordTrack->mState);
7512 // Someone else has changed state, let them take over,
7513 // leave mState in the new state.
7514 recordTrack->clearSyncStartEvent();
7515 return INVALID_OPERATION;
7516 }
7517 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007518 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007519 ALOGW("%s(%d): startInput failed, status %d",
7520 __func__, recordTrack->id(), status);
7521 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7522 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007523 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007524 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007525 return status;
7526 }
Eric Laurent81784c32012-11-19 14:55:58 -08007527 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007528 // Catch up with current buffer indices if thread is already running.
7529 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7530 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7531 // see previously buffered data before it called start(), but with greater risk of overrun.
7532
Andy Hung73c02e42015-03-29 01:13:58 -07007533 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007534 if (!recordTrack->isDirect()) {
7535 // clear any converter state as new data will be discontinuous
7536 recordTrack->mRecordBufferConverter->reset();
7537 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007538 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007539 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007540 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007541 return status;
7542 }
Eric Laurent81784c32012-11-19 14:55:58 -08007543}
7544
Eric Laurent81784c32012-11-19 14:55:58 -08007545void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7546{
7547 sp<SyncEvent> strongEvent = event.promote();
7548
7549 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007550 sp<RefBase> ptr = strongEvent->cookie().promote();
7551 if (ptr != 0) {
7552 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7553 recordTrack->handleSyncStartEvent(strongEvent);
7554 }
Eric Laurent81784c32012-11-19 14:55:58 -08007555 }
7556}
7557
Glenn Kastena8356f62013-07-25 14:37:52 -07007558bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007559 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007560 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007561 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007562 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007563 return false;
7564 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007565 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007566 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007567
7568 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7569 mWaitWorkCV.broadcast(); // signal thread to stop
7570 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007571 }
Andy Hungce685402018-10-05 17:23:27 -07007572
7573 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007574 ALOGV("Record stopped OK");
7575 return true;
7576 }
Andy Hungce685402018-10-05 17:23:27 -07007577
7578 // don't handle anything - we've been invalidated or restarted and in a different state
7579 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7580 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007581 return false;
7582}
7583
Glenn Kasten0f11b512014-01-31 16:18:54 -08007584bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007585{
7586 return false;
7587}
7588
Glenn Kasten0f11b512014-01-31 16:18:54 -08007589status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007590{
7591#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7592 if (!isValidSyncEvent(event)) {
7593 return BAD_VALUE;
7594 }
7595
Glenn Kastend848eb42016-03-08 13:42:11 -08007596 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007597 status_t ret = NAME_NOT_FOUND;
7598
7599 Mutex::Autolock _l(mLock);
7600
7601 for (size_t i = 0; i < mTracks.size(); i++) {
7602 sp<RecordTrack> track = mTracks[i];
7603 if (eventSession == track->sessionId()) {
7604 (void) track->setSyncEvent(event);
7605 ret = NO_ERROR;
7606 }
7607 }
7608 return ret;
7609#else
7610 return BAD_VALUE;
7611#endif
7612}
7613
jiabin653cc0a2018-01-17 17:54:10 -08007614status_t AudioFlinger::RecordThread::getActiveMicrophones(
7615 std::vector<media::MicrophoneInfo>* activeMicrophones)
7616{
7617 ALOGV("RecordThread::getActiveMicrophones");
7618 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007619 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7620 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007621}
7622
Paul McLean03a6e6a2018-12-04 10:54:13 -07007623status_t AudioFlinger::RecordThread::setMicrophoneDirection(audio_microphone_direction_t direction)
7624{
7625 ALOGV("RecordThread::setMicrophoneDirection");
7626 AutoMutex _l(mLock);
7627 return mInput->stream->setMicrophoneDirection(direction);
7628}
7629
7630status_t AudioFlinger::RecordThread::setMicrophoneFieldDimension(float zoom)
7631{
7632 ALOGV("RecordThread::setMicrophoneFieldDimension");
7633 AutoMutex _l(mLock);
7634 return mInput->stream->setMicrophoneFieldDimension(zoom);
7635}
7636
Kevin Rocard069c2712018-03-29 19:09:14 -07007637void AudioFlinger::RecordThread::updateMetadata_l()
7638{
7639 if (mInput == nullptr || mInput->stream == nullptr ||
7640 !mActiveTracks.readAndClearHasChanged()) {
7641 return;
7642 }
7643 StreamInHalInterface::SinkMetadata metadata;
7644 for (const sp<RecordTrack> &track : mActiveTracks) {
7645 // No track is invalid as this is called after prepareTrack_l in the same critical section
7646 metadata.tracks.push_back({
7647 .source = track->attributes().source,
7648 .gain = 1, // capture tracks do not have volumes
7649 });
7650 }
7651 mInput->stream->updateSinkMetadata(metadata);
7652}
7653
Eric Laurent81784c32012-11-19 14:55:58 -08007654// destroyTrack_l() must be called with ThreadBase::mLock held
7655void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7656{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007657 track->terminate();
7658 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007659 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007660 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007661 removeTrack_l(track);
7662 }
7663}
7664
7665void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7666{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007667 String8 result;
7668 track->appendDump(result, false /* active */);
7669 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7670
Eric Laurent81784c32012-11-19 14:55:58 -08007671 mTracks.remove(track);
7672 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007673 if (track->isFastTrack()) {
7674 ALOG_ASSERT(!mFastTrackAvail);
7675 mFastTrackAvail = true;
7676 }
Eric Laurent81784c32012-11-19 14:55:58 -08007677}
7678
7679void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7680{
7681 dumpInternals(fd, args);
7682 dumpTracks(fd, args);
7683 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007684 dprintf(fd, " Local log:\n");
7685 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007686}
7687
7688void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7689{
Glenn Kasten44182c22015-03-05 17:12:23 -08007690 dumpBase(fd, args);
7691
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007692 AudioStreamIn *input = mInput;
7693 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7694 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7695 input, flags, inputFlagsToString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007696 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007697 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007698 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007699 }
Andy Hungbfa64962017-06-12 14:43:19 -07007700
7701 if (input != nullptr) {
7702 dprintf(fd, " Hal stream dump:\n");
7703 (void)input->stream->dump(fd);
7704 }
7705
Mikhail Naganovf4a342a2018-12-04 08:55:41 -08007706 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hung7f39f562018-08-08 17:30:20 -07007707 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
Andy Hung20bd30b2018-06-01 15:39:35 -07007708 if (latencyMs != 0.) {
7709 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7710 } else {
7711 dprintf(fd, " NormalRecord latency ms: unavail\n");
7712 }
7713
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007714 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007715 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007716
Glenn Kasten2f90c512015-12-02 11:40:09 -08007717 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7718 // while we are dumping it. It may be inconsistent, but it won't mutate!
7719 // This is a large object so we place it on the heap.
7720 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007721 const std::unique_ptr<FastCaptureDumpState> copy =
7722 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007723 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007724}
7725
Glenn Kasten0f11b512014-01-31 16:18:54 -08007726void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007727{
Eric Laurent81784c32012-11-19 14:55:58 -08007728 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007729 size_t numtracks = mTracks.size();
7730 size_t numactive = mActiveTracks.size();
7731 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007732 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007733 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007734 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007735 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007736 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007737 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007738 for (size_t i = 0; i < numtracks ; ++i) {
7739 sp<RecordTrack> track = mTracks[i];
7740 if (track != 0) {
7741 bool active = mActiveTracks.indexOf(track) >= 0;
7742 if (active) {
7743 numactiveseen++;
7744 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007745 result.append(prefix);
7746 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007747 }
Eric Laurent81784c32012-11-19 14:55:58 -08007748 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007749 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007750 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007751 }
7752
Marco Nelissenb2208842014-02-07 14:00:50 -08007753 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007754 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007755 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007756 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007757 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007758 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007759 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007760 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007761 result.append(prefix);
7762 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007763 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007764 }
Eric Laurent81784c32012-11-19 14:55:58 -08007765
7766 }
7767 write(fd, result.string(), result.size());
7768}
7769
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007770void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7771{
7772 Mutex::Autolock _l(mLock);
7773 for (size_t i = 0; i < mTracks.size() ; i++) {
7774 sp<RecordTrack> track = mTracks[i];
7775 if (track != 0 && track->uid() == uid) {
7776 track->setSilenced(silenced);
7777 }
7778 }
7779}
Andy Hung73c02e42015-03-29 01:13:58 -07007780
7781void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7782{
7783 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7784 RecordThread *recordThread = (RecordThread *) threadBase.get();
7785 mRsmpInFront = recordThread->mRsmpInRear;
7786 mRsmpInUnrel = 0;
7787}
7788
7789void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7790 size_t *framesAvailable, bool *hasOverrun)
7791{
7792 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7793 RecordThread *recordThread = (RecordThread *) threadBase.get();
7794 const int32_t rear = recordThread->mRsmpInRear;
7795 const int32_t front = mRsmpInFront;
7796 const ssize_t filled = rear - front;
7797
7798 size_t framesIn;
7799 bool overrun = false;
7800 if (filled < 0) {
7801 // should not happen, but treat like a massive overrun and re-sync
7802 framesIn = 0;
7803 mRsmpInFront = rear;
7804 overrun = true;
7805 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7806 framesIn = (size_t) filled;
7807 } else {
7808 // client is not keeping up with server, but give it latest data
7809 framesIn = recordThread->mRsmpInFrames;
7810 mRsmpInFront = /* front = */ rear - framesIn;
7811 overrun = true;
7812 }
7813 if (framesAvailable != NULL) {
7814 *framesAvailable = framesIn;
7815 }
7816 if (hasOverrun != NULL) {
7817 *hasOverrun = overrun;
7818 }
7819}
7820
Eric Laurent81784c32012-11-19 14:55:58 -08007821// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007822status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007823 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007824{
Andy Hung73c02e42015-03-29 01:13:58 -07007825 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007826 if (threadBase == 0) {
7827 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007828 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007829 return NOT_ENOUGH_DATA;
7830 }
7831 RecordThread *recordThread = (RecordThread *) threadBase.get();
7832 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007833 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007834 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007835 // FIXME should not be P2 (don't want to increase latency)
7836 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007837 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007838 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007839 front &= recordThread->mRsmpInFramesP2 - 1;
7840 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007841 if (part1 > (size_t) filled) {
7842 part1 = filled;
7843 }
7844 size_t ask = buffer->frameCount;
7845 ALOG_ASSERT(ask > 0);
7846 if (part1 > ask) {
7847 part1 = ask;
7848 }
7849 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007850 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007851 buffer->raw = NULL;
7852 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007853 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007854 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007855 }
7856
Andy Hung57446612015-04-19 23:56:46 -07007857 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007858 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007859 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007860 return NO_ERROR;
7861}
7862
7863// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007864void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7865 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007866{
Glenn Kasten85948432013-08-19 12:09:05 -07007867 size_t stepCount = buffer->frameCount;
7868 if (stepCount == 0) {
7869 return;
7870 }
Andy Hung73c02e42015-03-29 01:13:58 -07007871 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7872 mRsmpInUnrel -= stepCount;
7873 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007874 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007875 buffer->frameCount = 0;
7876}
7877
Eric Laurentd8365c52017-07-16 15:27:05 -07007878void AudioFlinger::RecordThread::checkBtNrec()
7879{
7880 Mutex::Autolock _l(mLock);
7881 checkBtNrec_l();
7882}
7883
7884void AudioFlinger::RecordThread::checkBtNrec_l()
7885{
7886 // disable AEC and NS if the device is a BT SCO headset supporting those
7887 // pre processings
7888 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7889 mAudioFlinger->btNrecIsOff();
7890 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7891 for (size_t i = 0; i < mEffectChains.size(); i++) {
7892 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7893 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7894 }
7895 }
7896}
7897
Andy Hung97a893e2015-03-29 01:03:07 -07007898
Eric Laurent10351942014-05-08 18:49:52 -07007899bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7900 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007901{
7902 bool reconfig = false;
7903
Eric Laurent10351942014-05-08 18:49:52 -07007904 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007905
Eric Laurent10351942014-05-08 18:49:52 -07007906 audio_format_t reqFormat = mFormat;
7907 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007908 // 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 -07007909 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7910
7911 AudioParameter param = AudioParameter(keyValuePair);
7912 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007913
7914 // scope for AutoPark extends to end of method
7915 AutoPark<FastCapture> park(mFastCapture);
7916
Eric Laurent10351942014-05-08 18:49:52 -07007917 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7918 // channel count change can be requested. Do we mandate the first client defines the
7919 // HAL sampling rate and channel count or do we allow changes on the fly?
7920 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7921 samplingRate = value;
7922 reconfig = true;
7923 }
7924 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007925 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007926 status = BAD_VALUE;
7927 } else {
7928 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007929 reconfig = true;
7930 }
Eric Laurent10351942014-05-08 18:49:52 -07007931 }
7932 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7933 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007934 if (!audio_is_input_channel(mask) ||
7935 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007936 status = BAD_VALUE;
7937 } else {
7938 channelMask = mask;
7939 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007940 }
Eric Laurent10351942014-05-08 18:49:52 -07007941 }
7942 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7943 // do not accept frame count changes if tracks are open as the track buffer
7944 // size depends on frame count and correct behavior would not be guaranteed
7945 // if frame count is changed after track creation
7946 if (mActiveTracks.size() > 0) {
7947 status = INVALID_OPERATION;
7948 } else {
7949 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007950 }
Eric Laurent10351942014-05-08 18:49:52 -07007951 }
7952 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7953 // forward device change to effects that have requested to be
7954 // aware of attached audio device.
7955 for (size_t i = 0; i < mEffectChains.size(); i++) {
7956 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007957 }
Eric Laurent81784c32012-11-19 14:55:58 -08007958
Eric Laurent10351942014-05-08 18:49:52 -07007959 // store input device and output device but do not forward output device to audio HAL.
7960 // Note that status is ignored by the caller for output device
7961 // (see AudioFlinger::setParameters()
7962 if (audio_is_output_devices(value)) {
7963 mOutDevice = value;
7964 status = BAD_VALUE;
7965 } else {
7966 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007967 if (value != AUDIO_DEVICE_NONE) {
7968 mPrevInDevice = value;
7969 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007970 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007971 }
Eric Laurent10351942014-05-08 18:49:52 -07007972 }
7973 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7974 mAudioSource != (audio_source_t)value) {
7975 // forward device change to effects that have requested to be
7976 // aware of attached audio device.
7977 for (size_t i = 0; i < mEffectChains.size(); i++) {
7978 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007979 }
Eric Laurent10351942014-05-08 18:49:52 -07007980 mAudioSource = (audio_source_t)value;
7981 }
Glenn Kastene198c362013-08-13 09:13:36 -07007982
Eric Laurent10351942014-05-08 18:49:52 -07007983 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007984 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007985 if (status == INVALID_OPERATION) {
7986 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007987 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007988 }
7989 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007990 if (status == BAD_VALUE) {
7991 uint32_t sRate;
7992 audio_channel_mask_t channelMask;
7993 audio_format_t format;
7994 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7995 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7996 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7997 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7998 status = NO_ERROR;
7999 }
Eric Laurent81784c32012-11-19 14:55:58 -08008000 }
Eric Laurent10351942014-05-08 18:49:52 -07008001 if (status == NO_ERROR) {
8002 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008003 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008004 }
8005 }
Eric Laurent81784c32012-11-19 14:55:58 -08008006 }
Eric Laurent10351942014-05-08 18:49:52 -07008007
Eric Laurent81784c32012-11-19 14:55:58 -08008008 return reconfig;
8009}
8010
8011String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8012{
Eric Laurent81784c32012-11-19 14:55:58 -08008013 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008014 if (initCheck() == NO_ERROR) {
8015 String8 out_s8;
8016 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8017 return out_s8;
8018 }
Eric Laurent81784c32012-11-19 14:55:58 -08008019 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008020 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008021}
8022
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008023void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008024 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8025
8026 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008027
8028 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008029 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008030 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008031 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008032 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008033 desc->mChannelMask = mChannelMask;
8034 desc->mSamplingRate = mSampleRate;
8035 desc->mFormat = mFormat;
8036 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008037 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008038 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008039 break;
8040
Eric Laurent73e26b62015-04-27 16:55:58 -07008041 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008042 default:
8043 break;
8044 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008045 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008046}
8047
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008048void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008049{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008050 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8051 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008052 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008053 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8054 if (audio_is_linear_pcm(mFormat)) {
8055 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8056 mChannelCount, FCC_8);
8057 } else {
8058 // Can have more that FCC_8 channels in encoded streams.
8059 ALOGI("HAL format %#x is not linear pcm", mFormat);
8060 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008061 result = mInput->stream->getFrameSize(&mFrameSize);
8062 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8063 result = mInput->stream->getBufferSize(&mBufferSize);
8064 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008065 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008066 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
8067 "mBufferSize=%lld, mFrameCount=%lld",
8068 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
8069 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008070 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008071 // 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 -07008072 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008073 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008074 // A larger value should allow more old data to be read after a track calls start(),
8075 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008076 //
8077 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008078 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008079 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008080 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008081 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008082
8083 // TODO optimize audio capture buffer sizes ...
8084 // Here we calculate the size of the sliding buffer used as a source
8085 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8086 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8087 // be better to have it derived from the pipe depth in the long term.
8088 // The current value is higher than necessary. However it should not add to latency.
8089
Glenn Kasten85948432013-08-19 12:09:05 -07008090 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008091 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8092 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008093 // if posix_memalign fails, will segv here.
8094 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008095
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008096 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8097 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08008098}
8099
Glenn Kasten5f972c02014-01-13 09:59:31 -08008100uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008101{
8102 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008103 uint32_t result;
8104 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8105 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008106 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008107 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008108}
8109
Eric Laurent4c415062016-06-17 16:14:16 -07008110// hasAudioSession_l() must be called with ThreadBase::mLock held
8111uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08008112{
Eric Laurent81784c32012-11-19 14:55:58 -08008113 uint32_t result = 0;
8114 if (getEffectChain_l(sessionId) != 0) {
8115 result = EFFECT_SESSION;
8116 }
8117
8118 for (size_t i = 0; i < mTracks.size(); ++i) {
8119 if (sessionId == mTracks[i]->sessionId()) {
8120 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07008121 if (mTracks[i]->isFastTrack()) {
8122 result |= FAST_SESSION;
8123 }
Eric Laurent81784c32012-11-19 14:55:58 -08008124 break;
8125 }
8126 }
8127
8128 return result;
8129}
8130
Glenn Kastend848eb42016-03-08 13:42:11 -08008131KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008132{
Glenn Kastend848eb42016-03-08 13:42:11 -08008133 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008134 Mutex::Autolock _l(mLock);
8135 for (size_t j = 0; j < mTracks.size(); ++j) {
8136 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008137 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008138 if (ids.indexOfKey(sessionId) < 0) {
8139 ids.add(sessionId, true);
8140 }
8141 }
8142 return ids;
8143}
8144
8145AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8146{
8147 Mutex::Autolock _l(mLock);
8148 AudioStreamIn *input = mInput;
8149 mInput = NULL;
8150 return input;
8151}
8152
8153// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008154sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008155{
8156 if (mInput == NULL) {
8157 return NULL;
8158 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008159 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008160}
8161
8162status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8163{
8164 // only one chain per input thread
Eric Tan39ec8d62018-07-24 09:49:29 -07008165 if (!mEffectChains.isEmpty()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07008166 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08008167 return INVALID_OPERATION;
8168 }
8169 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008170 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008171 chain->setInBuffer(NULL);
8172 chain->setOutBuffer(NULL);
8173
8174 checkSuspendOnAddEffectChain_l(chain);
8175
Eric Laurent1b928682014-10-02 19:41:47 -07008176 // make sure enabled pre processing effects state is communicated to the HAL as we
8177 // just moved them to a new input stream.
8178 chain->syncHalEffectsState();
8179
Eric Laurent81784c32012-11-19 14:55:58 -08008180 mEffectChains.add(chain);
8181
8182 return NO_ERROR;
8183}
8184
8185size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8186{
8187 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
8188 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008189 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08008190 chain.get(), mEffectChains.size(), this);
8191 if (mEffectChains.size() == 1) {
8192 mEffectChains.removeAt(0);
8193 }
8194 return 0;
8195}
8196
Eric Laurent1c333e22014-05-20 10:48:17 -07008197status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8198 audio_patch_handle_t *handle)
8199{
8200 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008201
8202 // store new device and send to effects
8203 mInDevice = patch->sources[0].ext.device.type;
François Gaffie0c280aa2018-07-25 10:02:15 +02008204 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent296fb132015-05-01 11:38:42 -07008205 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07008206 for (size_t i = 0; i < mEffectChains.size(); i++) {
8207 mEffectChains[i]->setDevice_l(mInDevice);
8208 }
8209
Eric Laurentd8365c52017-07-16 15:27:05 -07008210 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008211
8212 // store new source and send to effects
8213 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8214 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008215 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008216 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008217 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008218 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008219
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008220 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008221 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8222 status = hwDevice->createAudioPatch(patch->num_sources,
8223 patch->sources,
8224 patch->num_sinks,
8225 patch->sinks,
8226 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008227 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008228 char *address;
8229 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8230 address = audio_device_address_to_parameter(
8231 patch->sources[0].ext.device.type,
8232 patch->sources[0].ext.device.address);
8233 } else {
8234 address = (char *)calloc(1, 1);
8235 }
8236 AudioParameter param = AudioParameter(String8(address));
8237 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008238 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008239 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008240 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008241 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008242 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008243 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008244 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008245
François Gaffie0c280aa2018-07-25 10:02:15 +02008246 if ((mInDevice != mPrevInDevice) || (mDeviceId != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008247 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8248 mPrevInDevice = mInDevice;
François Gaffie0c280aa2018-07-25 10:02:15 +02008249 mDeviceId = deviceId;
Eric Laurente8726fe2015-06-26 09:39:24 -07008250 }
Eric Laurent296fb132015-05-01 11:38:42 -07008251
Eric Laurent1c333e22014-05-20 10:48:17 -07008252 return status;
8253}
8254
8255status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8256{
8257 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008258
8259 mInDevice = AUDIO_DEVICE_NONE;
8260
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008261 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008262 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8263 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008264 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008265 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008266 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008267 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008268 }
8269 return status;
8270}
8271
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008272void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008273{
8274 Mutex::Autolock _l(mLock);
8275 mTracks.add(record);
8276}
8277
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008278void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008279{
8280 Mutex::Autolock _l(mLock);
8281 destroyTrack_l(record);
8282}
8283
Mikhail Naganovdc769682018-05-04 15:34:08 -07008284void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008285{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008286 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008287 config->role = AUDIO_PORT_ROLE_SINK;
8288 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8289 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008290 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8291 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8292 config->flags.input = mInput->flags;
8293 }
Eric Laurent83b88082014-06-20 18:31:16 -07008294}
Eric Laurent1c333e22014-05-20 10:48:17 -07008295
Eric Laurent6acd1d42017-01-04 14:23:29 -08008296// ----------------------------------------------------------------------------
8297// Mmap
8298// ----------------------------------------------------------------------------
8299
8300AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8301 : mThread(thread)
8302{
Phil Burk9fabbf82017-08-03 12:02:00 -07008303 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008304}
8305
8306AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8307{
Phil Burk9fabbf82017-08-03 12:02:00 -07008308 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008309}
8310
8311status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8312 struct audio_mmap_buffer_info *info)
8313{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008314 return mThread->createMmapBuffer(minSizeFrames, info);
8315}
8316
8317status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8318{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008319 return mThread->getMmapPosition(position);
8320}
8321
Eric Laurenta54f1282017-07-01 19:39:32 -07008322status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008323 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008324
8325{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008326 return mThread->start(client, handle);
8327}
8328
8329status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8330{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008331 return mThread->stop(handle);
8332}
8333
Eric Laurent18b57012017-02-13 16:23:52 -08008334status_t AudioFlinger::MmapThreadHandle::standby()
8335{
Eric Laurent18b57012017-02-13 16:23:52 -08008336 return mThread->standby();
8337}
8338
Eric Laurent6acd1d42017-01-04 14:23:29 -08008339
8340AudioFlinger::MmapThread::MmapThread(
8341 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8342 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8343 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8344 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008345 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008346 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008347 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008348 mActiveTracks(&this->mLocalLog),
8349 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8350 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008351{
Eric Laurent18b57012017-02-13 16:23:52 -08008352 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008353 readHalParameters_l();
8354}
8355
8356AudioFlinger::MmapThread::~MmapThread()
8357{
Eric Laurent18b57012017-02-13 16:23:52 -08008358 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008359}
8360
8361void AudioFlinger::MmapThread::onFirstRef()
8362{
8363 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8364}
8365
8366void AudioFlinger::MmapThread::disconnect()
8367{
Eric Laurent331679c2018-04-16 17:03:16 -07008368 ActiveTracks<MmapTrack> activeTracks;
8369 {
8370 Mutex::Autolock _l(mLock);
8371 for (const sp<MmapTrack> &t : mActiveTracks) {
8372 activeTracks.add(t);
8373 }
8374 }
8375 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008376 stop(t->portId());
8377 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008378 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008379 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008380 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008381 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008382 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008383 }
8384}
8385
8386
8387void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8388 audio_stream_type_t streamType __unused,
8389 audio_session_t sessionId,
8390 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008391 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008392 audio_port_handle_t portId)
8393{
8394 mAttr = *attr;
8395 mSessionId = sessionId;
8396 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008397 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008398 mPortId = portId;
8399}
8400
8401status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8402 struct audio_mmap_buffer_info *info)
8403{
8404 if (mHalStream == 0) {
8405 return NO_INIT;
8406 }
Eric Laurent18b57012017-02-13 16:23:52 -08008407 mStandby = true;
8408 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008409 return mHalStream->createMmapBuffer(minSizeFrames, info);
8410}
8411
8412status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8413{
8414 if (mHalStream == 0) {
8415 return NO_INIT;
8416 }
8417 return mHalStream->getMmapPosition(position);
8418}
8419
Eric Laurent331679c2018-04-16 17:03:16 -07008420status_t AudioFlinger::MmapThread::exitStandby()
8421{
8422 status_t ret = mHalStream->start();
8423 if (ret != NO_ERROR) {
8424 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8425 return ret;
8426 }
8427 mStandby = false;
8428 return NO_ERROR;
8429}
8430
Eric Laurenta54f1282017-07-01 19:39:32 -07008431status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008432 audio_port_handle_t *handle)
8433{
Eric Laurenta54f1282017-07-01 19:39:32 -07008434 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8435 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008436 if (mHalStream == 0) {
8437 return NO_INIT;
8438 }
8439
8440 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008441
Eric Laurenta54f1282017-07-01 19:39:32 -07008442 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008443 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008444 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008445 }
8446
8447 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8448
8449 audio_io_handle_t io = mId;
8450 if (isOutput()) {
8451 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8452 config.sample_rate = mSampleRate;
8453 config.channel_mask = mChannelMask;
8454 config.format = mFormat;
8455 audio_stream_type_t stream = streamType();
8456 audio_output_flags_t flags =
8457 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008458 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008459 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8460 mSessionId,
8461 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008462 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008463 client.clientUid,
8464 &config,
8465 flags,
8466 &deviceId,
8467 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008468 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008469 audio_config_base_t config;
8470 config.sample_rate = mSampleRate;
8471 config.channel_mask = mChannelMask;
8472 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008473 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008474 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8475 mSessionId,
8476 client.clientPid,
8477 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008478 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008479 &config,
8480 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8481 &deviceId,
8482 &portId);
8483 }
8484 // APM should not chose a different input or output stream for the same set of attributes
8485 // and audo configuration
8486 if (ret != NO_ERROR || io != mId) {
8487 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8488 __FUNCTION__, ret, io, mId);
8489 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008490 }
8491
8492 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008493 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008494 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008495 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008496 }
8497
Eric Laurent331679c2018-04-16 17:03:16 -07008498 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008499 // abort if start is rejected by audio policy manager
8500 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008501 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008502 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008503 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008504 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008505 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008506 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008507 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008508 }
Eric Laurent331679c2018-04-16 17:03:16 -07008509 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008510 } else {
8511 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008512 }
8513 return PERMISSION_DENIED;
8514 }
8515
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008516 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8517 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008518 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008519
Eric Laurent4eb58f12018-12-07 16:41:02 -08008520 if (isOutput()) {
8521 // force volume update when a new track is added
8522 mHalVolFloat = -1.0f;
8523 } else if (!track->isSilenced_l()) {
8524 for (const sp<MmapTrack> &t : mActiveTracks) {
8525 if (t->isSilenced_l() && t->uid() != client.clientUid)
8526 t->invalidate();
8527 }
8528 }
8529
8530
Eric Laurent6acd1d42017-01-04 14:23:29 -08008531 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008532 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008533 if (chain != 0) {
8534 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8535 chain->incTrackCnt();
8536 chain->incActiveTrackCnt();
8537 }
8538
8539 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008540 broadcast_l();
8541
Eric Laurenta54f1282017-07-01 19:39:32 -07008542 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008543
8544 return NO_ERROR;
8545}
8546
8547status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8548{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008549 ALOGV("%s handle %d", __FUNCTION__, handle);
8550
8551 if (mHalStream == 0) {
8552 return NO_INIT;
8553 }
8554
Eric Laurenta54f1282017-07-01 19:39:32 -07008555 if (handle == mPortId) {
8556 mHalStream->stop();
8557 return NO_ERROR;
8558 }
8559
Eric Laurent331679c2018-04-16 17:03:16 -07008560 Mutex::Autolock _l(mLock);
8561
Eric Laurent6acd1d42017-01-04 14:23:29 -08008562 sp<MmapTrack> track;
8563 for (const sp<MmapTrack> &t : mActiveTracks) {
8564 if (handle == t->portId()) {
8565 track = t;
8566 break;
8567 }
8568 }
8569 if (track == 0) {
8570 return BAD_VALUE;
8571 }
8572
8573 mActiveTracks.remove(track);
8574
Eric Laurent331679c2018-04-16 17:03:16 -07008575 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008576 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008577 AudioSystem::stopOutput(track->portId());
8578 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008579 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008580 AudioSystem::stopInput(track->portId());
8581 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008582 }
Eric Laurent331679c2018-04-16 17:03:16 -07008583 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008584
8585 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8586 if (chain != 0) {
8587 chain->decActiveTrackCnt();
8588 chain->decTrackCnt();
8589 }
8590
8591 broadcast_l();
8592
Eric Laurent6acd1d42017-01-04 14:23:29 -08008593 return NO_ERROR;
8594}
8595
Eric Laurent18b57012017-02-13 16:23:52 -08008596status_t AudioFlinger::MmapThread::standby()
8597{
8598 ALOGV("%s", __FUNCTION__);
8599
8600 if (mHalStream == 0) {
8601 return NO_INIT;
8602 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008603 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008604 return INVALID_OPERATION;
8605 }
8606 mHalStream->standby();
8607 mStandby = true;
8608 releaseWakeLock();
8609 return NO_ERROR;
8610}
8611
Eric Laurent6acd1d42017-01-04 14:23:29 -08008612
8613void AudioFlinger::MmapThread::readHalParameters_l()
8614{
8615 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8616 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8617 mFormat = mHALFormat;
8618 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8619 result = mHalStream->getFrameSize(&mFrameSize);
8620 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8621 result = mHalStream->getBufferSize(&mBufferSize);
8622 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8623 mFrameCount = mBufferSize / mFrameSize;
8624}
8625
8626bool AudioFlinger::MmapThread::threadLoop()
8627{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008628 checkSilentMode_l();
8629
8630 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8631
8632 while (!exitPending())
8633 {
8634 Mutex::Autolock _l(mLock);
8635 Vector< sp<EffectChain> > effectChains;
8636
8637 if (mSignalPending) {
8638 // A signal was raised while we were unlocked
8639 mSignalPending = false;
8640 } else {
8641 if (mConfigEvents.isEmpty()) {
8642 // we're about to wait, flush the binder command buffer
8643 IPCThreadState::self()->flushCommands();
8644
8645 if (exitPending()) {
8646 break;
8647 }
8648
Eric Laurent6acd1d42017-01-04 14:23:29 -08008649 // wait until we have something to do...
8650 ALOGV("%s going to sleep", myName.string());
8651 mWaitWorkCV.wait(mLock);
8652 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008653
8654 checkSilentMode_l();
8655
8656 continue;
8657 }
8658 }
8659
8660 processConfigEvents_l();
8661
8662 processVolume_l();
8663
8664 checkInvalidTracks_l();
8665
8666 mActiveTracks.updatePowerState(this);
8667
Kevin Rocard069c2712018-03-29 19:09:14 -07008668 updateMetadata_l();
8669
Eric Laurent6acd1d42017-01-04 14:23:29 -08008670 lockEffectChains_l(effectChains);
8671 for (size_t i = 0; i < effectChains.size(); i ++) {
8672 effectChains[i]->process_l();
8673 }
8674 // enable changes in effect chain
8675 unlockEffectChains(effectChains);
8676 // Effect chains will be actually deleted here if they were removed from
8677 // mEffectChains list during mixing or effects processing
8678 }
8679
8680 threadLoop_exit();
8681
8682 if (!mStandby) {
8683 threadLoop_standby();
8684 mStandby = true;
8685 }
8686
Eric Laurent6acd1d42017-01-04 14:23:29 -08008687 ALOGV("Thread %p type %d exiting", this, mType);
8688 return false;
8689}
8690
8691// checkForNewParameter_l() must be called with ThreadBase::mLock held
8692bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8693 status_t& status)
8694{
8695 AudioParameter param = AudioParameter(keyValuePair);
8696 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008697 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008698 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008699 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008700 // forward device change to effects that have requested to be
8701 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008702 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008703 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008704 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008705 }
8706 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008707 if (audio_is_output_devices(device)) {
8708 mOutDevice = device;
8709 if (!isOutput()) {
8710 sendToHal = false;
8711 }
8712 } else {
8713 mInDevice = device;
8714 if (device != AUDIO_DEVICE_NONE) {
8715 mPrevInDevice = value;
8716 }
8717 // TODO: implement and call checkBtNrec_l();
8718 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008719 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008720 if (sendToHal) {
8721 status = mHalStream->setParameters(keyValuePair);
8722 } else {
8723 status = NO_ERROR;
8724 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008725
8726 return false;
8727}
8728
8729String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8730{
8731 Mutex::Autolock _l(mLock);
8732 String8 out_s8;
8733 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8734 return out_s8;
8735 }
8736 return String8();
8737}
8738
8739void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8740 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8741
8742 desc->mIoHandle = mId;
8743
8744 switch (event) {
8745 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008746 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008747 case AUDIO_INPUT_CONFIG_CHANGED:
8748 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008749 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008750 case AUDIO_OUTPUT_CONFIG_CHANGED:
8751 desc->mPatch = mPatch;
8752 desc->mChannelMask = mChannelMask;
8753 desc->mSamplingRate = mSampleRate;
8754 desc->mFormat = mFormat;
8755 desc->mFrameCount = mFrameCount;
8756 desc->mFrameCountHAL = mFrameCount;
8757 desc->mLatency = 0;
8758 break;
8759
8760 case AUDIO_INPUT_CLOSED:
8761 case AUDIO_OUTPUT_CLOSED:
8762 default:
8763 break;
8764 }
8765 mAudioFlinger->ioConfigChanged(event, desc, pid);
8766}
8767
8768status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8769 audio_patch_handle_t *handle)
8770{
8771 status_t status = NO_ERROR;
8772
8773 // store new device and send to effects
8774 audio_devices_t type = AUDIO_DEVICE_NONE;
8775 audio_port_handle_t deviceId;
8776 if (isOutput()) {
8777 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8778 type |= patch->sinks[i].ext.device.type;
8779 }
8780 deviceId = patch->sinks[0].id;
8781 } else {
8782 type = patch->sources[0].ext.device.type;
8783 deviceId = patch->sources[0].id;
8784 }
8785
8786 for (size_t i = 0; i < mEffectChains.size(); i++) {
8787 mEffectChains[i]->setDevice_l(type);
8788 }
8789
8790 if (isOutput()) {
8791 mOutDevice = type;
8792 } else {
8793 mInDevice = type;
8794 // store new source and send to effects
8795 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8796 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8797 for (size_t i = 0; i < mEffectChains.size(); i++) {
8798 mEffectChains[i]->setAudioSource_l(mAudioSource);
8799 }
8800 }
8801 }
8802
8803 if (mAudioHwDev->supportsAudioPatches()) {
8804 status = mHalDevice->createAudioPatch(patch->num_sources,
8805 patch->sources,
8806 patch->num_sinks,
8807 patch->sinks,
8808 handle);
8809 } else {
8810 char *address;
8811 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8812 //FIXME: we only support address on first sink with HAL version < 3.0
8813 address = audio_device_address_to_parameter(
8814 patch->sinks[0].ext.device.type,
8815 patch->sinks[0].ext.device.address);
8816 } else {
8817 address = (char *)calloc(1, 1);
8818 }
8819 AudioParameter param = AudioParameter(String8(address));
8820 free(address);
8821 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8822 if (!isOutput()) {
8823 param.addInt(String8(AudioParameter::keyInputSource),
8824 (int)patch->sinks[0].ext.mix.usecase.source);
8825 }
8826 status = mHalStream->setParameters(param.toString());
8827 *handle = AUDIO_PATCH_HANDLE_NONE;
8828 }
8829
François Gaffie0c280aa2018-07-25 10:02:15 +02008830 if (isOutput() && (mPrevOutDevice != mOutDevice || mDeviceId != deviceId)) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008831 mPrevOutDevice = type;
8832 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008833 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008834 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008835 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008836 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008837 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008838 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008839 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008840 }
François Gaffie0c280aa2018-07-25 10:02:15 +02008841 if (!isOutput() && (mPrevInDevice != mInDevice || mDeviceId != deviceId)) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008842 mPrevInDevice = type;
8843 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008844 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008845 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008846 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008847 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008848 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008849 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008850 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008851 }
8852 return status;
8853}
8854
8855status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8856{
8857 status_t status = NO_ERROR;
8858
8859 mInDevice = AUDIO_DEVICE_NONE;
8860
8861 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8862 supportsAudioPatches : false;
8863
8864 if (supportsAudioPatches) {
8865 status = mHalDevice->releaseAudioPatch(handle);
8866 } else {
8867 AudioParameter param;
8868 param.addInt(String8(AudioParameter::keyRouting), 0);
8869 status = mHalStream->setParameters(param.toString());
8870 }
8871 return status;
8872}
8873
Mikhail Naganovdc769682018-05-04 15:34:08 -07008874void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008875{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008876 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008877 if (isOutput()) {
8878 config->role = AUDIO_PORT_ROLE_SOURCE;
8879 config->ext.mix.hw_module = mAudioHwDev->handle();
8880 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8881 } else {
8882 config->role = AUDIO_PORT_ROLE_SINK;
8883 config->ext.mix.hw_module = mAudioHwDev->handle();
8884 config->ext.mix.usecase.source = mAudioSource;
8885 }
8886}
8887
8888status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8889{
8890 audio_session_t session = chain->sessionId();
8891
8892 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8893 // Attach all tracks with same session ID to this chain.
8894 // indicate all active tracks in the chain
8895 for (const sp<MmapTrack> &track : mActiveTracks) {
8896 if (session == track->sessionId()) {
8897 chain->incTrackCnt();
8898 chain->incActiveTrackCnt();
8899 }
8900 }
8901
8902 chain->setThread(this);
8903 chain->setInBuffer(nullptr);
8904 chain->setOutBuffer(nullptr);
8905 chain->syncHalEffectsState();
8906
8907 mEffectChains.add(chain);
8908 checkSuspendOnAddEffectChain_l(chain);
8909 return NO_ERROR;
8910}
8911
8912size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8913{
8914 audio_session_t session = chain->sessionId();
8915
8916 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8917
8918 for (size_t i = 0; i < mEffectChains.size(); i++) {
8919 if (chain == mEffectChains[i]) {
8920 mEffectChains.removeAt(i);
8921 // detach all active tracks from the chain
8922 // detach all tracks with same session ID from this chain
8923 for (const sp<MmapTrack> &track : mActiveTracks) {
8924 if (session == track->sessionId()) {
8925 chain->decActiveTrackCnt();
8926 chain->decTrackCnt();
8927 }
8928 }
8929 break;
8930 }
8931 }
8932 return mEffectChains.size();
8933}
8934
8935// hasAudioSession_l() must be called with ThreadBase::mLock held
8936uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8937{
8938 uint32_t result = 0;
8939 if (getEffectChain_l(sessionId) != 0) {
8940 result = EFFECT_SESSION;
8941 }
8942
8943 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8944 sp<MmapTrack> track = mActiveTracks[i];
8945 if (sessionId == track->sessionId()) {
8946 result |= TRACK_SESSION;
8947 if (track->isFastTrack()) {
8948 result |= FAST_SESSION;
8949 }
8950 break;
8951 }
8952 }
8953
8954 return result;
8955}
8956
8957void AudioFlinger::MmapThread::threadLoop_standby()
8958{
8959 mHalStream->standby();
8960}
8961
8962void AudioFlinger::MmapThread::threadLoop_exit()
8963{
Phil Burk7dce7282017-09-27 13:51:41 -07008964 // Do not call callback->onTearDown() because it is redundant for thread exit
8965 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008966}
8967
8968status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8969{
8970 return BAD_VALUE;
8971}
8972
8973bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8974{
8975 return false;
8976}
8977
8978status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8979 const effect_descriptor_t *desc, audio_session_t sessionId)
8980{
8981 // No global effect sessions on mmap threads
8982 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8983 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8984 desc->name, mThreadName);
8985 return BAD_VALUE;
8986 }
8987
8988 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8989 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8990 desc->name);
8991 return BAD_VALUE;
8992 }
8993 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008994 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8995 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008996 return BAD_VALUE;
8997 }
8998
8999 // Only allow effects without processing load or latency
9000 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9001 return BAD_VALUE;
9002 }
9003
9004 return NO_ERROR;
9005
9006}
9007
9008void AudioFlinger::MmapThread::checkInvalidTracks_l()
9009{
9010 for (const sp<MmapTrack> &track : mActiveTracks) {
9011 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009012 sp<MmapStreamCallback> callback = mCallback.promote();
9013 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009014 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009015 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009016 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009017 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9018 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9019 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009020 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009021 }
9022 }
9023}
9024
9025void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
9026{
9027 dumpInternals(fd, args);
9028 dumpTracks(fd, args);
9029 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009030 dprintf(fd, " Local log:\n");
9031 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009032}
9033
9034void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
9035{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009036 dumpBase(fd, args);
9037
9038 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9039 mAttr.content_type, mAttr.usage, mAttr.source);
9040 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009041 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009042 dprintf(fd, " No active clients\n");
9043 }
9044}
9045
9046void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
9047{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009048 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009049 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009050 dprintf(fd, " %zu Tracks\n", numtracks);
9051 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009052 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009053 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009054 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009055 for (size_t i = 0; i < numtracks ; ++i) {
9056 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009057 result.append(prefix);
9058 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009059 }
9060 } else {
9061 dprintf(fd, "\n");
9062 }
9063 write(fd, result.string(), result.size());
9064}
9065
9066AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9067 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9068 AudioHwDevice *hwDev, AudioStreamOut *output,
9069 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9070 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
9071 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009072 mStreamVolume(1.0),
9073 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009074 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009075{
9076 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9077 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9078 mMasterVolume = audioFlinger->masterVolume_l();
9079 mMasterMute = audioFlinger->masterMute_l();
9080 if (mAudioHwDev) {
9081 if (mAudioHwDev->canSetMasterVolume()) {
9082 mMasterVolume = 1.0;
9083 }
9084
9085 if (mAudioHwDev->canSetMasterMute()) {
9086 mMasterMute = false;
9087 }
9088 }
9089}
9090
9091void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9092 audio_stream_type_t streamType,
9093 audio_session_t sessionId,
9094 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009095 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009096 audio_port_handle_t portId)
9097{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009098 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009099 mStreamType = streamType;
9100}
9101
9102AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9103{
9104 Mutex::Autolock _l(mLock);
9105 AudioStreamOut *output = mOutput;
9106 mOutput = NULL;
9107 return output;
9108}
9109
9110void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9111{
9112 Mutex::Autolock _l(mLock);
9113 // Don't apply master volume in SW if our HAL can do it for us.
9114 if (mAudioHwDev &&
9115 mAudioHwDev->canSetMasterVolume()) {
9116 mMasterVolume = 1.0;
9117 } else {
9118 mMasterVolume = value;
9119 }
9120}
9121
9122void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9123{
9124 Mutex::Autolock _l(mLock);
9125 // Don't apply master mute in SW if our HAL can do it for us.
9126 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9127 mMasterMute = false;
9128 } else {
9129 mMasterMute = muted;
9130 }
9131}
9132
9133void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9134{
9135 Mutex::Autolock _l(mLock);
9136 if (stream == mStreamType) {
9137 mStreamVolume = value;
9138 broadcast_l();
9139 }
9140}
9141
9142float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9143{
9144 Mutex::Autolock _l(mLock);
9145 if (stream == mStreamType) {
9146 return mStreamVolume;
9147 }
9148 return 0.0f;
9149}
9150
9151void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9152{
9153 Mutex::Autolock _l(mLock);
9154 if (stream == mStreamType) {
9155 mStreamMute= muted;
9156 broadcast_l();
9157 }
9158}
9159
9160void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9161{
9162 Mutex::Autolock _l(mLock);
9163 if (streamType == mStreamType) {
9164 for (const sp<MmapTrack> &track : mActiveTracks) {
9165 track->invalidate();
9166 }
9167 broadcast_l();
9168 }
9169}
9170
9171void AudioFlinger::MmapPlaybackThread::processVolume_l()
9172{
9173 float volume;
9174
9175 if (mMasterMute || mStreamMute) {
9176 volume = 0;
9177 } else {
9178 volume = mMasterVolume * mStreamVolume;
9179 }
9180
9181 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009182
9183 // Convert volumes from float to 8.24
9184 uint32_t vol = (uint32_t)(volume * (1 << 24));
9185
9186 // Delegate volume control to effect in track effect chain if needed
9187 // only one effect chain can be present on DirectOutputThread, so if
9188 // there is one, the track is connected to it
9189 if (!mEffectChains.isEmpty()) {
9190 mEffectChains[0]->setVolume_l(&vol, &vol);
9191 volume = (float)vol / (1 << 24);
9192 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009193 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009194 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9195 mHalVolFloat = volume; // HW volume control worked, so update value.
9196 mNoCallbackWarningCount = 0;
9197 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009198 sp<MmapStreamCallback> callback = mCallback.promote();
9199 if (callback != 0) {
9200 int channelCount;
9201 if (isOutput()) {
9202 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9203 } else {
9204 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9205 }
9206 Vector<float> values;
9207 for (int i = 0; i < channelCount; i++) {
9208 values.add(volume);
9209 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009210 mHalVolFloat = volume; // SW volume control worked, so update value.
9211 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009212 mLock.unlock();
9213 callback->onVolumeChanged(mChannelMask, values);
9214 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009215 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009216 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9217 ALOGW("Could not set MMAP stream volume: no volume callback!");
9218 mNoCallbackWarningCount++;
9219 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009220 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009221 }
9222 }
9223}
9224
Kevin Rocard069c2712018-03-29 19:09:14 -07009225void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9226{
9227 if (mOutput == nullptr || mOutput->stream == nullptr ||
9228 !mActiveTracks.readAndClearHasChanged()) {
9229 return;
9230 }
9231 StreamOutHalInterface::SourceMetadata metadata;
9232 for (const sp<MmapTrack> &track : mActiveTracks) {
9233 // No track is invalid as this is called after prepareTrack_l in the same critical section
9234 metadata.tracks.push_back({
9235 .usage = track->attributes().usage,
9236 .content_type = track->attributes().content_type,
9237 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9238 });
9239 }
9240 mOutput->stream->updateSourceMetadata(metadata);
9241}
9242
Eric Laurent6acd1d42017-01-04 14:23:29 -08009243void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9244{
9245 if (!mMasterMute) {
9246 char value[PROPERTY_VALUE_MAX];
9247 if (property_get("ro.audio.silent", value, "0") > 0) {
9248 char *endptr;
9249 unsigned long ul = strtoul(value, &endptr, 0);
9250 if (*endptr == '\0' && ul != 0) {
9251 ALOGD("Silence is golden");
9252 // The setprop command will not allow a property to be changed after
9253 // the first time it is set, so we don't have to worry about un-muting.
9254 setMasterMute_l(true);
9255 }
9256 }
9257 }
9258}
9259
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009260void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9261{
9262 MmapThread::toAudioPortConfig(config);
9263 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9264 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9265 config->flags.output = mOutput->flags;
9266 }
9267}
9268
Eric Laurent6acd1d42017-01-04 14:23:29 -08009269void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9270{
9271 MmapThread::dumpInternals(fd, args);
9272
Glenn Kastend3bb6452016-12-05 18:14:37 -08009273 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9274 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009275 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9276}
9277
9278AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9279 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9280 AudioHwDevice *hwDev, AudioStreamIn *input,
9281 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9282 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9283 mInput(input)
9284{
9285 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9286 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9287}
9288
Eric Laurent331679c2018-04-16 17:03:16 -07009289status_t AudioFlinger::MmapCaptureThread::exitStandby()
9290{
Phil Burkf054fc32018-12-06 09:45:59 -08009291 {
9292 // mInput might have been cleared by clearInput()
9293 Mutex::Autolock _l(mLock);
9294 if (mInput != nullptr && mInput->stream != nullptr) {
9295 mInput->stream->setGain(1.0f);
9296 }
9297 }
Eric Laurent331679c2018-04-16 17:03:16 -07009298 return MmapThread::exitStandby();
9299}
9300
Eric Laurent6acd1d42017-01-04 14:23:29 -08009301AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9302{
9303 Mutex::Autolock _l(mLock);
9304 AudioStreamIn *input = mInput;
9305 mInput = NULL;
9306 return input;
9307}
Kevin Rocard069c2712018-03-29 19:09:14 -07009308
Eric Laurent331679c2018-04-16 17:03:16 -07009309
9310void AudioFlinger::MmapCaptureThread::processVolume_l()
9311{
9312 bool changed = false;
9313 bool silenced = false;
9314
9315 sp<MmapStreamCallback> callback = mCallback.promote();
9316 if (callback == 0) {
9317 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9318 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9319 mNoCallbackWarningCount++;
9320 }
9321 }
9322
9323 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9324 // track is silenced and unmute otherwise
9325 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9326 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9327 changed = true;
9328 silenced = mActiveTracks[i]->isSilenced_l();
9329 }
9330 }
9331
9332 if (changed) {
9333 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9334 }
9335}
9336
Kevin Rocard069c2712018-03-29 19:09:14 -07009337void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9338{
9339 if (mInput == nullptr || mInput->stream == nullptr ||
9340 !mActiveTracks.readAndClearHasChanged()) {
9341 return;
9342 }
9343 StreamInHalInterface::SinkMetadata metadata;
9344 for (const sp<MmapTrack> &track : mActiveTracks) {
9345 // No track is invalid as this is called after prepareTrack_l in the same critical section
9346 metadata.tracks.push_back({
9347 .source = track->attributes().source,
9348 .gain = 1, // capture tracks do not have volumes
9349 });
9350 }
9351 mInput->stream->updateSinkMetadata(metadata);
9352}
9353
Eric Laurent331679c2018-04-16 17:03:16 -07009354void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9355{
9356 Mutex::Autolock _l(mLock);
9357 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9358 if (mActiveTracks[i]->uid() == uid) {
9359 mActiveTracks[i]->setSilenced_l(silenced);
9360 broadcast_l();
9361 }
9362 }
9363}
9364
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009365void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9366{
9367 MmapThread::toAudioPortConfig(config);
9368 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9369 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9370 config->flags.input = mInput->flags;
9371 }
9372}
9373
Glenn Kasten63238ef2015-03-02 15:50:29 -08009374} // namespace android