blob: a8c4bd1eaa94d7b4cf4f3f697e69e5dc29b61d27 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
27#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080030#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070032#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070033#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080034#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070035#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080037#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080038
39#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070040#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010041#include <audio_utils/Balance.h>
jiabin245cdd92018-12-07 17:55:15 -080042#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080043#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080044#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080045#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070046#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070047#include <system/audio_effects/effect_ns.h>
48#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080050
51// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070052#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053#include <media/nbaio/AudioStreamOutSink.h>
54#include <media/nbaio/MonoPipe.h>
55#include <media/nbaio/MonoPipeReader.h>
56#include <media/nbaio/Pipe.h>
57#include <media/nbaio/PipeReader.h>
58#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080059#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080060
61#include <powermanager/PowerManager.h>
62
Kevin Rocard7588ff42018-01-08 11:11:30 -080063#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070064#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080065
Eric Laurent81784c32012-11-19 14:55:58 -080066#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080067#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070068#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070069#include <mediautils/SchedulingPolicyService.h>
70#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071
Eric Laurent81784c32012-11-19 14:55:58 -080072#ifdef ADD_BATTERY_DATA
73#include <media/IMediaPlayerService.h>
74#include <media/IMediaDeathNotifier.h>
75#endif
76
Eric Laurent81784c32012-11-19 14:55:58 -080077#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070078#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080079#include <cpustats/ThreadCpuUsage.h>
80#endif
81
Glenn Kastenc05b8d72016-03-24 09:48:17 -070082#include "AutoPark.h"
83
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080084#include <pthread.h>
85#include "TypedLogger.h"
86
Eric Laurent81784c32012-11-19 14:55:58 -080087// ----------------------------------------------------------------------------
88
89// Note: the following macro is used for extremely verbose logging message. In
90// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
91// 0; but one side effect of this is to turn all LOGV's as well. Some messages
92// are so verbose that we want to suppress them even when we have ALOG_ASSERT
93// turned on. Do not uncomment the #def below unless you really know what you
94// are doing and want to see all of the extremely verbose messages.
95//#define VERY_VERY_VERBOSE_LOGGING
96#ifdef VERY_VERY_VERBOSE_LOGGING
97#define ALOGVV ALOGV
98#else
99#define ALOGVV(a...) do { } while(0)
100#endif
101
Andy Hung6770c6f2015-04-07 13:43:36 -0700102// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700103#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700104template <typename T>
105static inline T min(const T& a, const T& b)
106{
107 return a < b ? a : b;
108}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700109
Eric Laurent81784c32012-11-19 14:55:58 -0800110namespace android {
111
112// retry counts for buffer fill timeout
113// 50 * ~20msecs = 1 second
114static const int8_t kMaxTrackRetries = 50;
115static const int8_t kMaxTrackStartupRetries = 50;
116// allow less retry attempts on direct output thread.
117// direct outputs can be a scarce resource in audio hardware and should
118// be released as quickly as possible.
119static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700120
Eric Laurent51716182016-02-29 18:00:56 -0800121
Eric Laurent81784c32012-11-19 14:55:58 -0800122
123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
125
126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
128
Eric Laurent10351942014-05-08 18:49:52 -0700129// maximum time to wait in sendConfigEvent_l() for a status to be received
130static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800131
132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
Andy Hung09a50072014-02-27 14:30:47 -0800137// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700138// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800139static const uint32_t kMinNormalSinkBufferSizeMs = 20;
140// maximum normal sink buffer size
141static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800142
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700143// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
144// FIXME This should be based on experimentally observed scheduling jitter
145static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
146
Eric Laurent972a1732013-09-04 09:42:59 -0700147// Offloaded output thread standby delay: allows track transition without going to standby
148static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
149
Eric Laurent51716182016-02-29 18:00:56 -0800150// Direct output thread minimum sleep time in idle or active(underrun) state
151static const nsecs_t kDirectMinSleepTimeUs = 10000;
152
Glenn Kasten1b291842016-07-18 14:55:21 -0700153// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
154// balance between power consumption and latency, and allows threads to be scheduled reliably
155// by the CFS scheduler.
156// FIXME Express other hardcoded references to 20ms with references to this constant and move
157// it appropriately.
158#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800159
Eric Laurent81784c32012-11-19 14:55:58 -0800160// Whether to use fast mixer
161static const enum {
162 FastMixer_Never, // never initialize or use: for debugging only
163 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
164 // normal mixer multiplier is 1
165 FastMixer_Static, // initialize if needed, then use all the time if initialized,
166 // multiplier is calculated based on min & max normal mixer buffer size
167 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
168 // multiplier is calculated based on min & max normal mixer buffer size
169 // FIXME for FastMixer_Dynamic:
170 // Supporting this option will require fixing HALs that can't handle large writes.
171 // For example, one HAL implementation returns an error from a large write,
172 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
173 // We could either fix the HAL implementations, or provide a wrapper that breaks
174 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
175} kUseFastMixer = FastMixer_Static;
176
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700177// Whether to use fast capture
178static const enum {
179 FastCapture_Never, // never initialize or use: for debugging only
180 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
181 FastCapture_Static, // initialize if needed, then use all the time if initialized
182} kUseFastCapture = FastCapture_Static;
183
Eric Laurent81784c32012-11-19 14:55:58 -0800184// Priorities for requestPriority
185static const int kPriorityAudioApp = 2;
186static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700187static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800188
Glenn Kastenea38ee72016-04-18 11:08:01 -0700189// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
190// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
191// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700192
193// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800194static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800195
Glenn Kasten03490092014-05-27 12:30:54 -0700196// The minimum and maximum allowed values
197static const int kFastTrackMultiplierMin = 1;
198static const int kFastTrackMultiplierMax = 2;
199
200// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
201static int sFastTrackMultiplier = kFastTrackMultiplier;
202
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700203// See Thread::readOnlyHeap().
204// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
205// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
206// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700207static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700208
Eric Laurent81784c32012-11-19 14:55:58 -0800209// ----------------------------------------------------------------------------
210
Glenn Kasten03490092014-05-27 12:30:54 -0700211static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
212
213static void sFastTrackMultiplierInit()
214{
215 char value[PROPERTY_VALUE_MAX];
216 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
217 char *endptr;
218 unsigned long ul = strtoul(value, &endptr, 0);
219 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
220 sFastTrackMultiplier = (int) ul;
221 }
222 }
223}
224
225// ----------------------------------------------------------------------------
226
Eric Laurent81784c32012-11-19 14:55:58 -0800227#ifdef ADD_BATTERY_DATA
228// To collect the amplifier usage
229static void addBatteryData(uint32_t params) {
230 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
231 if (service == NULL) {
232 // it already logged
233 return;
234 }
235
236 service->addBatteryData(params);
237}
238#endif
239
Andy Hung3f0c9022016-01-15 17:49:46 -0800240// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
241struct {
242 // call when you acquire a partial wakelock
243 void acquire(const sp<IBinder> &wakeLockToken) {
244 pthread_mutex_lock(&mLock);
245 if (wakeLockToken.get() == nullptr) {
246 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
247 } else {
248 if (mCount == 0) {
249 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
250 }
251 ++mCount;
252 }
253 pthread_mutex_unlock(&mLock);
254 }
255
256 // call when you release a partial wakelock.
257 void release(const sp<IBinder> &wakeLockToken) {
258 if (wakeLockToken.get() == nullptr) {
259 return;
260 }
261 pthread_mutex_lock(&mLock);
262 if (--mCount < 0) {
263 ALOGE("negative wakelock count");
264 mCount = 0;
265 }
266 pthread_mutex_unlock(&mLock);
267 }
268
269 // retrieves the boottime timebase offset from monotonic.
270 int64_t getBoottimeOffset() {
271 pthread_mutex_lock(&mLock);
272 int64_t boottimeOffset = mBoottimeOffset;
273 pthread_mutex_unlock(&mLock);
274 return boottimeOffset;
275 }
276
277 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
278 // and the selected timebase.
279 // Currently only TIMEBASE_BOOTTIME is allowed.
280 //
281 // This only needs to be called upon acquiring the first partial wakelock
282 // after all other partial wakelocks are released.
283 //
284 // We do an empirical measurement of the offset rather than parsing
285 // /proc/timer_list since the latter is not a formal kernel ABI.
286 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
287 int clockbase;
288 switch (timebase) {
289 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
290 clockbase = SYSTEM_TIME_BOOTTIME;
291 break;
292 default:
293 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
294 break;
295 }
296 // try three times to get the clock offset, choose the one
297 // with the minimum gap in measurements.
298 const int tries = 3;
299 nsecs_t bestGap, measured;
300 for (int i = 0; i < tries; ++i) {
301 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
302 const nsecs_t tbase = systemTime(clockbase);
303 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
304 const nsecs_t gap = tmono2 - tmono;
305 if (i == 0 || gap < bestGap) {
306 bestGap = gap;
307 measured = tbase - ((tmono + tmono2) >> 1);
308 }
309 }
310
311 // to avoid micro-adjusting, we don't change the timebase
312 // unless it is significantly different.
313 //
314 // Assumption: It probably takes more than toleranceNs to
315 // suspend and resume the device.
316 static int64_t toleranceNs = 10000; // 10 us
317 if (llabs(*offset - measured) > toleranceNs) {
318 ALOGV("Adjusting timebase offset old: %lld new: %lld",
319 (long long)*offset, (long long)measured);
320 *offset = measured;
321 }
322 }
323
324 pthread_mutex_t mLock;
325 int32_t mCount;
326 int64_t mBoottimeOffset;
327} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800328
329// ----------------------------------------------------------------------------
330// CPU Stats
331// ----------------------------------------------------------------------------
332
333class CpuStats {
334public:
335 CpuStats();
336 void sample(const String8 &title);
337#ifdef DEBUG_CPU_USAGE
338private:
339 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700340 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800341
Andy Hung16698b82018-08-01 10:48:38 -0700342 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800343
344 int mCpuNum; // thread's current CPU number
345 int mCpukHz; // frequency of thread's current CPU in kHz
346#endif
347};
348
349CpuStats::CpuStats()
350#ifdef DEBUG_CPU_USAGE
351 : mCpuNum(-1), mCpukHz(-1)
352#endif
353{
354}
355
Glenn Kasten0f11b512014-01-31 16:18:54 -0800356void CpuStats::sample(const String8 &title
357#ifndef DEBUG_CPU_USAGE
358 __unused
359#endif
360 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800361#ifdef DEBUG_CPU_USAGE
362 // get current thread's delta CPU time in wall clock ns
363 double wcNs;
364 bool valid = mCpuUsage.sampleAndEnable(wcNs);
365
366 // record sample for wall clock statistics
367 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700368 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800369 }
370
371 // get the current CPU number
372 int cpuNum = sched_getcpu();
373
374 // get the current CPU frequency in kHz
375 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
376
377 // check if either CPU number or frequency changed
378 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
379 mCpuNum = cpuNum;
380 mCpukHz = cpukHz;
381 // ignore sample for purposes of cycles
382 valid = false;
383 }
384
385 // if no change in CPU number or frequency, then record sample for cycle statistics
386 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700387 const double cycles = wcNs * cpukHz * 0.000001;
388 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800389 }
390
Eric Tan5b13ff82018-07-27 11:20:17 -0700391 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800392 // mCpuUsage.elapsed() is expensive, so don't call it every loop
393 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700394 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800395 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700396 const double perLoop = elapsed / (double) n;
397 const double perLoop100 = perLoop * 0.01;
398 const double perLoop1k = perLoop * 0.001;
399 const double mean = mWcStats.getMean();
400 const double stddev = mWcStats.getStdDev();
401 const double minimum = mWcStats.getMin();
402 const double maximum = mWcStats.getMax();
403 const double meanCycles = mHzStats.getMean();
404 const double stddevCycles = mHzStats.getStdDev();
405 const double minCycles = mHzStats.getMin();
406 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800407 mCpuUsage.resetElapsed();
408 mWcStats.reset();
409 mHzStats.reset();
410 ALOGD("CPU usage for %s over past %.1f secs\n"
411 " (%u mixer loops at %.1f mean ms per loop):\n"
412 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
413 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
414 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
415 title.string(),
416 elapsed * .000000001, n, perLoop * .000001,
417 mean * .001,
418 stddev * .001,
419 minimum * .001,
420 maximum * .001,
421 mean / perLoop100,
422 stddev / perLoop100,
423 minimum / perLoop100,
424 maximum / perLoop100,
425 meanCycles / perLoop1k,
426 stddevCycles / perLoop1k,
427 minCycles / perLoop1k,
428 maxCycles / perLoop1k);
429
430 }
431 }
432#endif
433};
434
435// ----------------------------------------------------------------------------
436// ThreadBase
437// ----------------------------------------------------------------------------
438
Glenn Kasten97b7b752014-09-28 13:04:24 -0700439// static
440const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
441{
442 switch (type) {
443 case MIXER:
444 return "MIXER";
445 case DIRECT:
446 return "DIRECT";
447 case DUPLICATING:
448 return "DUPLICATING";
449 case RECORD:
450 return "RECORD";
451 case OFFLOAD:
452 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800453 case MMAP:
454 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700455 default:
456 return "unknown";
457 }
458}
459
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700460std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800461{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700462 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800463 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800467 }
468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800475 return result;
476}
477
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700478std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700479{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700480 std::string result;
481 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700482 return result;
483}
484
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800485const char *sourceToString(audio_source_t source)
486{
487 switch (source) {
488 case AUDIO_SOURCE_DEFAULT: return "default";
489 case AUDIO_SOURCE_MIC: return "mic";
490 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
491 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
492 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
493 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
494 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
495 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
496 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800497 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Eric Laurentae4b6ec2019-01-15 18:34:38 -0800498 case AUDIO_SOURCE_VOICE_PERFORMANCE: return "voice performance";
499 case AUDIO_SOURCE_ECHO_REFERENCE: return "echo reference";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800500 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
501 case AUDIO_SOURCE_HOTWORD: return "hotword";
502 default: return "unknown";
503 }
504}
505
Eric Laurent81784c32012-11-19 14:55:58 -0800506AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700507 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800508 : Thread(false /*canCallJava*/),
509 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700510 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700511 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800512 // are set by PlaybackThread::readOutputParameters_l() or
513 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700514 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800515 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700516 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
517 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800518 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700519 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800520 mSystemReady(systemReady),
521 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800522{
Eric Laurent296fb132015-05-01 11:38:42 -0700523 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800524}
525
526AudioFlinger::ThreadBase::~ThreadBase()
527{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700528 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700529 mConfigEvents.clear();
530
Eric Laurent81784c32012-11-19 14:55:58 -0800531 // do not lock the mutex in destructor
532 releaseWakeLock_l();
533 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800534 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800535 binder->unlinkToDeath(mDeathRecipient);
536 }
537}
538
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700539status_t AudioFlinger::ThreadBase::readyToRun()
540{
541 status_t status = initCheck();
542 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800543 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700544 } else {
545 ALOGE("No working audio driver found.");
546 }
547 return status;
548}
549
Eric Laurent81784c32012-11-19 14:55:58 -0800550void AudioFlinger::ThreadBase::exit()
551{
552 ALOGV("ThreadBase::exit");
553 // do any cleanup required for exit to succeed
554 preExit();
555 {
556 // This lock prevents the following race in thread (uniprocessor for illustration):
557 // if (!exitPending()) {
558 // // context switch from here to exit()
559 // // exit() calls requestExit(), what exitPending() observes
560 // // exit() calls signal(), which is dropped since no waiters
561 // // context switch back from exit() to here
562 // mWaitWorkCV.wait(...);
563 // // now thread is hung
564 // }
565 AutoMutex lock(mLock);
566 requestExit();
567 mWaitWorkCV.broadcast();
568 }
569 // When Thread::requestExitAndWait is made virtual and this method is renamed to
570 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
571 requestExitAndWait();
572}
573
574status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
575{
Eric Laurent81784c32012-11-19 14:55:58 -0800576 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
577 Mutex::Autolock _l(mLock);
578
Eric Laurent10351942014-05-08 18:49:52 -0700579 return sendSetParameterConfigEvent_l(keyValuePairs);
580}
581
582// sendConfigEvent_l() must be called with ThreadBase::mLock held
583// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
584status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
585{
586 status_t status = NO_ERROR;
587
Eric Laurent72e3f392015-05-20 14:43:50 -0700588 if (event->mRequiresSystemReady && !mSystemReady) {
589 event->mWaitStatus = false;
590 mPendingConfigEvents.add(event);
591 return status;
592 }
Eric Laurent10351942014-05-08 18:49:52 -0700593 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700594 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800595 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700596 mLock.unlock();
597 {
598 Mutex::Autolock _l(event->mLock);
599 while (event->mWaitStatus) {
600 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
601 event->mStatus = TIMED_OUT;
602 event->mWaitStatus = false;
603 }
604 }
605 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800606 }
Eric Laurent10351942014-05-08 18:49:52 -0700607 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800608 return status;
609}
610
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800612{
613 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700614 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800615}
616
617// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700618void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800619{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700620 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700621 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800622}
623
Mikhail Naganov83f04272017-02-07 10:45:09 -0800624void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700625{
626 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800627 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700628}
629
Eric Laurent81784c32012-11-19 14:55:58 -0800630// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800631void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
632 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800633{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800634 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700635 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800636}
637
Eric Laurent10351942014-05-08 18:49:52 -0700638// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
639status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800640{
Andy Hung2ddee192015-12-18 17:34:44 -0800641 sp<ConfigEvent> configEvent;
642 AudioParameter param(keyValuePair);
643 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700644 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800645 setMasterMono_l(value != 0);
646 if (param.size() == 1) {
647 return NO_ERROR; // should be a solo parameter - we don't pass down
648 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700649 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800650 configEvent = new SetParameterConfigEvent(param.toString());
651 } else {
652 configEvent = new SetParameterConfigEvent(keyValuePair);
653 }
Eric Laurent10351942014-05-08 18:49:52 -0700654 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700655}
656
Eric Laurent1c333e22014-05-20 10:48:17 -0700657status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
658 const struct audio_patch *patch,
659 audio_patch_handle_t *handle)
660{
661 Mutex::Autolock _l(mLock);
662 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
663 status_t status = sendConfigEvent_l(configEvent);
664 if (status == NO_ERROR) {
665 CreateAudioPatchConfigEventData *data =
666 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
667 *handle = data->mHandle;
668 }
669 return status;
670}
671
672status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
673 const audio_patch_handle_t handle)
674{
675 Mutex::Autolock _l(mLock);
676 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
677 return sendConfigEvent_l(configEvent);
678}
679
680
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700681// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700682void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700683{
Eric Laurent10351942014-05-08 18:49:52 -0700684 bool configChanged = false;
685
Eric Laurent81784c32012-11-19 14:55:58 -0800686 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700687 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700688 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800689 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700690 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700691 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700692 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
693 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800694 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700695 true /*asynchronous*/);
696 if (err != 0) {
697 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700698 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700699 }
700 } break;
701 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700702 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700703 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700704 } break;
705 case CFG_EVENT_SET_PARAMETER: {
706 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
707 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
708 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700709 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
710 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700711 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700712 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700713 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700714 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700715 CreateAudioPatchConfigEventData *data =
716 (CreateAudioPatchConfigEventData *)event->mData.get();
717 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700718 const audio_devices_t newDevice = getDevice();
719 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
720 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
721 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700722 } break;
723 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700724 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700725 ReleaseAudioPatchConfigEventData *data =
726 (ReleaseAudioPatchConfigEventData *)event->mData.get();
727 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700728 const audio_devices_t newDevice = getDevice();
729 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
730 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
731 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700732 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700733 default:
Eric Laurent10351942014-05-08 18:49:52 -0700734 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700735 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
Eric Laurent10351942014-05-08 18:49:52 -0700737 {
738 Mutex::Autolock _l(event->mLock);
739 if (event->mWaitStatus) {
740 event->mWaitStatus = false;
741 event->mCond.signal();
742 }
743 }
744 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
745 }
746
747 if (configChanged) {
748 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800749 }
Eric Laurent81784c32012-11-19 14:55:58 -0800750}
751
Marco Nelissenb2208842014-02-07 14:00:50 -0800752String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
753 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700754 const audio_channel_representation_t representation =
755 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700756
757 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800758 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700759 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
760 if (output) {
761 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
762 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
763 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
764 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
765 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
766 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
767 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
768 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
769 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
770 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
771 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
772 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
773 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
774 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
775 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
776 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
777 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
778 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700779 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
780 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800781 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
782 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700783 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
784 } else {
785 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
786 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
787 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
788 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
789 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
790 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
791 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
792 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
793 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
794 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
795 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
796 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700797 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
798 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
799 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
800 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
801 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
802 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700803 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
804 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
805 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
806 }
807 const int len = s.length();
808 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700809 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700810 s.unlockBuffer(len - 2); // remove trailing ", "
811 }
812 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800813 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700814 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
815 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
816 return s;
817 default:
818 s.appendFormat("unknown mask, representation:%d bits:%#x",
819 representation, audio_channel_mask_get_bits(mask));
820 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800821 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800822}
823
Glenn Kasten0f11b512014-01-31 16:18:54 -0800824void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800825{
826 const size_t SIZE = 256;
827 char buffer[SIZE];
828 String8 result;
829
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800830 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
831 this, mThreadName, getTid(), type(), threadTypeToString(type()));
832
Eric Laurent81784c32012-11-19 14:55:58 -0800833 bool locked = AudioFlinger::dumpTryLock(mLock);
834 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800835 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800836 }
837
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700839 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700840 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700841 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700842 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700843 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700844 dprintf(fd, " Channel count: %u\n", mChannelCount);
845 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800846 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700847 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700848 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700849 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800850 size_t numConfig = mConfigEvents.size();
851 if (numConfig) {
852 for (size_t i = 0; i < numConfig; i++) {
853 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700854 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800855 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700856 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800857 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700858 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Andy Hung293558a2017-03-21 12:19:20 -0700860 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700861 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
862 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800863 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800864
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700865 // Dump timestamp statistics for the Thread types that support it.
866 if (mType == RECORD
867 || mType == MIXER
868 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700869 || mType == DIRECT
870 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700871 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700872 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700873 }
874
Eric Laurent81784c32012-11-19 14:55:58 -0800875 if (locked) {
876 mLock.unlock();
877 }
878}
879
880void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
881{
882 const size_t SIZE = 256;
883 char buffer[SIZE];
884 String8 result;
885
Marco Nelissenb2208842014-02-07 14:00:50 -0800886 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000887 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800888 write(fd, buffer, strlen(buffer));
889
Marco Nelissenb2208842014-02-07 14:00:50 -0800890 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800891 sp<EffectChain> chain = mEffectChains[i];
892 if (chain != 0) {
893 chain->dump(fd, args);
894 }
895 }
896}
897
Andy Hungdae27702016-10-31 14:01:16 -0700898void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800899{
900 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700901 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800902}
903
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100904String16 AudioFlinger::ThreadBase::getWakeLockTag()
905{
906 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800907 case MIXER:
908 return String16("AudioMix");
909 case DIRECT:
910 return String16("AudioDirectOut");
911 case DUPLICATING:
912 return String16("AudioDup");
913 case RECORD:
914 return String16("AudioIn");
915 case OFFLOAD:
916 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800917 case MMAP:
918 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800919 default:
920 ALOG_ASSERT(false);
921 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100922 }
923}
924
Andy Hungdae27702016-10-31 14:01:16 -0700925void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800926{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800927 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (mPowerManager != 0) {
929 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700930 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
931 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700932 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100933 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700934 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700935 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800936 if (status == NO_ERROR) {
937 mWakeLockToken = binder;
938 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800939 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800940 }
Wei Jia3f273d12015-11-24 09:06:49 -0800941
Andy Hung3f0c9022016-01-15 17:49:46 -0800942 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800943 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
944 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800945}
946
947void AudioFlinger::ThreadBase::releaseWakeLock()
948{
949 Mutex::Autolock _l(mLock);
950 releaseWakeLock_l();
951}
952
953void AudioFlinger::ThreadBase::releaseWakeLock_l()
954{
Andy Hung3f0c9022016-01-15 17:49:46 -0800955 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800956 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800957 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800958 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700959 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
960 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800961 }
962 mWakeLockToken.clear();
963 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800964}
965
966void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700967 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800968 // use checkService() to avoid blocking if power service is not up yet
969 sp<IBinder> binder =
970 defaultServiceManager()->checkService(String16("power"));
971 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800972 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800973 } else {
974 mPowerManager = interface_cast<IPowerManager>(binder);
975 binder->linkToDeath(mDeathRecipient);
976 }
977 }
978}
979
Andy Hungd01b0f12016-11-07 16:10:30 -0800980void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800981 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700982
983#if !LOG_NDEBUG
984 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800985 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700986 s << uid << " ";
987 }
988 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
989#endif
990
Andy Hung438e7572015-12-14 15:51:17 -0800991 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
992 if (mSystemReady) {
993 ALOGE("no wake lock to update, but system ready!");
994 } else {
995 ALOGW("no wake lock to update, system not ready yet");
996 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800997 return;
998 }
999 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001000 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
1001 status_t status = mPowerManager->updateWakeLockUids(
1002 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
1003 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001004 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001005 }
1006}
1007
Eric Laurent81784c32012-11-19 14:55:58 -08001008void AudioFlinger::ThreadBase::clearPowerManager()
1009{
1010 Mutex::Autolock _l(mLock);
1011 releaseWakeLock_l();
1012 mPowerManager.clear();
1013}
1014
Glenn Kasten0f11b512014-01-31 16:18:54 -08001015void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001016{
1017 sp<ThreadBase> thread = mThread.promote();
1018 if (thread != 0) {
1019 thread->clearPowerManager();
1020 }
1021 ALOGW("power manager service died !!!");
1022}
1023
Eric Laurent81784c32012-11-19 14:55:58 -08001024void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001025 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001026{
1027 sp<EffectChain> chain = getEffectChain_l(sessionId);
1028 if (chain != 0) {
1029 if (type != NULL) {
1030 chain->setEffectSuspended_l(type, suspend);
1031 } else {
1032 chain->setEffectSuspendedAll_l(suspend);
1033 }
1034 }
1035
1036 updateSuspendedSessions_l(type, suspend, sessionId);
1037}
1038
1039void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1040{
1041 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1042 if (index < 0) {
1043 return;
1044 }
1045
1046 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1047 mSuspendedSessions.valueAt(index);
1048
1049 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001050 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001051 for (int j = 0; j < desc->mRefCount; j++) {
1052 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1053 chain->setEffectSuspendedAll_l(true);
1054 } else {
1055 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1056 desc->mType.timeLow);
1057 chain->setEffectSuspended_l(&desc->mType, true);
1058 }
1059 }
1060 }
1061}
1062
1063void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1064 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001065 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001066{
1067 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1068
1069 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1070
1071 if (suspend) {
1072 if (index >= 0) {
1073 sessionEffects = mSuspendedSessions.valueAt(index);
1074 } else {
1075 mSuspendedSessions.add(sessionId, sessionEffects);
1076 }
1077 } else {
1078 if (index < 0) {
1079 return;
1080 }
1081 sessionEffects = mSuspendedSessions.valueAt(index);
1082 }
1083
1084
1085 int key = EffectChain::kKeyForSuspendAll;
1086 if (type != NULL) {
1087 key = type->timeLow;
1088 }
1089 index = sessionEffects.indexOfKey(key);
1090
1091 sp<SuspendedSessionDesc> desc;
1092 if (suspend) {
1093 if (index >= 0) {
1094 desc = sessionEffects.valueAt(index);
1095 } else {
1096 desc = new SuspendedSessionDesc();
1097 if (type != NULL) {
1098 desc->mType = *type;
1099 }
1100 sessionEffects.add(key, desc);
1101 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1102 }
1103 desc->mRefCount++;
1104 } else {
1105 if (index < 0) {
1106 return;
1107 }
1108 desc = sessionEffects.valueAt(index);
1109 if (--desc->mRefCount == 0) {
1110 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1111 sessionEffects.removeItemsAt(index);
1112 if (sessionEffects.isEmpty()) {
1113 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1114 sessionId);
1115 mSuspendedSessions.removeItem(sessionId);
1116 }
1117 }
1118 }
1119 if (!sessionEffects.isEmpty()) {
1120 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1121 }
1122}
1123
1124void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1125 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001126 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001127{
1128 Mutex::Autolock _l(mLock);
1129 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1130}
1131
1132void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1133 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001134 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001135{
1136 if (mType != RECORD) {
1137 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1138 // another session. This gives the priority to well behaved effect control panels
1139 // and applications not using global effects.
1140 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1141 // global effects
1142 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1143 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1144 }
1145 }
1146
1147 sp<EffectChain> chain = getEffectChain_l(sessionId);
1148 if (chain != 0) {
1149 chain->checkSuspendOnEffectEnabled(effect, enabled);
1150 }
1151}
1152
Eric Laurent4c415062016-06-17 16:14:16 -07001153// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1154status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1155 const effect_descriptor_t *desc, audio_session_t sessionId)
1156{
1157 // No global effect sessions on record threads
1158 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1159 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1160 desc->name, mThreadName);
1161 return BAD_VALUE;
1162 }
1163 // only pre processing effects on record thread
1164 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1165 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1166 desc->name, mThreadName);
1167 return BAD_VALUE;
1168 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001169
1170 // always allow effects without processing load or latency
1171 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1172 return NO_ERROR;
1173 }
1174
Eric Laurent4c415062016-06-17 16:14:16 -07001175 audio_input_flags_t flags = mInput->flags;
1176 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1177 if (flags & AUDIO_INPUT_FLAG_RAW) {
1178 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1179 desc->name, mThreadName);
1180 return BAD_VALUE;
1181 }
1182 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1183 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1184 desc->name, mThreadName);
1185 return BAD_VALUE;
1186 }
1187 }
1188 return NO_ERROR;
1189}
1190
1191// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1192status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1193 const effect_descriptor_t *desc, audio_session_t sessionId)
1194{
1195 // no preprocessing on playback threads
1196 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1197 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1198 " thread %s", desc->name, mThreadName);
1199 return BAD_VALUE;
1200 }
1201
Eric Laurent3e4de772017-07-16 16:55:08 -07001202 // always allow effects without processing load or latency
1203 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1204 return NO_ERROR;
1205 }
1206
Eric Laurent4c415062016-06-17 16:14:16 -07001207 switch (mType) {
1208 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001209#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001210 // Reject any effect on mixer multichannel sinks.
1211 // TODO: fix both format and multichannel issues with effects.
1212 if (mChannelCount != FCC_2) {
1213 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1214 " thread %s", desc->name, mChannelCount, mThreadName);
1215 return BAD_VALUE;
1216 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001217#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001218 audio_output_flags_t flags = mOutput->flags;
1219 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1220 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1221 // global effects are applied only to non fast tracks if they are SW
1222 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1223 break;
1224 }
1225 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1226 // only post processing on output stage session
1227 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1228 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1229 " on output stage session", desc->name);
1230 return BAD_VALUE;
1231 }
1232 } else {
1233 // no restriction on effects applied on non fast tracks
1234 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1235 break;
1236 }
1237 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001238
Eric Laurent4c415062016-06-17 16:14:16 -07001239 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1240 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1241 desc->name);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1245 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1246 " in fast mode", desc->name);
1247 return BAD_VALUE;
1248 }
1249 }
1250 } break;
1251 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001252 // nothing actionable on offload threads, if the effect:
1253 // - is offloadable: the effect can be created
1254 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1255 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001256 break;
1257 case DIRECT:
1258 // Reject any effect on Direct output threads for now, since the format of
1259 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1260 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1261 desc->name, mThreadName);
1262 return BAD_VALUE;
1263 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001264#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001265 // Reject any effect on mixer multichannel sinks.
1266 // TODO: fix both format and multichannel issues with effects.
1267 if (mChannelCount != FCC_2) {
1268 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1269 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1270 return BAD_VALUE;
1271 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001272#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001273 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1274 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1275 " thread %s", desc->name, mThreadName);
1276 return BAD_VALUE;
1277 }
1278 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1279 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1280 " DUPLICATING thread %s", desc->name, mThreadName);
1281 return BAD_VALUE;
1282 }
1283 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1284 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1285 " DUPLICATING thread %s", desc->name, mThreadName);
1286 return BAD_VALUE;
1287 }
1288 break;
1289 default:
1290 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1291 }
1292
1293 return NO_ERROR;
1294}
1295
Eric Laurent81784c32012-11-19 14:55:58 -08001296// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1297sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1298 const sp<AudioFlinger::Client>& client,
1299 const sp<IEffectClient>& effectClient,
1300 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001301 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001302 effect_descriptor_t *desc,
1303 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001304 status_t *status,
1305 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001306{
1307 sp<EffectModule> effect;
1308 sp<EffectHandle> handle;
1309 status_t lStatus;
1310 sp<EffectChain> chain;
1311 bool chainCreated = false;
1312 bool effectCreated = false;
1313 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001314 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001315
1316 lStatus = initCheck();
1317 if (lStatus != NO_ERROR) {
1318 ALOGW("createEffect_l() Audio driver not initialized.");
1319 goto Exit;
1320 }
1321
Eric Laurent81784c32012-11-19 14:55:58 -08001322 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1323
1324 { // scope for mLock
1325 Mutex::Autolock _l(mLock);
1326
Eric Laurent4c415062016-06-17 16:14:16 -07001327 lStatus = checkEffectCompatibility_l(desc, sessionId);
1328 if (lStatus != NO_ERROR) {
1329 goto Exit;
1330 }
1331
Eric Laurent81784c32012-11-19 14:55:58 -08001332 // check for existing effect chain with the requested audio session
1333 chain = getEffectChain_l(sessionId);
1334 if (chain == 0) {
1335 // create a new chain for this session
1336 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1337 chain = new EffectChain(this, sessionId);
1338 addEffectChain_l(chain);
1339 chain->setStrategy(getStrategyForSession_l(sessionId));
1340 chainCreated = true;
1341 } else {
1342 effect = chain->getEffectFromDesc_l(desc);
1343 }
1344
1345 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1346
1347 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001348 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001349 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001350 lStatus = AudioSystem::registerEffect(
1351 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001352 if (lStatus != NO_ERROR) {
1353 goto Exit;
1354 }
1355 effectRegistered = true;
1356 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001357 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001358 if (lStatus != NO_ERROR) {
1359 goto Exit;
1360 }
1361 effectCreated = true;
1362
1363 effect->setDevice(mOutDevice);
1364 effect->setDevice(mInDevice);
1365 effect->setMode(mAudioFlinger->getMode());
1366 effect->setAudioSource(mAudioSource);
1367 }
1368 // create effect handle and connect it to effect module
1369 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001370 lStatus = handle->initCheck();
1371 if (lStatus == OK) {
1372 lStatus = effect->addHandle(handle.get());
1373 }
Eric Laurent81784c32012-11-19 14:55:58 -08001374 if (enabled != NULL) {
1375 *enabled = (int)effect->isEnabled();
1376 }
1377 }
1378
1379Exit:
1380 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1381 Mutex::Autolock _l(mLock);
1382 if (effectCreated) {
1383 chain->removeEffect_l(effect);
1384 }
1385 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001386 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001387 }
1388 if (chainCreated) {
1389 removeEffectChain_l(chain);
1390 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001391 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001392 }
1393
Glenn Kasten9156ef32013-08-06 15:39:08 -07001394 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001395 return handle;
1396}
1397
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001398void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1399 bool unpinIfLast)
1400{
1401 bool remove = false;
1402 sp<EffectModule> effect;
1403 {
1404 Mutex::Autolock _l(mLock);
1405
1406 effect = handle->effect().promote();
1407 if (effect == 0) {
1408 return;
1409 }
1410 // restore suspended effects if the disconnected handle was enabled and the last one.
1411 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1412 if (remove) {
1413 removeEffect_l(effect, true);
1414 }
1415 }
1416 if (remove) {
1417 mAudioFlinger->updateOrphanEffectChains(effect);
1418 AudioSystem::unregisterEffect(effect->id());
1419 if (handle->enabled()) {
1420 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1421 }
1422 }
1423}
1424
Glenn Kastend848eb42016-03-08 13:42:11 -08001425sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1426 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001427{
1428 Mutex::Autolock _l(mLock);
1429 return getEffect_l(sessionId, effectId);
1430}
1431
Glenn Kastend848eb42016-03-08 13:42:11 -08001432sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1433 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001434{
1435 sp<EffectChain> chain = getEffectChain_l(sessionId);
1436 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1437}
1438
1439// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1440// PlaybackThread::mLock held
1441status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1442{
1443 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001444 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001445 sp<EffectChain> chain = getEffectChain_l(sessionId);
1446 bool chainCreated = false;
1447
Eric Laurent5baf2af2013-09-12 17:37:00 -07001448 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001449 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001450 this, effect->desc().name, effect->desc().flags);
1451
Eric Laurent81784c32012-11-19 14:55:58 -08001452 if (chain == 0) {
1453 // create a new chain for this session
1454 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1455 chain = new EffectChain(this, sessionId);
1456 addEffectChain_l(chain);
1457 chain->setStrategy(getStrategyForSession_l(sessionId));
1458 chainCreated = true;
1459 }
1460 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1461
1462 if (chain->getEffectFromId_l(effect->id()) != 0) {
1463 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1464 this, effect->desc().name, chain.get());
1465 return BAD_VALUE;
1466 }
1467
Eric Laurent5baf2af2013-09-12 17:37:00 -07001468 effect->setOffloaded(mType == OFFLOAD, mId);
1469
Eric Laurent81784c32012-11-19 14:55:58 -08001470 status_t status = chain->addEffect_l(effect);
1471 if (status != NO_ERROR) {
1472 if (chainCreated) {
1473 removeEffectChain_l(chain);
1474 }
1475 return status;
1476 }
1477
1478 effect->setDevice(mOutDevice);
1479 effect->setDevice(mInDevice);
1480 effect->setMode(mAudioFlinger->getMode());
1481 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001482
Eric Laurent81784c32012-11-19 14:55:58 -08001483 return NO_ERROR;
1484}
1485
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001486void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001487
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001488 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001489 effect_descriptor_t desc = effect->desc();
1490 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1491 detachAuxEffect_l(effect->id());
1492 }
1493
1494 sp<EffectChain> chain = effect->chain().promote();
1495 if (chain != 0) {
1496 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001497 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001498 removeEffectChain_l(chain);
1499 }
1500 } else {
1501 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1502 }
1503}
1504
1505void AudioFlinger::ThreadBase::lockEffectChains_l(
1506 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1507{
1508 effectChains = mEffectChains;
1509 for (size_t i = 0; i < mEffectChains.size(); i++) {
1510 mEffectChains[i]->lock();
1511 }
1512}
1513
1514void AudioFlinger::ThreadBase::unlockEffectChains(
1515 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1516{
1517 for (size_t i = 0; i < effectChains.size(); i++) {
1518 effectChains[i]->unlock();
1519 }
1520}
1521
Glenn Kastend848eb42016-03-08 13:42:11 -08001522sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001523{
1524 Mutex::Autolock _l(mLock);
1525 return getEffectChain_l(sessionId);
1526}
1527
Glenn Kastend848eb42016-03-08 13:42:11 -08001528sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1529 const
Eric Laurent81784c32012-11-19 14:55:58 -08001530{
1531 size_t size = mEffectChains.size();
1532 for (size_t i = 0; i < size; i++) {
1533 if (mEffectChains[i]->sessionId() == sessionId) {
1534 return mEffectChains[i];
1535 }
1536 }
1537 return 0;
1538}
1539
1540void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1541{
1542 Mutex::Autolock _l(mLock);
1543 size_t size = mEffectChains.size();
1544 for (size_t i = 0; i < size; i++) {
1545 mEffectChains[i]->setMode_l(mode);
1546 }
1547}
1548
Mikhail Naganovdc769682018-05-04 15:34:08 -07001549void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001550{
1551 config->type = AUDIO_PORT_TYPE_MIX;
1552 config->ext.mix.handle = mId;
1553 config->sample_rate = mSampleRate;
1554 config->format = mFormat;
1555 config->channel_mask = mChannelMask;
1556 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1557 AUDIO_PORT_CONFIG_FORMAT;
1558}
1559
Eric Laurent72e3f392015-05-20 14:43:50 -07001560void AudioFlinger::ThreadBase::systemReady()
1561{
1562 Mutex::Autolock _l(mLock);
1563 if (mSystemReady) {
1564 return;
1565 }
1566 mSystemReady = true;
1567
1568 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1569 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1570 }
1571 mPendingConfigEvents.clear();
1572}
1573
Andy Hungdae27702016-10-31 14:01:16 -07001574template <typename T>
1575ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1576 ssize_t index = mActiveTracks.indexOf(track);
1577 if (index >= 0) {
1578 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1579 return index;
1580 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001581 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001582 mActiveTracksGeneration++;
1583 mLatestActiveTrack = track;
1584 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001585 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001586 return mActiveTracks.add(track);
1587}
1588
1589template <typename T>
1590ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1591 ssize_t index = mActiveTracks.remove(track);
1592 if (index < 0) {
1593 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1594 return index;
1595 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001596 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001597 mActiveTracksGeneration++;
1598 --mBatteryCounter[track->uid()].second;
1599 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001600 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001601#ifdef TEE_SINK
1602 track->dumpTee(-1 /* fd */, "_REMOVE");
1603#endif
Andy Hungdae27702016-10-31 14:01:16 -07001604 return index;
1605}
1606
1607template <typename T>
1608void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1609 for (const sp<T> &track : mActiveTracks) {
1610 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001611 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001612 }
1613 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001614 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001615 mActiveTracks.clear();
1616 mLatestActiveTrack.clear();
1617 mBatteryCounter.clear();
1618}
1619
1620template <typename T>
1621void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1622 sp<ThreadBase> thread, bool force) {
1623 // Updates ActiveTracks client uids to the thread wakelock.
1624 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1625 thread->updateWakeLockUids_l(getWakeLockUids());
1626 mLastActiveTracksGeneration = mActiveTracksGeneration;
1627 }
1628
1629 // Updates BatteryNotifier uids
1630 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1631 const uid_t uid = it->first;
1632 ssize_t &previous = it->second.first;
1633 ssize_t &current = it->second.second;
1634 if (current > 0) {
1635 if (previous == 0) {
1636 BatteryNotifier::getInstance().noteStartAudio(uid);
1637 }
1638 previous = current;
1639 ++it;
1640 } else if (current == 0) {
1641 if (previous > 0) {
1642 BatteryNotifier::getInstance().noteStopAudio(uid);
1643 }
1644 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1645 } else /* (current < 0) */ {
1646 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1647 }
1648 }
1649}
Eric Laurent83b88082014-06-20 18:31:16 -07001650
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001651template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001652bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1653 const bool hasChanged = mHasChanged;
1654 mHasChanged = false;
1655 return hasChanged;
1656}
1657
1658template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001659void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1660 const char *funcName, const sp<T> &track) const {
1661 if (mLocalLog != nullptr) {
1662 String8 result;
1663 track->appendDump(result, false /* active */);
1664 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1665 }
1666}
1667
Eric Laurent6acd1d42017-01-04 14:23:29 -08001668void AudioFlinger::ThreadBase::broadcast_l()
1669{
1670 // Thread could be blocked waiting for async
1671 // so signal it to handle state changes immediately
1672 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1673 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1674 mSignalPending = true;
1675 mWaitWorkCV.broadcast();
1676}
1677
Eric Laurent81784c32012-11-19 14:55:58 -08001678// ----------------------------------------------------------------------------
1679// Playback
1680// ----------------------------------------------------------------------------
1681
1682AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1683 AudioStreamOut* output,
1684 audio_io_handle_t id,
1685 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001686 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001687 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001688 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001689 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001690 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001691 mMixerBuffer(NULL),
1692 mMixerBufferSize(0),
1693 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1694 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001695 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001696 mEffectBuffer(NULL),
1697 mEffectBufferSize(0),
1698 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1699 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001700 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001701 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001702 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001703 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001704 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001705 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001706 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001707 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001708 mMixerStatus(MIXER_IDLE),
1709 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001710 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001711 mBytesRemaining(0),
1712 mCurrentWriteLength(0),
1713 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001714 mWriteAckSequence(0),
1715 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001716 mScreenState(AudioFlinger::mScreenState),
1717 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001718 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001719 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1720 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001721{
Glenn Kastend7dca052015-03-05 16:05:54 -08001722 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1723 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001724
1725 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1726 // it would be safer to explicitly pass initial masterVolume/masterMute as
1727 // parameter.
1728 //
1729 // If the HAL we are using has support for master volume or master mute,
1730 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1731 // and the mute set to false).
1732 mMasterVolume = audioFlinger->masterVolume_l();
1733 mMasterMute = audioFlinger->masterMute_l();
1734 if (mOutput && mOutput->audioHwDev) {
1735 if (mOutput->audioHwDev->canSetMasterVolume()) {
1736 mMasterVolume = 1.0;
1737 }
1738
1739 if (mOutput->audioHwDev->canSetMasterMute()) {
1740 mMasterMute = false;
1741 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001742 mIsMsdDevice = strcmp(
1743 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001744 }
1745
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001746 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001747
Andy Hungc8fddf32018-08-08 18:32:37 -07001748 // TODO: We may also match on address as well as device type for
1749 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
1750 if (type == MIXER || type == DIRECT) {
1751 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
1752 "audio.timestamp.corrected_output_devices",
1753 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1754 : AUDIO_DEVICE_NONE));
1755 }
1756
Eric Laurent223fd5c2014-11-11 13:43:36 -08001757 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001758 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001759 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001760 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001761 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1762 }
Eric Laurent98e38192018-02-15 18:31:53 -08001763 // Audio patch volume is always max
1764 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1765 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001766}
1767
1768AudioFlinger::PlaybackThread::~PlaybackThread()
1769{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001770 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001771 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001772 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001773 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001774}
1775
1776void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1777{
1778 dumpInternals(fd, args);
1779 dumpTracks(fd, args);
1780 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001781 dprintf(fd, " Local log:\n");
1782 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001783}
1784
Glenn Kasten0f11b512014-01-31 16:18:54 -08001785void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001786{
Eric Laurent81784c32012-11-19 14:55:58 -08001787 String8 result;
1788
Marco Nelissenb2208842014-02-07 14:00:50 -08001789 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001790 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1791 const stream_type_t *st = &mStreamTypes[i];
1792 if (i > 0) {
1793 result.appendFormat(", ");
1794 }
1795 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1796 if (st->mute) {
1797 result.append("M");
1798 }
1799 }
1800 result.append("\n");
1801 write(fd, result.string(), result.length());
1802 result.clear();
1803
Eric Laurent81784c32012-11-19 14:55:58 -08001804 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1805 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001806 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001807 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001808
1809 size_t numtracks = mTracks.size();
1810 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001811 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001812 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001813 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001814 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001815 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001816 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001817 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001818 for (size_t i = 0; i < numtracks; ++i) {
1819 sp<Track> track = mTracks[i];
1820 if (track != 0) {
1821 bool active = mActiveTracks.indexOf(track) >= 0;
1822 if (active) {
1823 numactiveseen++;
1824 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001825 result.append(prefix);
1826 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001827 }
1828 }
1829 } else {
1830 result.append("\n");
1831 }
1832 if (numactiveseen != numactive) {
1833 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001834 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001835 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001836 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001837 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001838 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001839 sp<Track> track = mActiveTracks[i];
1840 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001841 result.append(prefix);
1842 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001843 }
1844 }
1845 }
1846
1847 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001848}
1849
1850void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1851{
Glenn Kasten44182c22015-03-05 17:12:23 -08001852 dumpBase(fd, args);
1853
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07001854 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08001855 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
1856 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
1857 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
1858 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001859 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001860 dprintf(fd, " Last write occurred (msecs): %llu\n",
1861 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001862 dprintf(fd, " Total writes: %d\n", mNumWrites);
1863 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1864 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1865 dprintf(fd, " Suspend count: %d\n", mSuspended);
1866 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1867 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1868 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1869 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001870 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001871 AudioStreamOut *output = mOutput;
1872 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001873 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1874 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001875 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1876 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1877 if (mPipeSink.get() != nullptr) {
1878 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1879 }
1880 if (output != nullptr) {
1881 dprintf(fd, " Hal stream dump:\n");
1882 (void)output->stream->dump(fd);
1883 }
Eric Laurent81784c32012-11-19 14:55:58 -08001884}
1885
1886// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001887
1888void AudioFlinger::PlaybackThread::onFirstRef()
1889{
Glenn Kastend7dca052015-03-05 16:05:54 -08001890 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001891}
1892
1893// ThreadBase virtuals
1894void AudioFlinger::PlaybackThread::preExit()
1895{
1896 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001897 // FIXME this is using hard-coded strings but in the future, this functionality will be
1898 // converted to use audio HAL extensions required to support tunneling
1899 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1900 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001901}
1902
1903// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1904sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1905 const sp<AudioFlinger::Client>& client,
1906 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001907 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001908 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001909 audio_format_t format,
1910 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001911 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001912 size_t *pNotificationFrameCount,
1913 uint32_t notificationsPerBuffer,
1914 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001915 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001916 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001917 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001918 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001919 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001920 status_t *status,
1921 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001922{
Glenn Kasten74935e42013-12-19 08:56:45 -08001923 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001924 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001925 sp<Track> track;
1926 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001927 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001928 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001929 uint32_t sampleRate;
1930
1931 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1932 lStatus = BAD_VALUE;
1933 goto Exit;
1934 }
Eric Laurent21da6472017-11-09 16:29:26 -08001935
1936 if (*pSampleRate == 0) {
1937 *pSampleRate = mSampleRate;
1938 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001939 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001940
1941 // special case for FAST flag considered OK if fast mixer is present
1942 if (hasFastMixer()) {
1943 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1944 }
1945
1946 // Check if requested flags are compatible with output stream flags
1947 if ((*flags & outputFlags) != *flags) {
1948 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1949 *flags, outputFlags);
1950 *flags = (audio_output_flags_t)(*flags & outputFlags);
1951 }
Eric Laurent81784c32012-11-19 14:55:58 -08001952
Eric Laurent81784c32012-11-19 14:55:58 -08001953 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001954 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001955 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001956 // PCM data
1957 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001958 // TODO: extract as a data library function that checks that a computationally
1959 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08001960 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07001961 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1962 (channelMask == AUDIO_CHANNEL_OUT_MONO
1963 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001964 // hardware sample rate
1965 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001966 // normal mixer has an associated fast mixer
1967 hasFastMixer() &&
1968 // there are sufficient fast track slots available
1969 (mFastTrackAvailMask != 0)
1970 // FIXME test that MixerThread for this fast track has a capable output HAL
1971 // FIXME add a permission test also?
1972 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001973 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1974 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001975 // read the fast track multiplier property the first time it is needed
1976 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1977 if (ok != 0) {
1978 ALOGE("%s pthread_once failed: %d", __func__, ok);
1979 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001980 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001981 }
Eric Laurent4c415062016-06-17 16:14:16 -07001982
1983 // check compatibility with audio effects.
1984 { // scope for mLock
1985 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001986 for (audio_session_t session : {
1987 AUDIO_SESSION_OUTPUT_STAGE,
1988 AUDIO_SESSION_OUTPUT_MIX,
1989 sessionId,
1990 }) {
1991 sp<EffectChain> chain = getEffectChain_l(session);
1992 if (chain.get() != nullptr) {
1993 audio_output_flags_t old = *flags;
1994 chain->checkOutputFlagCompatibility(flags);
1995 if (old != *flags) {
1996 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1997 (int)session, (int)old, (int)*flags);
1998 }
Eric Laurent4c415062016-06-17 16:14:16 -07001999 }
2000 }
2001 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002002 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002003 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2004 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002005 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002006 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2007 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002008 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002009 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002010 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002011 audio_is_linear_pcm(format),
2012 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002013 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002014 }
2015 }
Eric Laurent21da6472017-11-09 16:29:26 -08002016
2017 if (!audio_has_proportional_frames(format)) {
2018 if (sharedBuffer != 0) {
2019 // Same comment as below about ignoring frameCount parameter for set()
2020 frameCount = sharedBuffer->size();
2021 } else if (frameCount == 0) {
2022 frameCount = mNormalFrameCount;
2023 }
2024 if (notificationFrameCount != frameCount) {
2025 notificationFrameCount = frameCount;
2026 }
2027 } else if (sharedBuffer != 0) {
2028 // FIXME: Ensure client side memory buffers need
2029 // not have additional alignment beyond sample
2030 // (e.g. 16 bit stereo accessed as 32 bit frame).
2031 size_t alignment = audio_bytes_per_sample(format);
2032 if (alignment & 1) {
2033 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2034 alignment = 1;
2035 }
2036 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2037 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2038 if (channelCount > 1) {
2039 // More than 2 channels does not require stronger alignment than stereo
2040 alignment <<= 1;
2041 }
2042 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2043 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2044 sharedBuffer->pointer(), channelCount);
2045 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002046 goto Exit;
2047 }
Eric Laurent21da6472017-11-09 16:29:26 -08002048
2049 // When initializing a shared buffer AudioTrack via constructors,
2050 // there's no frameCount parameter.
2051 // But when initializing a shared buffer AudioTrack via set(),
2052 // there _is_ a frameCount parameter. We silently ignore it.
2053 frameCount = sharedBuffer->size() / frameSize;
2054 } else {
2055 size_t minFrameCount = 0;
2056 // For fast tracks we try to respect the application's request for notifications per buffer.
2057 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2058 if (notificationsPerBuffer > 0) {
2059 // Avoid possible arithmetic overflow during multiplication.
2060 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2061 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2062 notificationsPerBuffer, mFrameCount);
2063 } else {
2064 minFrameCount = mFrameCount * notificationsPerBuffer;
2065 }
2066 }
2067 } else {
2068 // For normal PCM streaming tracks, update minimum frame count.
2069 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2070 // cover audio hardware latency.
2071 // This is probably too conservative, but legacy application code may depend on it.
2072 // If you change this calculation, also review the start threshold which is related.
2073 uint32_t latencyMs = latency_l();
2074 if (latencyMs == 0) {
2075 ALOGE("Error when retrieving output stream latency");
2076 lStatus = UNKNOWN_ERROR;
2077 goto Exit;
2078 }
2079
2080 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2081 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2082
Eric Laurent81784c32012-11-19 14:55:58 -08002083 }
Eric Laurent21da6472017-11-09 16:29:26 -08002084 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002085 frameCount = minFrameCount;
2086 }
Eric Laurent81784c32012-11-19 14:55:58 -08002087 }
Eric Laurent21da6472017-11-09 16:29:26 -08002088
2089 // Make sure that application is notified with sufficient margin before underrun.
2090 // The client can divide the AudioTrack buffer into sub-buffers,
2091 // and expresses its desire to server as the notification frame count.
2092 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2093 size_t maxNotificationFrames;
2094 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2095 // notify every HAL buffer, regardless of the size of the track buffer
2096 maxNotificationFrames = mFrameCount;
2097 } else {
2098 // For normal tracks, use at least double-buffering if no sample rate conversion,
2099 // or at least triple-buffering if there is sample rate conversion
2100 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2101 maxNotificationFrames = frameCount / nBuffering;
2102 // If client requested a fast track but this was denied, then use the smaller maximum.
2103 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2104 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2105 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2106 maxNotificationFrames = maxNotificationFramesFastDenied;
2107 }
2108 }
2109 }
2110 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2111 if (notificationFrameCount == 0) {
2112 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2113 maxNotificationFrames, frameCount);
2114 } else {
2115 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2116 notificationFrameCount, maxNotificationFrames, frameCount);
2117 }
2118 notificationFrameCount = maxNotificationFrames;
2119 }
2120 }
2121
Glenn Kasten74935e42013-12-19 08:56:45 -08002122 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002123 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002124
Glenn Kastenc3df8382014-03-13 15:05:25 -07002125 switch (mType) {
2126
2127 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002128 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002129 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002130 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2131 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002132 sampleRate, format, channelMask, mOutput, mFormat);
2133 lStatus = BAD_VALUE;
2134 goto Exit;
2135 }
2136 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002137 break;
2138
2139 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002140 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002141 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2142 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002143 sampleRate, format, channelMask, mOutput, mFormat);
2144 lStatus = BAD_VALUE;
2145 goto Exit;
2146 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002147 break;
2148
2149 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002150 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002151 ALOGE("createTrack_l() Bad parameter: format %#x \""
2152 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153 format, mOutput, mFormat);
2154 lStatus = BAD_VALUE;
2155 goto Exit;
2156 }
Andy Hungcd044842014-08-07 11:04:34 -07002157 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002158 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2159 lStatus = BAD_VALUE;
2160 goto Exit;
2161 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002162 break;
2163
Eric Laurent81784c32012-11-19 14:55:58 -08002164 }
2165
2166 lStatus = initCheck();
2167 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002168 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002169 goto Exit;
2170 }
2171
2172 { // scope for mLock
2173 Mutex::Autolock _l(mLock);
2174
2175 // all tracks in same audio session must share the same routing strategy otherwise
2176 // conflicts will happen when tracks are moved from one output to another by audio policy
2177 // manager
2178 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2179 for (size_t i = 0; i < mTracks.size(); ++i) {
2180 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002181 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002182 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2183 if (sessionId == t->sessionId() && strategy != actual) {
2184 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2185 strategy, actual);
2186 lStatus = BAD_VALUE;
2187 goto Exit;
2188 }
2189 }
2190 }
2191
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002192 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002193 channelMask, frameCount,
2194 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002195 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002196
Glenn Kasten03003332013-08-06 15:40:54 -07002197 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2198 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002199 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002200 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002201 goto Exit;
2202 }
2203 mTracks.add(track);
2204
2205 sp<EffectChain> chain = getEffectChain_l(sessionId);
2206 if (chain != 0) {
2207 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2208 track->setMainBuffer(chain->inBuffer());
2209 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2210 chain->incTrackCnt();
2211 }
2212
Eric Laurent05067782016-06-01 18:27:28 -07002213 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002214 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2215 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2216 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002217 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002218 }
2219 }
2220
2221 lStatus = NO_ERROR;
2222
2223Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002224 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002225 return track;
2226}
2227
Andy Hung1bc088a2018-02-09 15:57:31 -08002228template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002229ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2230{
Andy Hungc0691382018-09-12 18:01:57 -07002231 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002232 const ssize_t index = mTracks.remove(track);
2233 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002234 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002235 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002236 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002237 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002238 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002239 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002240 }
2241 return index;
2242}
2243
Eric Laurent81784c32012-11-19 14:55:58 -08002244uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2245{
2246 return latency;
2247}
2248
2249uint32_t AudioFlinger::PlaybackThread::latency() const
2250{
2251 Mutex::Autolock _l(mLock);
2252 return latency_l();
2253}
2254uint32_t AudioFlinger::PlaybackThread::latency_l() const
2255{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002256 uint32_t latency;
2257 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2258 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002259 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002260 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002261}
2262
2263void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2264{
2265 Mutex::Autolock _l(mLock);
2266 // Don't apply master volume in SW if our HAL can do it for us.
2267 if (mOutput && mOutput->audioHwDev &&
2268 mOutput->audioHwDev->canSetMasterVolume()) {
2269 mMasterVolume = 1.0;
2270 } else {
2271 mMasterVolume = value;
2272 }
2273}
2274
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002275void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2276{
2277 mMasterBalance.store(balance);
2278}
2279
Eric Laurent81784c32012-11-19 14:55:58 -08002280void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2281{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002282 if (isDuplicating()) {
2283 return;
2284 }
Eric Laurent81784c32012-11-19 14:55:58 -08002285 Mutex::Autolock _l(mLock);
2286 // Don't apply master mute in SW if our HAL can do it for us.
2287 if (mOutput && mOutput->audioHwDev &&
2288 mOutput->audioHwDev->canSetMasterMute()) {
2289 mMasterMute = false;
2290 } else {
2291 mMasterMute = muted;
2292 }
2293}
2294
2295void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2296{
2297 Mutex::Autolock _l(mLock);
2298 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002299 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002300}
2301
2302void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2303{
2304 Mutex::Autolock _l(mLock);
2305 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002306 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002307}
2308
2309float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2310{
2311 Mutex::Autolock _l(mLock);
2312 return mStreamTypes[stream].volume;
2313}
2314
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002315void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2316{
2317 mOutput->stream->setVolume(left, right);
2318}
2319
Eric Laurent81784c32012-11-19 14:55:58 -08002320// addTrack_l() must be called with ThreadBase::mLock held
2321status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2322{
2323 status_t status = ALREADY_EXISTS;
2324
Eric Laurent81784c32012-11-19 14:55:58 -08002325 if (mActiveTracks.indexOf(track) < 0) {
2326 // the track is newly added, make sure it fills up all its
2327 // buffers before playing. This is to ensure the client will
2328 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002329 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330 TrackBase::track_state state = track->mState;
2331 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002332 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002333 mLock.lock();
2334 // abort track was stopped/paused while we released the lock
2335 if (state != track->mState) {
2336 if (status == NO_ERROR) {
2337 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002338 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002339 mLock.lock();
2340 }
2341 return INVALID_OPERATION;
2342 }
2343 // abort if start is rejected by audio policy manager
2344 if (status != NO_ERROR) {
2345 return PERMISSION_DENIED;
2346 }
2347#ifdef ADD_BATTERY_DATA
2348 // to track the speaker usage
2349 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2350#endif
2351 }
2352
Eric Laurent51716182016-02-29 18:00:56 -08002353 // set retry count for buffer fill
2354 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002355 if (track->isStopping_1()) {
2356 track->mRetryCount = kMaxTrackStopRetriesOffload;
2357 } else {
2358 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2359 }
2360 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002361 } else {
2362 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002363 track->mFillingUpStatus =
2364 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002365 }
2366
jiabin245cdd92018-12-07 17:55:15 -08002367 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2368 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002369 // Unlock due to VibratorService will lock for this call and will
2370 // call Tracks.mute/unmute which also require thread's lock.
2371 mLock.unlock();
2372 const int intensity = AudioFlinger::onExternalVibrationStart(
2373 track->getExternalVibration());
2374 mLock.lock();
jiabinbf6b0ec2019-02-12 12:30:12 -08002375 track->setHapticIntensity(static_cast<AudioMixer::haptic_intensity_t>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002376 // Haptic playback should be enabled by vibrator service.
2377 if (track->getHapticPlaybackEnabled()) {
2378 // Disable haptic playback of all active track to ensure only
2379 // one track playing haptic if current track should play haptic.
2380 for (const auto &t : mActiveTracks) {
2381 t->setHapticPlaybackEnabled(false);
2382 }
jiabin245cdd92018-12-07 17:55:15 -08002383 }
jiabin245cdd92018-12-07 17:55:15 -08002384 }
2385
Eric Laurent81784c32012-11-19 14:55:58 -08002386 track->mResetDone = false;
2387 track->mPresentationCompleteFrames = 0;
2388 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002389 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2390 if (chain != 0) {
2391 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2392 track->sessionId());
2393 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002394 }
2395
2396 status = NO_ERROR;
2397 }
2398
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002399 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002400 return status;
2401}
2402
Eric Laurentbfb1b832013-01-07 09:53:42 -08002403bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002404{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002405 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002406 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002407 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2408 track->mState = TrackBase::STOPPED;
2409 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002410 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002411 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002413 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002414
2415 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002416}
2417
2418void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2419{
2420 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002421
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002422 String8 result;
2423 track->appendDump(result, false /* active */);
2424 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002425
Eric Laurent81784c32012-11-19 14:55:58 -08002426 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002427 if (track->isFastTrack()) {
2428 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002429 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002430 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2431 mFastTrackAvailMask |= 1 << index;
2432 // redundant as track is about to be destroyed, for dumpsys only
2433 track->mFastIndex = -1;
2434 }
2435 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2436 if (chain != 0) {
2437 chain->decTrackCnt();
2438 }
2439}
2440
2441String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2442{
Eric Laurent81784c32012-11-19 14:55:58 -08002443 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002444 String8 out_s8;
2445 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2446 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002447 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002448 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002449}
2450
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002451status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2452 Mutex::Autolock _l(mLock);
2453 if (mOutput == nullptr || mOutput->stream == nullptr) {
2454 return NO_INIT;
2455 }
2456 return mOutput->stream->selectPresentation(presentationId, programId);
2457}
2458
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002459void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002460 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2461 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002462
Eric Laurent73e26b62015-04-27 16:55:58 -07002463 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002464
2465 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002466 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002467 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002468 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002469 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002470 desc->mChannelMask = mChannelMask;
2471 desc->mSamplingRate = mSampleRate;
2472 desc->mFormat = mFormat;
2473 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002474 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002475 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002476 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002477 break;
2478
Eric Laurent73e26b62015-04-27 16:55:58 -07002479 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002480 default:
2481 break;
2482 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002483 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002484}
2485
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002486void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002487{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002488 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002489}
2490
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002491void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002492{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002493 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002494}
2495
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002496void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002497{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002498 mCallbackThread->setAsyncError();
2499}
2500
Eric Laurent3b4529e2013-09-05 18:09:19 -07002501void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002502{
2503 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002504 // reject out of sequence requests
2505 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2506 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002507 mWaitWorkCV.signal();
2508 }
2509}
2510
Eric Laurent3b4529e2013-09-05 18:09:19 -07002511void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002512{
2513 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002514 // reject out of sequence requests
2515 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002516 // Register discontinuity when HW drain is completed because that can cause
2517 // the timestamp frame position to reset to 0 for direct and offload threads.
2518 // (Out of sequence requests are ignored, since the discontinuity would be handled
2519 // elsewhere, e.g. in flush).
2520 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002521 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002522 mWaitWorkCV.signal();
2523 }
2524}
2525
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002526void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002527{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002528 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002529 mSampleRate = mOutput->getSampleRate();
2530 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002531 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002532 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002533 }
Andy Hung9a592762014-07-21 21:56:01 -07002534 if ((mType == MIXER || mType == DUPLICATING)
2535 && !isValidPcmSinkChannelMask(mChannelMask)) {
2536 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2537 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002538 }
Andy Hunge5412692014-05-16 11:25:07 -07002539 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002540 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002541
2542 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002543 status_t result = mOutput->stream->getFormat(&mHALFormat);
2544 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002545 // Get format from the shim, which will be different than the HAL format
2546 // if playing compressed audio over HDMI passthrough.
2547 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002548 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002549 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002550 }
Andy Hung6146c082014-03-18 11:56:15 -07002551 if ((mType == MIXER || mType == DUPLICATING)
2552 && !isValidPcmSinkFormat(mFormat)) {
2553 LOG_FATAL("HAL format %#x not supported for mixed output",
2554 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002555 }
Phil Burk062e67a2015-02-11 13:40:50 -08002556 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002557 result = mOutput->stream->getBufferSize(&mBufferSize);
2558 LOG_ALWAYS_FATAL_IF(result != OK,
2559 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002560 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002561 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002562 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002563 mFrameCount);
2564 }
2565
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002566 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2567 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002568 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002569 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002570 }
2571 }
2572
Eric Laurentd1f69b02014-12-15 14:33:13 -08002573 mHwSupportsPause = false;
2574 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002575 bool supportsPause = false, supportsResume = false;
2576 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2577 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002578 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002579 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002580 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002581 } else if (supportsResume) {
2582 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002583 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002584 }
2585 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002586 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2587 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2588 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002589
Andy Hungfbfc3952015-01-15 13:33:51 -08002590 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2591 // For best precision, we use float instead of the associated output
2592 // device format (typically PCM 16 bit).
2593
2594 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2595 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2596 mBufferSize = mFrameSize * mFrameCount;
2597
2598 // TODO: We currently use the associated output device channel mask and sample rate.
2599 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2600 // (if a valid mask) to avoid premature downmix.
2601 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2602 // instead of the output device sample rate to avoid loss of high frequency information.
2603 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2604 }
2605
Andy Hung09a50072014-02-27 14:30:47 -08002606 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002607 double multiplier = 1.0;
2608 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2609 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002610 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2611 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002612
Eric Laurent81784c32012-11-19 14:55:58 -08002613 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2614 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2615 maxNormalFrameCount = maxNormalFrameCount & ~15;
2616 if (maxNormalFrameCount < minNormalFrameCount) {
2617 maxNormalFrameCount = minNormalFrameCount;
2618 }
2619 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2620 if (multiplier <= 1.0) {
2621 multiplier = 1.0;
2622 } else if (multiplier <= 2.0) {
2623 if (2 * mFrameCount <= maxNormalFrameCount) {
2624 multiplier = 2.0;
2625 } else {
2626 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2627 }
2628 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002629 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002630 }
2631 }
2632 mNormalFrameCount = multiplier * mFrameCount;
2633 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002634 if (mType == MIXER || mType == DUPLICATING) {
2635 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2636 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002637 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002638 mNormalFrameCount);
2639
Andy Hung08fb1742015-05-31 23:22:10 -07002640 // Check if we want to throttle the processing to no more than 2x normal rate
2641 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002642 mThreadThrottleTimeMs = 0;
2643 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002644 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2645
Andy Hung010a1a12014-03-13 13:57:33 -07002646 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2647 // Originally this was int16_t[] array, need to remove legacy implications.
2648 free(mSinkBuffer);
2649 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002650 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2651 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2652 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002653 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002654
Andy Hung69aed5f2014-02-25 17:24:40 -08002655 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2656 // drives the output.
2657 free(mMixerBuffer);
2658 mMixerBuffer = NULL;
2659 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002660 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002661 mMixerBufferSize = mNormalFrameCount * mChannelCount
2662 * audio_bytes_per_sample(mMixerBufferFormat);
2663 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2664 }
Andy Hung98ef9782014-03-04 14:46:50 -08002665 free(mEffectBuffer);
2666 mEffectBuffer = NULL;
2667 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002668 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002669 mEffectBufferSize = mNormalFrameCount * mChannelCount
2670 * audio_bytes_per_sample(mEffectBufferFormat);
2671 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2672 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002673
jiabin245cdd92018-12-07 17:55:15 -08002674 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2675 mChannelMask &= ~mHapticChannelMask;
2676 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2677 mChannelCount -= mHapticChannelCount;
2678
Eric Laurent81784c32012-11-19 14:55:58 -08002679 // force reconfiguration of effect chains and engines to take new buffer size and audio
2680 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002681 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002682 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2683 // matter.
2684 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2685 Vector< sp<EffectChain> > effectChains = mEffectChains;
2686 for (size_t i = 0; i < effectChains.size(); i ++) {
2687 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2688 }
2689}
2690
Kevin Rocard069c2712018-03-29 19:09:14 -07002691void AudioFlinger::PlaybackThread::updateMetadata_l()
2692{
Kevin Rocard12381092018-04-11 09:19:59 -07002693 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2694 return; // That should not happen
2695 }
2696 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2697 for (const sp<Track> &track : mActiveTracks) {
2698 // Do not short-circuit as all hasChanged states must be reset
2699 // as all the metadata are going to be sent
2700 hasChanged |= track->readAndClearHasChanged();
2701 }
2702 if (!hasChanged) {
2703 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002704 }
2705 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002706 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002707 for (const sp<Track> &track : mActiveTracks) {
2708 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002709 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002710 }
Kevin Rocard12381092018-04-11 09:19:59 -07002711 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002712}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002713
Kevin Rocard12381092018-04-11 09:19:59 -07002714void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2715 const StreamOutHalInterface::SourceMetadata& metadata)
2716{
2717 mOutput->stream->updateSourceMetadata(metadata);
2718};
2719
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002720status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002721{
2722 if (halFrames == NULL || dspFrames == NULL) {
2723 return BAD_VALUE;
2724 }
2725 Mutex::Autolock _l(mLock);
2726 if (initCheck() != NO_ERROR) {
2727 return INVALID_OPERATION;
2728 }
Andy Hung818e7a32016-02-16 18:08:07 -08002729 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002730 *halFrames = framesWritten;
2731
2732 if (isSuspended()) {
2733 // return an estimation of rendered frames when the output is suspended
2734 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002735 *dspFrames = (uint32_t)
2736 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002737 return NO_ERROR;
2738 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002739 status_t status;
2740 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002741 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002742 *dspFrames = (size_t)frames;
2743 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002744 }
2745}
2746
Eric Laurent4c415062016-06-17 16:14:16 -07002747// hasAudioSession_l() must be called with ThreadBase::mLock held
2748uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002749{
Eric Laurent81784c32012-11-19 14:55:58 -08002750 uint32_t result = 0;
2751 if (getEffectChain_l(sessionId) != 0) {
2752 result = EFFECT_SESSION;
2753 }
2754
2755 for (size_t i = 0; i < mTracks.size(); ++i) {
2756 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002757 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002758 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002759 if (track->isFastTrack()) {
2760 result |= FAST_SESSION;
2761 }
Eric Laurent81784c32012-11-19 14:55:58 -08002762 break;
2763 }
2764 }
2765
2766 return result;
2767}
2768
Glenn Kastend848eb42016-03-08 13:42:11 -08002769uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002770{
2771 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2772 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2773 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2774 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2775 }
2776 for (size_t i = 0; i < mTracks.size(); i++) {
2777 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002778 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002779 return AudioSystem::getStrategyForStream(track->streamType());
2780 }
2781 }
2782 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2783}
2784
2785
Phil Burk062e67a2015-02-11 13:40:50 -08002786AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002787{
2788 Mutex::Autolock _l(mLock);
2789 return mOutput;
2790}
2791
Phil Burk062e67a2015-02-11 13:40:50 -08002792AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
2794 Mutex::Autolock _l(mLock);
2795 AudioStreamOut *output = mOutput;
2796 mOutput = NULL;
2797 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2798 // must push a NULL and wait for ack
2799 mOutputSink.clear();
2800 mPipeSink.clear();
2801 mNormalSink.clear();
2802 return output;
2803}
2804
2805// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002806sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002807{
2808 if (mOutput == NULL) {
2809 return NULL;
2810 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002811 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002812}
2813
2814uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2815{
2816 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2817}
2818
2819status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2820{
2821 if (!isValidSyncEvent(event)) {
2822 return BAD_VALUE;
2823 }
2824
2825 Mutex::Autolock _l(mLock);
2826
2827 for (size_t i = 0; i < mTracks.size(); ++i) {
2828 sp<Track> track = mTracks[i];
2829 if (event->triggerSession() == track->sessionId()) {
2830 (void) track->setSyncEvent(event);
2831 return NO_ERROR;
2832 }
2833 }
2834
2835 return NAME_NOT_FOUND;
2836}
2837
2838bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2839{
2840 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2841}
2842
2843void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2844 const Vector< sp<Track> >& tracksToRemove)
2845{
Andy Hungfe726a62018-09-27 15:17:25 -07002846 // Miscellaneous track cleanup when removed from the active list,
2847 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002848#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002849 for (const auto& track : tracksToRemove) {
2850 if (track->isExternalTrack()) {
2851 // to track the speaker usage
2852 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002853 }
2854 }
Andy Hungfe726a62018-09-27 15:17:25 -07002855#else
2856 (void)tracksToRemove; // suppress unused warning
2857#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002858}
2859
2860void AudioFlinger::PlaybackThread::checkSilentMode_l()
2861{
2862 if (!mMasterMute) {
2863 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002864 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2865 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2866 return;
2867 }
Eric Laurent81784c32012-11-19 14:55:58 -08002868 if (property_get("ro.audio.silent", value, "0") > 0) {
2869 char *endptr;
2870 unsigned long ul = strtoul(value, &endptr, 0);
2871 if (*endptr == '\0' && ul != 0) {
2872 ALOGD("Silence is golden");
2873 // The setprop command will not allow a property to be changed after
2874 // the first time it is set, so we don't have to worry about un-muting.
2875 setMasterMute_l(true);
2876 }
2877 }
2878 }
2879}
2880
2881// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002883{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002884 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002885 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002887 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002888
2889 // If an NBAIO sink is present, use it to write the normal mixer's submix
2890 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002891
Andy Hung010a1a12014-03-13 13:57:33 -07002892 const size_t count = mBytesRemaining / mFrameSize;
2893
Simon Wilson2d590962012-11-29 15:18:50 -08002894 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002895 // update the setpoint when AudioFlinger::mScreenState changes
2896 uint32_t screenState = AudioFlinger::mScreenState;
2897 if (screenState != mScreenState) {
2898 mScreenState = screenState;
2899 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2900 if (pipe != NULL) {
2901 pipe->setAvgFrames((mScreenState & 1) ?
2902 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2903 }
2904 }
Andy Hung010a1a12014-03-13 13:57:33 -07002905 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002906 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002907 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002908 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002909#ifdef TEE_SINK
2910 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2911#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002912 } else {
2913 bytesWritten = framesWritten;
2914 }
2915 // otherwise use the HAL / AudioStreamOut directly
2916 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002917 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002918
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002920 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2921 mWriteAckSequence += 2;
2922 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002923 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002924 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002925 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002926 // FIXME We should have an implementation of timestamps for direct output threads.
2927 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002928 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002929
Eric Laurentbfb1b832013-01-07 09:53:42 -08002930 if (mUseAsyncWrite &&
2931 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2932 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002933 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002934 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002935 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002936 }
Eric Laurent81784c32012-11-19 14:55:58 -08002937 }
2938
Eric Laurent81784c32012-11-19 14:55:58 -08002939 mNumWrites++;
2940 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002941 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002942 return bytesWritten;
2943}
2944
2945void AudioFlinger::PlaybackThread::threadLoop_drain()
2946{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002947 bool supportsDrain = false;
2948 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002949 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2950 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002951 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2952 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002953 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002954 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002955 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002956 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002957 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002958 }
2959}
2960
2961void AudioFlinger::PlaybackThread::threadLoop_exit()
2962{
Eric Laurent275e8e92014-11-30 15:14:47 -08002963 {
2964 Mutex::Autolock _l(mLock);
2965 for (size_t i = 0; i < mTracks.size(); i++) {
2966 sp<Track> track = mTracks[i];
2967 track->invalidate();
2968 }
Andy Hungdae27702016-10-31 14:01:16 -07002969 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2970 // After we exit there are no more track changes sent to BatteryNotifier
2971 // because that requires an active threadLoop.
2972 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2973 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002974 }
Eric Laurent81784c32012-11-19 14:55:58 -08002975}
2976
2977/*
2978The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002979 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002980 - mActiveSleepTimeUs from activeSleepTimeUs()
2981 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002982 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2983 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002984 - maxPeriod from frame count and sample rate (MIXER only)
2985
2986The parameters that affect these derived values are:
2987 - frame count
2988 - frame size
2989 - sample rate
2990 - device type: A2DP or not
2991 - device latency
2992 - format: PCM or not
2993 - active sleep time
2994 - idle sleep time
2995*/
2996
2997void AudioFlinger::PlaybackThread::cacheParameters_l()
2998{
Andy Hung25c2dac2014-02-27 14:56:00 -08002999 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003000 mActiveSleepTimeUs = activeSleepTimeUs();
3001 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003002
3003 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3004 // truncating audio when going to standby.
3005 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
3006 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
3007 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3008 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3009 }
3010 }
Eric Laurent81784c32012-11-19 14:55:58 -08003011}
3012
Eric Laurent13084622016-05-17 10:51:49 -07003013bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003014{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003015 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003016 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003017 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003018 size_t size = mTracks.size();
3019 for (size_t i = 0; i < size; i++) {
3020 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003021 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003022 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003023 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003024 }
3025 }
Eric Laurent13084622016-05-17 10:51:49 -07003026 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003027}
3028
Haynes Mathew George05317d22016-05-03 16:34:26 -07003029void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3030{
3031 Mutex::Autolock _l(mLock);
3032 invalidateTracks_l(streamType);
3033}
3034
Eric Laurent81784c32012-11-19 14:55:58 -08003035status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3036{
Glenn Kastend848eb42016-03-08 13:42:11 -08003037 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003038 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003039 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003040 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3041 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3042 &halInBuffer);
3043 if (result != OK) return result;
3044 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003045 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003046 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003047 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003048 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003049 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003050 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003051 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003052 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003053 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003054 &halInBuffer);
3055 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003056#ifdef FLOAT_EFFECT_CHAIN
3057 buffer = halInBuffer->audioBuffer()->f32;
3058#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003059 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003060#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003061 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3062 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003063 }
3064
3065 // Attach all tracks with same session ID to this chain.
3066 for (size_t i = 0; i < mTracks.size(); ++i) {
3067 sp<Track> track = mTracks[i];
3068 if (session == track->sessionId()) {
3069 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3070 buffer);
3071 track->setMainBuffer(buffer);
3072 chain->incTrackCnt();
3073 }
3074 }
3075
3076 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003077 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003078 if (session == track->sessionId()) {
3079 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3080 chain->incActiveTrackCnt();
3081 }
3082 }
3083 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003084 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003085 chain->setInBuffer(halInBuffer);
3086 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003087 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003088 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003089 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3090 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003091 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003092 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003093 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003094 // Effect chain for other sessions are inserted at beginning of effect
3095 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003096 // sessions is not important.
3097 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3098 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3099 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003100 size_t size = mEffectChains.size();
3101 size_t i = 0;
3102 for (i = 0; i < size; i++) {
3103 if (mEffectChains[i]->sessionId() < session) {
3104 break;
3105 }
3106 }
3107 mEffectChains.insertAt(chain, i);
3108 checkSuspendOnAddEffectChain_l(chain);
3109
3110 return NO_ERROR;
3111}
3112
3113size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3114{
Glenn Kastend848eb42016-03-08 13:42:11 -08003115 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003116
3117 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3118
3119 for (size_t i = 0; i < mEffectChains.size(); i++) {
3120 if (chain == mEffectChains[i]) {
3121 mEffectChains.removeAt(i);
3122 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003123 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003124 if (session == track->sessionId()) {
3125 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3126 chain.get(), session);
3127 chain->decActiveTrackCnt();
3128 }
3129 }
3130
3131 // detach all tracks with same session ID from this chain
3132 for (size_t i = 0; i < mTracks.size(); ++i) {
3133 sp<Track> track = mTracks[i];
3134 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003135 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003136 chain->decTrackCnt();
3137 }
3138 }
3139 break;
3140 }
3141 }
3142 return mEffectChains.size();
3143}
3144
3145status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003146 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003147{
3148 Mutex::Autolock _l(mLock);
3149 return attachAuxEffect_l(track, EffectId);
3150}
3151
3152status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003153 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003154{
3155 status_t status = NO_ERROR;
3156
3157 if (EffectId == 0) {
3158 track->setAuxBuffer(0, NULL);
3159 } else {
3160 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3161 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3162 if (effect != 0) {
3163 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3164 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3165 } else {
3166 status = INVALID_OPERATION;
3167 }
3168 } else {
3169 status = BAD_VALUE;
3170 }
3171 }
3172 return status;
3173}
3174
3175void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3176{
3177 for (size_t i = 0; i < mTracks.size(); ++i) {
3178 sp<Track> track = mTracks[i];
3179 if (track->auxEffectId() == effectId) {
3180 attachAuxEffect_l(track, 0);
3181 }
3182 }
3183}
3184
3185bool AudioFlinger::PlaybackThread::threadLoop()
3186{
Glenn Kasten388d5712017-04-07 14:38:41 -07003187 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003188
Eric Laurent81784c32012-11-19 14:55:58 -08003189 Vector< sp<Track> > tracksToRemove;
3190
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003191 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003192 nsecs_t lastWriteFinished = -1; // time last server write completed
3193 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003194
3195 // MIXER
3196 nsecs_t lastWarning = 0;
3197
3198 // DUPLICATING
3199 // FIXME could this be made local to while loop?
3200 writeFrames = 0;
3201
3202 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003203 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003204
3205 if (mType == MIXER) {
3206 sleepTimeShift = 0;
3207 }
3208
3209 CpuStats cpuStats;
3210 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3211
3212 acquireWakeLock();
3213
Glenn Kasteneef598c2017-04-03 14:41:13 -07003214 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3215 // thread associated with this PlaybackThread.
3216 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3217 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003218 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3219 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003220 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003221 const char *logString = NULL;
3222
rago1bb90822017-05-02 18:31:48 -07003223 // Estimated time for next buffer to be written to hal. This is used only on
3224 // suspended mode (for now) to help schedule the wait time until next iteration.
3225 nsecs_t timeLoopNextNs = 0;
3226
Eric Laurent664539d2013-09-23 18:24:31 -07003227 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003228
Andy Hungf3234512018-07-03 14:51:47 -07003229 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3230 // TODO: add confirmation checks:
3231 // 1) DIRECT threads and linear PCM format really resets to 0?
3232 // 2) Is frame count really valid if not linear pcm?
3233 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3234 if (mType == OFFLOAD || mType == DIRECT) {
3235 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3236 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003237 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003238
Eric Laurent81784c32012-11-19 14:55:58 -08003239 while (!exitPending())
3240 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003241 // Log merge requests are performed during AudioFlinger binder transactions, but
3242 // that does not cover audio playback. It's requested here for that reason.
3243 mAudioFlinger->requestLogMerge();
3244
Eric Laurent81784c32012-11-19 14:55:58 -08003245 cpuStats.sample(myName);
3246
3247 Vector< sp<EffectChain> > effectChains;
3248
Andy Hung2dbffc22018-08-08 18:50:41 -07003249 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3250 //
3251 // Note: we access outDevice() outside of mLock.
3252 if (isMsdDevice() && (outDevice() & AUDIO_DEVICE_OUT_BUS) != 0) {
3253 // Here, we try for the AF lock, but do not block on it as the latency
3254 // is more informational.
3255 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3256 std::vector<PatchPanel::SoftwarePatch> swPatches;
3257 double latencyMs;
3258 status_t status = INVALID_OPERATION;
3259 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3260 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3261 && swPatches.size() > 0) {
3262 status = swPatches[0].getLatencyMs_l(&latencyMs);
3263 downstreamPatchHandle = swPatches[0].getPatchHandle();
3264 }
3265 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003266 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003267 lastDownstreamPatchHandle = downstreamPatchHandle;
3268 }
3269 if (status == OK) {
3270 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003271 // latency of 5 seconds).
3272 const double minLatency = 0., maxLatency = 5000.;
3273 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003274 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003275 } else {
3276 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003277 if (latencyMs < minLatency) latencyMs = minLatency;
3278 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003279 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003280 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003281 }
3282 mAudioFlinger->mLock.unlock();
3283 }
3284 } else {
3285 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3286 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003287 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003288 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3289 }
3290 }
3291
Eric Laurent81784c32012-11-19 14:55:58 -08003292 { // scope for mLock
3293
3294 Mutex::Autolock _l(mLock);
3295
Eric Laurent021cf962014-05-13 10:18:14 -07003296 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003297
Glenn Kasteneef598c2017-04-03 14:41:13 -07003298 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003299 if (logString != NULL) {
3300 mNBLogWriter->logTimestamp();
3301 mNBLogWriter->log(logString);
3302 logString = NULL;
3303 }
3304
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003305 // Collect timestamp statistics for the Playback Thread types that support it.
3306 if (mType == MIXER
3307 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003308 || mType == DIRECT
3309 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003310 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003311 // and associate with the sink frames written out. We need
3312 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003313 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003314 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003315 if (mStandby) {
3316 mTimestampVerifier.discontinuity();
3317 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3318 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3319 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3320 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003321
3322 if (isTimestampCorrectionEnabled()) {
3323 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3324 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3325 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3326 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3327 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3328 = correctedTimestamp.mFrames;
3329 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3330 = correctedTimestamp.mTimeNs;
3331 ALOGV("TS_AFTER: %d %lld %lld", id(),
3332 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3333 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003334
3335 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003336 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003337 const int64_t newPosition =
3338 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003339 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003340 // prevent retrograde
3341 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3342 newPosition,
3343 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3344 - mSuspendedFrames));
3345 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003346 }
3347
Andy Hung818e7a32016-02-16 18:08:07 -08003348 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003349 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003350
3351 // We keep track of the last valid kernel position in case we are in underrun
3352 // and the normal mixer period is the same as the fast mixer period, or there
3353 // is some error from the HAL.
3354 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3355 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3356 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3357 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3358 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3359
3360 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3361 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3362 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3363 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003364 }
3365
3366 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3367 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003368 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003369 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003370 }
3371
Andy Hung818e7a32016-02-16 18:08:07 -08003372 // copy over kernel info
3373 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003374 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3375 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003376 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3377 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003378 } else {
3379 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003380 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003381
Andy Hungc54b1ff2016-02-23 14:07:07 -08003382 // mFramesWritten for non-offloaded tracks are contiguous
3383 // even after standby() is called. This is useful for the track frame
3384 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003385 bool serverLocationUpdate = false;
3386 if (mFramesWritten != lastFramesWritten) {
3387 serverLocationUpdate = true;
3388 lastFramesWritten = mFramesWritten;
3389 }
3390 // Only update timestamps if there is a meaningful change.
3391 // Either the kernel timestamp must be valid or we have written something.
3392 if (kernelLocationUpdate || serverLocationUpdate) {
3393 if (serverLocationUpdate) {
3394 // use the time before we called the HAL write - it is a bit more accurate
3395 // to when the server last read data than the current time here.
3396 //
3397 // If we haven't written anything, mLastWriteTime will be -1
3398 // and we use systemTime().
3399 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3400 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3401 ? systemTime() : mLastWriteTime;
3402 }
Andy Hungdae27702016-10-31 14:01:16 -07003403
3404 for (const sp<Track> &t : mActiveTracks) {
3405 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003406 t->updateTrackFrameInfo(
3407 t->mAudioTrackServerProxy->framesReleased(),
3408 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003409 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003410 mTimestamp);
3411 }
Andy Hunge10393e2015-06-12 13:59:33 -07003412 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003413 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003414 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003415#if 0
3416 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003417 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003418 timespec ts;
3419 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003420 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003421 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003422 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003423 }
3424 ++z;
3425#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003426 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003427 if (mSignalPending) {
3428 // A signal was raised while we were unlocked
3429 mSignalPending = false;
3430 } else if (waitingAsyncCallback_l()) {
3431 if (exitPending()) {
3432 break;
3433 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003434 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003435 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003436 releaseWakeLock_l();
3437 released = true;
3438 }
Andy Hung10cbff12017-02-21 17:30:14 -08003439
3440 const int64_t waitNs = computeWaitTimeNs_l();
3441 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3442 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3443 if (status == TIMED_OUT) {
3444 mSignalPending = true; // if timeout recheck everything
3445 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003446 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003447 if (released) {
3448 acquireWakeLock_l();
3449 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003450 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3451 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003452
3453 continue;
3454 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003455 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003456 isSuspended()) {
3457 // put audio hardware into standby after short delay
3458 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003459
3460 threadLoop_standby();
3461
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003462 // This is where we go into standby
3463 if (!mStandby) {
3464 LOG_AUDIO_STATE();
3465 }
Eric Laurent81784c32012-11-19 14:55:58 -08003466 mStandby = true;
3467 }
3468
Eric Tan39ec8d62018-07-24 09:49:29 -07003469 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003470 // we're about to wait, flush the binder command buffer
3471 IPCThreadState::self()->flushCommands();
3472
3473 clearOutputTracks();
3474
3475 if (exitPending()) {
3476 break;
3477 }
3478
3479 releaseWakeLock_l();
3480 // wait until we have something to do...
3481 ALOGV("%s going to sleep", myName.string());
3482 mWaitWorkCV.wait(mLock);
3483 ALOGV("%s waking up", myName.string());
3484 acquireWakeLock_l();
3485
3486 mMixerStatus = MIXER_IDLE;
3487 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3488 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003489 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003490 checkSilentMode_l();
3491
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003492 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3493 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003494 if (mType == MIXER) {
3495 sleepTimeShift = 0;
3496 }
3497
3498 continue;
3499 }
3500 }
Eric Laurent81784c32012-11-19 14:55:58 -08003501 // mMixerStatusIgnoringFastTracks is also updated internally
3502 mMixerStatus = prepareTracks_l(&tracksToRemove);
3503
Andy Hungdae27702016-10-31 14:01:16 -07003504 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003505
Kevin Rocard069c2712018-03-29 19:09:14 -07003506 updateMetadata_l();
3507
Eric Laurent81784c32012-11-19 14:55:58 -08003508 // prevent any changes in effect chain list and in each effect chain
3509 // during mixing and effect process as the audio buffers could be deleted
3510 // or modified if an effect is created or deleted
3511 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003512 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003513
Eric Laurentbfb1b832013-01-07 09:53:42 -08003514 if (mBytesRemaining == 0) {
3515 mCurrentWriteLength = 0;
3516 if (mMixerStatus == MIXER_TRACKS_READY) {
3517 // threadLoop_mix() sets mCurrentWriteLength
3518 threadLoop_mix();
3519 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3520 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003521 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003522 // must be written to HAL
3523 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003524 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003525 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003526 }
3527 }
Andy Hung98ef9782014-03-04 14:46:50 -08003528 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003529 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003530 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3531 // or mSinkBuffer (if there are no effects).
3532 //
3533 // This is done pre-effects computation; if effects change to
3534 // support higher precision, this needs to move.
3535 //
3536 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003537 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003538 if (mMixerBufferValid) {
3539 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3540 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3541
Andy Hung2ddee192015-12-18 17:34:44 -08003542 // mono blend occurs for mixer threads only (not direct or offloaded)
3543 // and is handled here if we're going directly to the sink.
3544 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003545 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3546 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003547 }
3548
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003549 if (!hasFastMixer()) {
3550 // Balance must take effect after mono conversion.
3551 // We do it here if there is no FastMixer.
3552 // mBalance detects zero balance within the class for speed (not needed here).
3553 mBalance.setBalance(mMasterBalance.load());
3554 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3555 }
3556
Andy Hung98ef9782014-03-04 14:46:50 -08003557 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003558 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3559
3560 // If we're going directly to the sink and there are haptic channels,
3561 // we should adjust channels as the sample data is partially interleaved
3562 // in this case.
3563 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3564 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3565 mChannelCount + mHapticChannelCount,
3566 audio_bytes_per_sample(format),
3567 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3568 }
Andy Hung98ef9782014-03-04 14:46:50 -08003569 }
3570
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 mBytesRemaining = mCurrentWriteLength;
3572 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003573 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3574 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3575 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3576 mBytesWritten += mBytesRemaining;
3577 mFramesWritten += framesRemaining;
3578 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003579 mBytesRemaining = 0;
3580 }
Eric Laurent81784c32012-11-19 14:55:58 -08003581
Eric Laurentbfb1b832013-01-07 09:53:42 -08003582 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003583 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003584 for (size_t i = 0; i < effectChains.size(); i ++) {
3585 effectChains[i]->process_l();
3586 }
Eric Laurent81784c32012-11-19 14:55:58 -08003587 }
3588 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003589 // Process effect chains for offloaded thread even if no audio
3590 // was read from audio track: process only updates effect state
3591 // and thus does have to be synchronized with audio writes but may have
3592 // to be called while waiting for async write callback
3593 if (mType == OFFLOAD) {
3594 for (size_t i = 0; i < effectChains.size(); i ++) {
3595 effectChains[i]->process_l();
3596 }
3597 }
Eric Laurent81784c32012-11-19 14:55:58 -08003598
Andy Hung98ef9782014-03-04 14:46:50 -08003599 // Only if the Effects buffer is enabled and there is data in the
3600 // Effects buffer (buffer valid), we need to
3601 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003602 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003603 if (mEffectBufferValid) {
3604 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003605
3606 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003607 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3608 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003609 }
3610
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003611 if (!hasFastMixer()) {
3612 // Balance must take effect after mono conversion.
3613 // We do it here if there is no FastMixer.
3614 // mBalance detects zero balance within the class for speed (not needed here).
3615 mBalance.setBalance(mMasterBalance.load());
3616 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3617 }
3618
Andy Hung98ef9782014-03-04 14:46:50 -08003619 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003620 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3621 // The sample data is partially interleaved when haptic channels exist,
3622 // we need to adjust channels here.
3623 if (mHapticChannelCount > 0) {
3624 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3625 mChannelCount + mHapticChannelCount,
3626 audio_bytes_per_sample(mFormat),
3627 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3628 }
Andy Hung98ef9782014-03-04 14:46:50 -08003629 }
3630
Eric Laurent81784c32012-11-19 14:55:58 -08003631 // enable changes in effect chain
3632 unlockEffectChains(effectChains);
3633
Eric Laurentbfb1b832013-01-07 09:53:42 -08003634 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003635 // mSleepTimeUs == 0 means we must write to audio hardware
3636 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003637 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003638 // We save lastWriteFinished here, as previousLastWriteFinished,
3639 // for throttling. On thread start, previousLastWriteFinished will be
3640 // set to -1, which properly results in no throttling after the first write.
3641 nsecs_t previousLastWriteFinished = lastWriteFinished;
3642 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003643 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003644 // FIXME rewrite to reduce number of system calls
3645 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003646 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003647 lastWriteFinished = systemTime();
3648 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003649 if (ret < 0) {
3650 mBytesRemaining = 0;
3651 } else {
3652 mBytesWritten += ret;
3653 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003654 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003655 }
3656 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3657 (mMixerStatus == MIXER_DRAIN_ALL)) {
3658 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003659 }
Andy Hung08fb1742015-05-31 23:22:10 -07003660 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003661 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003662 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003663 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003664 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003665 ATRACE_NAME("underrun");
3666 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003667 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003668 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003669 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003670 }
Andy Hung08fb1742015-05-31 23:22:10 -07003671
3672 if (mThreadThrottle
3673 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3674 && ret > 0) { // we wrote something
3675 // Limit MixerThread data processing to no more than twice the
3676 // expected processing rate.
3677 //
3678 // This helps prevent underruns with NuPlayer and other applications
3679 // which may set up buffers that are close to the minimum size, or use
3680 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3681 //
3682 // The throttle smooths out sudden large data drains from the device,
3683 // e.g. when it comes out of standby, which often causes problems with
3684 // (1) mixer threads without a fast mixer (which has its own warm-up)
3685 // (2) minimum buffer sized tracks (even if the track is full,
3686 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003687 //
3688 // Total time spent in last processing cycle equals time spent in
3689 // 1. threadLoop_write, as well as time spent in
3690 // 2. threadLoop_mix (significant for heavy mixing, especially
3691 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003692
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003693 // it's OK if deltaMs (and deltaNs) is an overestimate.
3694 nsecs_t deltaNs;
3695 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3696 __builtin_sub_overflow(
3697 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3698 const int32_t deltaMs = deltaNs / 1000000;
3699
Ivan Lozanoea04d392017-11-07 14:37:07 -08003700 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003701 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3702 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003703 // notify of throttle start on verbose log
3704 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3705 "mixer(%p) throttle begin:"
3706 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003707 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003708 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003709 // Throttle must be attributed to the previous mixer loop's write time
3710 // to allow back-to-back throttling.
3711 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003712 } else {
3713 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3714 if (diff > 0) {
3715 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003716 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003717 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3718 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003719 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003720 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3721 }
Andy Hung08fb1742015-05-31 23:22:10 -07003722 }
3723 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003724 }
Eric Laurent81784c32012-11-19 14:55:58 -08003725
Eric Laurentbfb1b832013-01-07 09:53:42 -08003726 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003727 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003728 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003729 // suspended requires accurate metering of sleep time.
3730 if (isSuspended()) {
3731 // advance by expected sleepTime
3732 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3733 const nsecs_t nowNs = systemTime();
3734
3735 // compute expected next time vs current time.
3736 // (negative deltas are treated as delays).
3737 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3738 if (deltaNs < -kMaxNextBufferDelayNs) {
3739 // Delays longer than the max allowed trigger a reset.
3740 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3741 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3742 timeLoopNextNs = nowNs + deltaNs;
3743 } else if (deltaNs < 0) {
3744 // Delays within the max delay allowed: zero the delta/sleepTime
3745 // to help the system catch up in the next iteration(s)
3746 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3747 deltaNs = 0;
3748 }
3749 // update sleep time (which is >= 0)
3750 mSleepTimeUs = deltaNs / 1000;
3751 }
Eric Laurente93cc032016-05-05 10:15:10 -07003752 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3753 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003754 }
Glenn Kastene7754022014-10-31 12:11:26 -07003755 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003756 }
Eric Laurent81784c32012-11-19 14:55:58 -08003757 }
3758
3759 // Finally let go of removed track(s), without the lock held
3760 // since we can't guarantee the destructors won't acquire that
3761 // same lock. This will also mutate and push a new fast mixer state.
3762 threadLoop_removeTracks(tracksToRemove);
3763 tracksToRemove.clear();
3764
3765 // FIXME I don't understand the need for this here;
3766 // it was in the original code but maybe the
3767 // assignment in saveOutputTracks() makes this unnecessary?
3768 clearOutputTracks();
3769
3770 // Effect chains will be actually deleted here if they were removed from
3771 // mEffectChains list during mixing or effects processing
3772 effectChains.clear();
3773
3774 // FIXME Note that the above .clear() is no longer necessary since effectChains
3775 // is now local to this block, but will keep it for now (at least until merge done).
3776 }
3777
Eric Laurentbfb1b832013-01-07 09:53:42 -08003778 threadLoop_exit();
3779
Eric Laurentcf817a22014-08-04 20:36:31 -07003780 if (!mStandby) {
3781 threadLoop_standby();
3782 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003783 }
3784
3785 releaseWakeLock();
3786
3787 ALOGV("Thread %p type %d exiting", this, mType);
3788 return false;
3789}
3790
Eric Laurentbfb1b832013-01-07 09:53:42 -08003791// removeTracks_l() must be called with ThreadBase::mLock held
3792void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3793{
Andy Hungfe726a62018-09-27 15:17:25 -07003794 for (const auto& track : tracksToRemove) {
3795 mActiveTracks.remove(track);
3796 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3797 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3798 if (chain != 0) {
3799 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3800 __func__, track->id(), chain.get(), track->sessionId());
3801 chain->decActiveTrackCnt();
3802 }
3803 // If an external client track, inform APM we're no longer active, and remove if needed.
3804 // We do this under lock so that the state is consistent if the Track is destroyed.
3805 if (track->isExternalTrack()) {
3806 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003807 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003808 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003809 }
3810 }
Andy Hungfe726a62018-09-27 15:17:25 -07003811 if (track->isTerminated()) {
3812 // remove from our tracks vector
3813 removeTrack_l(track);
3814 }
jiabin57303cc2018-12-18 15:45:57 -08003815 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
3816 && mHapticChannelCount > 0) {
3817 mLock.unlock();
3818 // Unlock due to VibratorService will lock for this call and will
3819 // call Tracks.mute/unmute which also require thread's lock.
3820 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
3821 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08003822 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003823 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003824}
Eric Laurent81784c32012-11-19 14:55:58 -08003825
Eric Laurentaccc1472013-09-20 09:36:34 -07003826status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3827{
3828 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003829 ExtendedTimestamp ets;
3830 status_t status = mNormalSink->getTimestamp(ets);
3831 if (status == NO_ERROR) {
3832 status = ets.getBestTimestamp(&timestamp);
3833 }
3834 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003835 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003836 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003837 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003838 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003839 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11003840 if (mDownstreamLatencyStatMs.getN() > 0) {
3841 const uint32_t positionOffset =
3842 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3843 if (positionOffset > timestamp.mPosition) {
3844 timestamp.mPosition = 0;
3845 } else {
3846 timestamp.mPosition -= positionOffset;
3847 }
3848 }
Eric Laurentaccc1472013-09-20 09:36:34 -07003849 return NO_ERROR;
3850 }
3851 }
3852 return INVALID_OPERATION;
3853}
Eric Laurent1c333e22014-05-20 10:48:17 -07003854
Eric Laurent054d9d32015-04-24 08:48:48 -07003855status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3856 audio_patch_handle_t *handle)
3857{
Andy Hungf60abce2016-08-26 11:37:54 -07003858 status_t status;
3859 if (property_get_bool("af.patch_park", false /* default_value */)) {
3860 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3861 // or if HAL does not properly lock against access.
3862 AutoPark<FastMixer> park(mFastMixer);
3863 status = PlaybackThread::createAudioPatch_l(patch, handle);
3864 } else {
3865 status = PlaybackThread::createAudioPatch_l(patch, handle);
3866 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003867 return status;
3868}
3869
Eric Laurent1c333e22014-05-20 10:48:17 -07003870status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3871 audio_patch_handle_t *handle)
3872{
3873 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003874
3875 // store new device and send to effects
3876 audio_devices_t type = AUDIO_DEVICE_NONE;
3877 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3878 type |= patch->sinks[i].ext.device.type;
3879 }
3880
François Gaffie0c280aa2018-07-25 10:02:15 +02003881 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07003882#ifdef ADD_BATTERY_DATA
3883 // when changing the audio output device, call addBatteryData to notify
3884 // the change
3885 if (mOutDevice != type) {
3886 uint32_t params = 0;
3887 // check whether speaker is on
3888 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3889 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003890 }
3891
Eric Laurent054d9d32015-04-24 08:48:48 -07003892 audio_devices_t deviceWithoutSpeaker
3893 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3894 // check if any other device (except speaker) is on
3895 if (type & deviceWithoutSpeaker) {
3896 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3897 }
3898
3899 if (params != 0) {
3900 addBatteryData(params);
3901 }
3902 }
3903#endif
3904
3905 for (size_t i = 0; i < mEffectChains.size(); i++) {
3906 mEffectChains[i]->setDevice_l(type);
3907 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003908
3909 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3910 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
François Gaffie0c280aa2018-07-25 10:02:15 +02003911 bool configChanged = (mPrevOutDevice != type) || (mDeviceId != sinkPortId);
Eric Laurent054d9d32015-04-24 08:48:48 -07003912 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003913 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003914
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003915 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003916 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3917 status = hwDevice->createAudioPatch(patch->num_sources,
3918 patch->sources,
3919 patch->num_sinks,
3920 patch->sinks,
3921 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003922 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003923 char *address;
3924 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3925 //FIXME: we only support address on first sink with HAL version < 3.0
3926 address = audio_device_address_to_parameter(
3927 patch->sinks[0].ext.device.type,
3928 patch->sinks[0].ext.device.address);
3929 } else {
3930 address = (char *)calloc(1, 1);
3931 }
3932 AudioParameter param = AudioParameter(String8(address));
3933 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003934 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003935 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003936 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003937 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003938 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003939 mPrevOutDevice = type;
François Gaffie0c280aa2018-07-25 10:02:15 +02003940 mDeviceId = sinkPortId;
Eric Laurente8726fe2015-06-26 09:39:24 -07003941 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3942 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003943 return status;
3944}
3945
Eric Laurent054d9d32015-04-24 08:48:48 -07003946status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3947{
Andy Hungf60abce2016-08-26 11:37:54 -07003948 status_t status;
3949 if (property_get_bool("af.patch_park", false /* default_value */)) {
3950 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3951 // or if HAL does not properly lock against access.
3952 AutoPark<FastMixer> park(mFastMixer);
3953 status = PlaybackThread::releaseAudioPatch_l(handle);
3954 } else {
3955 status = PlaybackThread::releaseAudioPatch_l(handle);
3956 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003957 return status;
3958}
3959
Eric Laurent1c333e22014-05-20 10:48:17 -07003960status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3961{
3962 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003963
3964 mOutDevice = AUDIO_DEVICE_NONE;
3965
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003966 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003967 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3968 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003969 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003970 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003971 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003972 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003973 }
3974 return status;
3975}
3976
Eric Laurent83b88082014-06-20 18:31:16 -07003977void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3978{
3979 Mutex::Autolock _l(mLock);
3980 mTracks.add(track);
3981}
3982
3983void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3984{
3985 Mutex::Autolock _l(mLock);
3986 destroyTrack_l(track);
3987}
3988
Mikhail Naganovdc769682018-05-04 15:34:08 -07003989void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003990{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003991 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003992 config->role = AUDIO_PORT_ROLE_SOURCE;
3993 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3994 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003995 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3996 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3997 config->flags.output = mOutput->flags;
3998 }
Eric Laurent83b88082014-06-20 18:31:16 -07003999}
4000
Eric Laurent81784c32012-11-19 14:55:58 -08004001// ----------------------------------------------------------------------------
4002
4003AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07004004 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
4005 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004006 // mAudioMixer below
4007 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004008 mFastMixerFutex(0),
4009 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004010 // mOutputSink below
4011 // mPipeSink below
4012 // mNormalSink below
4013{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004014 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08004015 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004016 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004017 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004018 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4019 mNormalFrameCount);
4020 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4021
Andy Hungfbfc3952015-01-15 13:33:51 -08004022 if (type == DUPLICATING) {
4023 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4024 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4025 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4026 return;
4027 }
Eric Laurent81784c32012-11-19 14:55:58 -08004028 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004029 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004030 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004031 const NBAIO_Format offers[1] = {Format_from_SR_C(
4032 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004033#if !LOG_NDEBUG
4034 ssize_t index =
4035#else
4036 (void)
4037#endif
4038 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004039 ALOG_ASSERT(index == 0);
4040
4041 // initialize fast mixer depending on configuration
4042 bool initFastMixer;
4043 switch (kUseFastMixer) {
4044 case FastMixer_Never:
4045 initFastMixer = false;
4046 break;
4047 case FastMixer_Always:
4048 initFastMixer = true;
4049 break;
4050 case FastMixer_Static:
4051 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004052 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4053 // where the period is less than an experimentally determined threshold that can be
4054 // scheduled reliably with CFS. However, the BT A2DP HAL is
4055 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4056 initFastMixer = mFrameCount < mNormalFrameCount
4057 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004058 break;
4059 }
Andy Hungfda69402017-02-15 14:33:12 -08004060 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4061 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4062 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004063 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004064 audio_format_t fastMixerFormat;
4065 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4066 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4067 } else {
4068 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4069 }
4070 if (mFormat != fastMixerFormat) {
4071 // change our Sink format to accept our intermediate precision
4072 mFormat = fastMixerFormat;
4073 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004074 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004075 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4076 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4077 }
Eric Laurent81784c32012-11-19 14:55:58 -08004078
4079 // create a MonoPipe to connect our submix to FastMixer
4080 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004081
Andy Hung1258c1a2014-05-23 21:22:17 -07004082 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004083 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004084 format.mFormat = fastMixerFormat;
4085 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4086
Eric Laurent81784c32012-11-19 14:55:58 -08004087 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4088 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4089 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4090 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4091 const NBAIO_Format offers[1] = {format};
4092 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004093#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004094 ssize_t index =
4095#else
4096 (void)
4097#endif
4098 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004099 ALOG_ASSERT(index == 0);
4100 monoPipe->setAvgFrames((mScreenState & 1) ?
4101 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4102 mPipeSink = monoPipe;
4103
Eric Laurent81784c32012-11-19 14:55:58 -08004104 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004105 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004106 FastMixerStateQueue *sq = mFastMixer->sq();
4107#ifdef STATE_QUEUE_DUMP
4108 sq->setObserverDump(&mStateQueueObserverDump);
4109 sq->setMutatorDump(&mStateQueueMutatorDump);
4110#endif
4111 FastMixerState *state = sq->begin();
4112 FastTrack *fastTrack = &state->mFastTracks[0];
4113 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4114 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4115 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004116 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4117 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004118 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004119 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004120 fastTrack->mGeneration++;
4121 state->mFastTracksGen++;
4122 state->mTrackMask = 1;
4123 // fast mixer will use the HAL output sink
4124 state->mOutputSink = mOutputSink.get();
4125 state->mOutputSinkGen++;
4126 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004127 // specify sink channel mask when haptic channel mask present as it can not
4128 // be calculated directly from channel count
4129 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4130 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004131 state->mCommand = FastMixerState::COLD_IDLE;
4132 // already done in constructor initialization list
4133 //mFastMixerFutex = 0;
4134 state->mColdFutexAddr = &mFastMixerFutex;
4135 state->mColdGen++;
4136 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004137 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4138 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004139 sq->end();
4140 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4141
Eric Tan0513b5d2018-09-17 10:32:48 -07004142 NBLog::thread_info_t info;
4143 info.id = mId;
4144 info.type = NBLog::FASTMIXER;
4145 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4146
Eric Laurent81784c32012-11-19 14:55:58 -08004147 // start the fast mixer
4148 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4149 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004150 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004151 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004152
4153#ifdef AUDIO_WATCHDOG
4154 // create and start the watchdog
4155 mAudioWatchdog = new AudioWatchdog();
4156 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4157 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4158 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004159 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004160#endif
Andy Hung8946a282018-04-19 20:04:56 -07004161 } else {
4162#ifdef TEE_SINK
4163 // Only use the MixerThread tee if there is no FastMixer.
4164 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4165 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4166#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004167 }
4168
4169 switch (kUseFastMixer) {
4170 case FastMixer_Never:
4171 case FastMixer_Dynamic:
4172 mNormalSink = mOutputSink;
4173 break;
4174 case FastMixer_Always:
4175 mNormalSink = mPipeSink;
4176 break;
4177 case FastMixer_Static:
4178 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4179 break;
4180 }
4181}
4182
4183AudioFlinger::MixerThread::~MixerThread()
4184{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004185 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004186 FastMixerStateQueue *sq = mFastMixer->sq();
4187 FastMixerState *state = sq->begin();
4188 if (state->mCommand == FastMixerState::COLD_IDLE) {
4189 int32_t old = android_atomic_inc(&mFastMixerFutex);
4190 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004191 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004192 }
4193 }
4194 state->mCommand = FastMixerState::EXIT;
4195 sq->end();
4196 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4197 mFastMixer->join();
4198 // Though the fast mixer thread has exited, it's state queue is still valid.
4199 // We'll use that extract the final state which contains one remaining fast track
4200 // corresponding to our sub-mix.
4201 state = sq->begin();
4202 ALOG_ASSERT(state->mTrackMask == 1);
4203 FastTrack *fastTrack = &state->mFastTracks[0];
4204 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4205 delete fastTrack->mBufferProvider;
4206 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004207 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004208#ifdef AUDIO_WATCHDOG
4209 if (mAudioWatchdog != 0) {
4210 mAudioWatchdog->requestExit();
4211 mAudioWatchdog->requestExitAndWait();
4212 mAudioWatchdog.clear();
4213 }
4214#endif
4215 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004216 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004217 delete mAudioMixer;
4218}
4219
4220
4221uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4222{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004223 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004224 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4225 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4226 }
4227 return latency;
4228}
4229
Eric Laurentbfb1b832013-01-07 09:53:42 -08004230ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004231{
4232 // FIXME we should only do one push per cycle; confirm this is true
4233 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004234 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004235 FastMixerStateQueue *sq = mFastMixer->sq();
4236 FastMixerState *state = sq->begin();
4237 if (state->mCommand != FastMixerState::MIX_WRITE &&
4238 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4239 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004240
4241 // FIXME workaround for first HAL write being CPU bound on some devices
4242 ATRACE_BEGIN("write");
4243 mOutput->write((char *)mSinkBuffer, 0);
4244 ATRACE_END();
4245
Eric Laurent81784c32012-11-19 14:55:58 -08004246 int32_t old = android_atomic_inc(&mFastMixerFutex);
4247 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004248 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004249 }
4250#ifdef AUDIO_WATCHDOG
4251 if (mAudioWatchdog != 0) {
4252 mAudioWatchdog->resume();
4253 }
4254#endif
4255 }
4256 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004257#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004258 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004259 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004260#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004261 sq->end();
4262 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4263 if (kUseFastMixer == FastMixer_Dynamic) {
4264 mNormalSink = mPipeSink;
4265 }
4266 } else {
4267 sq->end(false /*didModify*/);
4268 }
4269 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004270 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004271}
4272
4273void AudioFlinger::MixerThread::threadLoop_standby()
4274{
4275 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004276 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004277 FastMixerStateQueue *sq = mFastMixer->sq();
4278 FastMixerState *state = sq->begin();
4279 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004280 // Report any frames trapped in the Monopipe
4281 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4282 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4283 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4284 "monoPipeWritten:%lld monoPipeLeft:%lld",
4285 (long long)mFramesWritten, (long long)mSuspendedFrames,
4286 (long long)mPipeSink->framesWritten(), pipeFrames);
4287 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4288
Eric Laurent81784c32012-11-19 14:55:58 -08004289 state->mCommand = FastMixerState::COLD_IDLE;
4290 state->mColdFutexAddr = &mFastMixerFutex;
4291 state->mColdGen++;
4292 mFastMixerFutex = 0;
4293 sq->end();
4294 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4295 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4296 if (kUseFastMixer == FastMixer_Dynamic) {
4297 mNormalSink = mOutputSink;
4298 }
4299#ifdef AUDIO_WATCHDOG
4300 if (mAudioWatchdog != 0) {
4301 mAudioWatchdog->pause();
4302 }
4303#endif
4304 } else {
4305 sq->end(false /*didModify*/);
4306 }
4307 }
4308 PlaybackThread::threadLoop_standby();
4309}
4310
Eric Laurentbfb1b832013-01-07 09:53:42 -08004311bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4312{
4313 return false;
4314}
4315
4316bool AudioFlinger::PlaybackThread::shouldStandby_l()
4317{
4318 return !mStandby;
4319}
4320
4321bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4322{
4323 Mutex::Autolock _l(mLock);
4324 return waitingAsyncCallback_l();
4325}
4326
Eric Laurent81784c32012-11-19 14:55:58 -08004327// shared by MIXER and DIRECT, overridden by DUPLICATING
4328void AudioFlinger::PlaybackThread::threadLoop_standby()
4329{
4330 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004331 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004332 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004333 // discard any pending drain or write ack by incrementing sequence
4334 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4335 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004336 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004337 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4338 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004339 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004340 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004341}
4342
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004343void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4344{
4345 ALOGV("signal playback thread");
4346 broadcast_l();
4347}
4348
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004349void AudioFlinger::PlaybackThread::onAsyncError()
4350{
4351 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4352 invalidateTracks((audio_stream_type_t)i);
4353 }
4354}
4355
Eric Laurent81784c32012-11-19 14:55:58 -08004356void AudioFlinger::MixerThread::threadLoop_mix()
4357{
Eric Laurent81784c32012-11-19 14:55:58 -08004358 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004359 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004360 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004361 // increase sleep time progressively when application underrun condition clears.
4362 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4363 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4364 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004365 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004366 sleepTimeShift--;
4367 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004368 mSleepTimeUs = 0;
4369 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004370 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004371
Eric Laurent81784c32012-11-19 14:55:58 -08004372}
4373
4374void AudioFlinger::MixerThread::threadLoop_sleepTime()
4375{
4376 // If no tracks are ready, sleep once for the duration of an output
4377 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004378 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004379 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004380 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4381 // Using the Monopipe availableToWrite, we estimate the
4382 // sleep time to retry for more data (before we underrun).
4383 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4384 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4385 const size_t pipeFrames = monoPipe->maxFrames();
4386 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4387 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4388 const size_t framesDelay = std::min(
4389 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4390 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4391 pipeFrames, framesLeft, framesDelay);
4392 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4393 } else {
4394 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4395 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4396 mSleepTimeUs = kMinThreadSleepTimeUs;
4397 }
4398 // reduce sleep time in case of consecutive application underruns to avoid
4399 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4400 // duration we would end up writing less data than needed by the audio HAL if
4401 // the condition persists.
4402 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4403 sleepTimeShift++;
4404 }
Eric Laurent81784c32012-11-19 14:55:58 -08004405 }
4406 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004407 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004408 }
4409 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004410 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4411 // before effects processing or output.
4412 if (mMixerBufferValid) {
4413 memset(mMixerBuffer, 0, mMixerBufferSize);
4414 } else {
4415 memset(mSinkBuffer, 0, mSinkBufferSize);
4416 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004417 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004418 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4419 "anticipated start");
4420 }
4421 // TODO add standby time extension fct of effect tail
4422}
4423
4424// prepareTracks_l() must be called with ThreadBase::mLock held
4425AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4426 Vector< sp<Track> > *tracksToRemove)
4427{
Andy Hungc0691382018-09-12 18:01:57 -07004428 // clean up deleted track ids in AudioMixer before allocating new tracks
4429 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4430 // for each trackId, destroy it in the AudioMixer
4431 if (mAudioMixer->exists(trackId)) {
4432 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004433 }
4434 });
Andy Hungc0691382018-09-12 18:01:57 -07004435 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004436
4437 mixer_state mixerStatus = MIXER_IDLE;
4438 // find out which tracks need to be processed
4439 size_t count = mActiveTracks.size();
4440 size_t mixedTracks = 0;
4441 size_t tracksWithEffect = 0;
4442 // counts only _active_ fast tracks
4443 size_t fastTracks = 0;
4444 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4445
4446 float masterVolume = mMasterVolume;
4447 bool masterMute = mMasterMute;
4448
4449 if (masterMute) {
4450 masterVolume = 0;
4451 }
4452 // Delegate master volume control to effect in output mix effect chain if needed
4453 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4454 if (chain != 0) {
4455 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4456 chain->setVolume_l(&v, &v);
4457 masterVolume = (float)((v + (1 << 23)) >> 24);
4458 chain.clear();
4459 }
4460
4461 // prepare a new state to push
4462 FastMixerStateQueue *sq = NULL;
4463 FastMixerState *state = NULL;
4464 bool didModify = false;
4465 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004466 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004467 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004468 sq = mFastMixer->sq();
4469 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004470 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004471 }
4472
Andy Hung69aed5f2014-02-25 17:24:40 -08004473 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004474 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004475
Andy Hungbd3b2b02018-05-21 10:53:11 -07004476 // DeferredOperations handles statistics after setting mixerStatus.
4477 class DeferredOperations {
4478 public:
4479 DeferredOperations(mixer_state *mixerStatus)
4480 : mMixerStatus(mixerStatus) { }
4481
4482 // when leaving scope, tally frames properly.
4483 ~DeferredOperations() {
4484 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4485 // because that is when the underrun occurs.
4486 // We do not distinguish between FastTracks and NormalTracks here.
4487 if (*mMixerStatus == MIXER_TRACKS_READY) {
4488 for (const auto &underrun : mUnderrunFrames) {
4489 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4490 underrun.second);
4491 }
4492 }
4493 }
4494
4495 // tallyUnderrunFrames() is called to update the track counters
4496 // with the number of underrun frames for a particular mixer period.
4497 // We defer tallying until we know the final mixer status.
4498 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4499 mUnderrunFrames.emplace_back(track, underrunFrames);
4500 }
4501
4502 private:
4503 const mixer_state * const mMixerStatus;
4504 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4505 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4506
jiabin245cdd92018-12-07 17:55:15 -08004507 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004508 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004509 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004510
4511 // this const just means the local variable doesn't change
4512 Track* const track = t.get();
4513
4514 // process fast tracks
4515 if (track->isFastTrack()) {
jiabin245cdd92018-12-07 17:55:15 -08004516 if (track->getHapticPlaybackEnabled()) {
4517 noFastHapticTrack = false;
4518 }
Eric Laurent81784c32012-11-19 14:55:58 -08004519
4520 // It's theoretically possible (though unlikely) for a fast track to be created
4521 // and then removed within the same normal mix cycle. This is not a problem, as
4522 // the track never becomes active so it's fast mixer slot is never touched.
4523 // The converse, of removing an (active) track and then creating a new track
4524 // at the identical fast mixer slot within the same normal mix cycle,
4525 // is impossible because the slot isn't marked available until the end of each cycle.
4526 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004527 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004528 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4529 FastTrack *fastTrack = &state->mFastTracks[j];
4530
4531 // Determine whether the track is currently in underrun condition,
4532 // and whether it had a recent underrun.
4533 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4534 FastTrackUnderruns underruns = ftDump->mUnderruns;
4535 uint32_t recentFull = (underruns.mBitFields.mFull -
4536 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4537 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4538 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4539 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4540 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4541 uint32_t recentUnderruns = recentPartial + recentEmpty;
4542 track->mObservedUnderruns = underruns;
4543 // don't count underruns that occur while stopping or pausing
4544 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004545 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004546 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4547 recentUnderruns > 0) {
4548 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004549 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004550 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004551 // Immediately account for FastTrack underruns.
4552 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004553
4554 // This is similar to the state machine for normal tracks,
4555 // with a few modifications for fast tracks.
4556 bool isActive = true;
4557 switch (track->mState) {
4558 case TrackBase::STOPPING_1:
4559 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004560 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004561 track->mState = TrackBase::STOPPING_2;
4562 }
4563 break;
4564 case TrackBase::PAUSING:
4565 // ramp down is not yet implemented
4566 track->setPaused();
4567 break;
4568 case TrackBase::RESUMING:
4569 // ramp up is not yet implemented
4570 track->mState = TrackBase::ACTIVE;
4571 break;
4572 case TrackBase::ACTIVE:
4573 if (recentFull > 0 || recentPartial > 0) {
4574 // track has provided at least some frames recently: reset retry count
4575 track->mRetryCount = kMaxTrackRetries;
4576 }
4577 if (recentUnderruns == 0) {
4578 // no recent underruns: stay active
4579 break;
4580 }
4581 // there has recently been an underrun of some kind
4582 if (track->sharedBuffer() == 0) {
4583 // were any of the recent underruns "empty" (no frames available)?
4584 if (recentEmpty == 0) {
4585 // no, then ignore the partial underruns as they are allowed indefinitely
4586 break;
4587 }
4588 // there has recently been an "empty" underrun: decrement the retry counter
4589 if (--(track->mRetryCount) > 0) {
4590 break;
4591 }
4592 // indicate to client process that the track was disabled because of underrun;
4593 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004594 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004595 // remove from active list, but state remains ACTIVE [confusing but true]
4596 isActive = false;
4597 break;
4598 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004599 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004600 case TrackBase::STOPPING_2:
4601 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004602 case TrackBase::STOPPED:
4603 case TrackBase::FLUSHED: // flush() while active
4604 // Check for presentation complete if track is inactive
4605 // We have consumed all the buffers of this track.
4606 // This would be incomplete if we auto-paused on underrun
4607 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004608 uint32_t latency = 0;
4609 status_t result = mOutput->stream->getLatency(&latency);
4610 ALOGE_IF(result != OK,
4611 "Error when retrieving output stream latency: %d", result);
4612 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004613 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004614 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4615 // track stays in active list until presentation is complete
4616 break;
4617 }
4618 }
4619 if (track->isStopping_2()) {
4620 track->mState = TrackBase::STOPPED;
4621 }
4622 if (track->isStopped()) {
4623 // Can't reset directly, as fast mixer is still polling this track
4624 // track->reset();
4625 // So instead mark this track as needing to be reset after push with ack
4626 resetMask |= 1 << i;
4627 }
4628 isActive = false;
4629 break;
4630 case TrackBase::IDLE:
4631 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004632 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004633 }
4634
4635 if (isActive) {
4636 // was it previously inactive?
4637 if (!(state->mTrackMask & (1 << j))) {
4638 ExtendedAudioBufferProvider *eabp = track;
4639 VolumeProvider *vp = track;
4640 fastTrack->mBufferProvider = eabp;
4641 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004642 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004643 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08004644 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08004645 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08004646 fastTrack->mGeneration++;
4647 state->mTrackMask |= 1 << j;
4648 didModify = true;
4649 // no acknowledgement required for newly active tracks
4650 }
Kevin Rocard12381092018-04-11 09:19:59 -07004651 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004652 // cache the combined master volume and stream type volume for fast mixer; this
4653 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004654 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004655 proxy->framesReleased()).first;
4656 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004657 * mStreamTypes[track->streamType()].volume
4658 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004659 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004660 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4661 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4662 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4663 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004664 ++fastTracks;
4665 } else {
4666 // was it previously active?
4667 if (state->mTrackMask & (1 << j)) {
4668 fastTrack->mBufferProvider = NULL;
4669 fastTrack->mGeneration++;
4670 state->mTrackMask &= ~(1 << j);
4671 didModify = true;
4672 // If any fast tracks were removed, we must wait for acknowledgement
4673 // because we're about to decrement the last sp<> on those tracks.
4674 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4675 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004676 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4677 // AudioTrack may start (which may not be with a start() but with a write()
4678 // after underrun) and immediately paused or released. In that case the
4679 // FastTrack state hasn't had time to update.
4680 // TODO Remove the ALOGW when this theory is confirmed.
4681 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004682 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4683 j, track->mState, state->mTrackMask, recentUnderruns,
4684 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004685 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004686 }
4687 tracksToRemove->add(track);
4688 // Avoids a misleading display in dumpsys
4689 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4690 }
jiabin245cdd92018-12-07 17:55:15 -08004691 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
4692 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
4693 didModify = true;
4694 }
Eric Laurent81784c32012-11-19 14:55:58 -08004695 continue;
4696 }
4697
4698 { // local variable scope to avoid goto warning
4699
4700 audio_track_cblk_t* cblk = track->cblk();
4701
4702 // The first time a track is added we wait
4703 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004704 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004705
4706 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004707 // use the trackId as the AudioMixer name.
4708 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004709 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004710 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004711 track->mChannelMask,
4712 track->mFormat,
4713 track->mSessionId);
4714 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004715 ALOGW("%s(): AudioMixer cannot create track(%d)"
4716 " mask %#x, format %#x, sessionId %d",
4717 __func__, trackId,
4718 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004719 tracksToRemove->add(track);
4720 track->invalidate(); // consider it dead.
4721 continue;
4722 }
4723 }
4724
Eric Laurent81784c32012-11-19 14:55:58 -08004725 // make sure that we have enough frames to mix one full buffer.
4726 // enforce this condition only once to enable draining the buffer in case the client
4727 // app does not call stop() and relies on underrun to stop:
4728 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4729 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004730 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004731 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004732 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004733
4734 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004735 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004736 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4737 // add frames already consumed but not yet released by the resampler
4738 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004739 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004740
Eric Laurent81784c32012-11-19 14:55:58 -08004741 uint32_t minFrames = 1;
4742 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4743 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004744 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004745 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004746
4747 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004748 if (ATRACE_ENABLED()) {
4749 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004750 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004751 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004752 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004753 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004754 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004755 !track->isPaused() && !track->isTerminated())
4756 {
Andy Hungc0691382018-09-12 18:01:57 -07004757 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004758
4759 mixedTracks++;
4760
Andy Hung69aed5f2014-02-25 17:24:40 -08004761 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4762 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004763 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004764 if (track->mainBuffer() != mSinkBuffer &&
4765 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004766 if (mEffectBufferEnabled) {
4767 mEffectBufferValid = true; // Later can set directly.
4768 }
Eric Laurent81784c32012-11-19 14:55:58 -08004769 chain = getEffectChain_l(track->sessionId());
4770 // Delegate volume control to effect in track effect chain if needed
4771 if (chain != 0) {
4772 tracksWithEffect++;
4773 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004774 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004775 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004776 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004777 }
4778 }
4779
4780
4781 int param = AudioMixer::VOLUME;
4782 if (track->mFillingUpStatus == Track::FS_FILLED) {
4783 // no ramp for the first volume setting
4784 track->mFillingUpStatus = Track::FS_ACTIVE;
4785 if (track->mState == TrackBase::RESUMING) {
4786 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08004787 // If a new track is paused immediately after start, do not ramp on resume.
4788 if (cblk->mServer != 0) {
4789 param = AudioMixer::RAMP_VOLUME;
4790 }
Eric Laurent81784c32012-11-19 14:55:58 -08004791 }
Andy Hungc0691382018-09-12 18:01:57 -07004792 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004793 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004794 // FIXME should not make a decision based on mServer
4795 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004796 // If the track is stopped before the first frame was mixed,
4797 // do not apply ramp
4798 param = AudioMixer::RAMP_VOLUME;
4799 }
4800
4801 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004802 uint32_t vl, vr; // in U8.24 integer format
4803 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004804 // read original volumes with volume control
4805 float typeVolume = mStreamTypes[track->streamType()].volume;
4806 float v = masterVolume * typeVolume;
4807
Glenn Kastene4756fe2012-11-29 13:38:14 -08004808 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004809 vl = vr = 0;
4810 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004811 if (track->isPausing()) {
4812 track->setPaused();
4813 }
4814 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004815 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004816 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004817 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4818 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004819 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004820 if (vlf > GAIN_FLOAT_UNITY) {
4821 ALOGV("Track left volume out of range: %.3g", vlf);
4822 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004823 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004824 if (vrf > GAIN_FLOAT_UNITY) {
4825 ALOGV("Track right volume out of range: %.3g", vrf);
4826 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004827 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004828 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004829 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004830 // now apply the master volume and stream type volume and shaper volume
4831 vlf *= v * vh;
4832 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004833 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004834 // then derive vl and vr as U8.24 versions for the effect chain
4835 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4836 vl = (uint32_t) (scaleto8_24 * vlf);
4837 vr = (uint32_t) (scaleto8_24 * vrf);
4838 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004839 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004840 // send level comes from shared memory and so may be corrupt
4841 if (sendLevel > MAX_GAIN_INT) {
4842 ALOGV("Track send level out of range: %04X", sendLevel);
4843 sendLevel = MAX_GAIN_INT;
4844 }
Andy Hung6be49402014-05-30 10:42:03 -07004845 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4846 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004847 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004848
Kevin Rocard12381092018-04-11 09:19:59 -07004849 track->setFinalVolume((vrf + vlf) / 2.f);
4850
Eric Laurent81784c32012-11-19 14:55:58 -08004851 // Delegate volume control to effect in track effect chain if needed
4852 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4853 // Do not ramp volume if volume is controlled by effect
4854 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004855 // Update remaining floating point volume levels
4856 vlf = (float)vl / (1 << 24);
4857 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004858 track->mHasVolumeController = true;
4859 } else {
4860 // force no volume ramp when volume controller was just disabled or removed
4861 // from effect chain to avoid volume spike
4862 if (track->mHasVolumeController) {
4863 param = AudioMixer::VOLUME;
4864 }
4865 track->mHasVolumeController = false;
4866 }
4867
Eric Laurent7c29ec92017-09-20 17:54:22 -07004868 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4869 // still applied by the mixer.
4870 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4871 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4872 if (v != mLeftVolFloat) {
4873 status_t result = mOutput->stream->setVolume(v, v);
4874 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4875 if (result == OK) {
4876 mLeftVolFloat = v;
4877 }
4878 }
4879 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4880 // remove stream volume contribution from software volume.
4881 if (v != 0.0f && mLeftVolFloat == v) {
4882 vlf = min(1.0f, vlf / v);
4883 vrf = min(1.0f, vrf / v);
4884 vaf = min(1.0f, vaf / v);
4885 }
4886 }
Eric Laurent81784c32012-11-19 14:55:58 -08004887 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07004888 mAudioMixer->setBufferProvider(trackId, track);
4889 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004890
Andy Hungc0691382018-09-12 18:01:57 -07004891 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
4892 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
4893 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004894 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004895 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004896 AudioMixer::TRACK,
4897 AudioMixer::FORMAT, (void *)track->format());
4898 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004899 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004900 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004901 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004902 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004903 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07004904 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08004905 AudioMixer::MIXER_CHANNEL_MASK,
4906 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08004907 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004908 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004909 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004910 if (reqSampleRate == 0) {
4911 reqSampleRate = mSampleRate;
4912 } else if (reqSampleRate > maxSampleRate) {
4913 reqSampleRate = maxSampleRate;
4914 }
Eric Laurent81784c32012-11-19 14:55:58 -08004915 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004916 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004917 AudioMixer::RESAMPLE,
4918 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004919 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004920
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004921 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004922 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004923 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07004924 AudioMixer::TIMESTRETCH,
4925 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004926 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004927
Andy Hung69aed5f2014-02-25 17:24:40 -08004928 /*
4929 * Select the appropriate output buffer for the track.
4930 *
Andy Hung98ef9782014-03-04 14:46:50 -08004931 * Tracks with effects go into their own effects chain buffer
4932 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004933 *
4934 * Other tracks can use mMixerBuffer for higher precision
4935 * channel accumulation. If this buffer is enabled
4936 * (mMixerBufferEnabled true), then selected tracks will accumulate
4937 * into it.
4938 *
4939 */
4940 if (mMixerBufferEnabled
4941 && (track->mainBuffer() == mSinkBuffer
4942 || track->mainBuffer() == mMixerBuffer)) {
4943 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004944 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004945 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004946 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004947 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004948 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004949 AudioMixer::TRACK,
4950 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4951 // TODO: override track->mainBuffer()?
4952 mMixerBufferValid = true;
4953 } else {
4954 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004955 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004956 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004957 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004958 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004959 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004960 AudioMixer::TRACK,
4961 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4962 }
Eric Laurent81784c32012-11-19 14:55:58 -08004963 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004964 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004965 AudioMixer::TRACK,
4966 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08004967 mAudioMixer->setParameter(
4968 trackId,
4969 AudioMixer::TRACK,
4970 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08004971 mAudioMixer->setParameter(
4972 trackId,
4973 AudioMixer::TRACK,
4974 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08004975
4976 // reset retry count
4977 track->mRetryCount = kMaxTrackRetries;
4978
4979 // If one track is ready, set the mixer ready if:
4980 // - the mixer was not ready during previous round OR
4981 // - no other track is not ready
4982 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4983 mixerStatus != MIXER_TRACKS_ENABLED) {
4984 mixerStatus = MIXER_TRACKS_READY;
4985 }
4986 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004987 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004988 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07004989 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
4990 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004991 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004992 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004993 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004994
Eric Laurent81784c32012-11-19 14:55:58 -08004995 // clear effect chain input buffer if an active track underruns to avoid sending
4996 // previous audio buffer again to effects
4997 chain = getEffectChain_l(track->sessionId());
4998 if (chain != 0) {
4999 chain->clearInputBuffer();
5000 }
5001
Andy Hungc0691382018-09-12 18:01:57 -07005002 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005003 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5004 track->isStopped() || track->isPaused()) {
5005 // We have consumed all the buffers of this track.
5006 // Remove it from the list of active tracks.
5007 // TODO: use actual buffer filling status instead of latency when available from
5008 // audio HAL
5009 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005010 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005011 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5012 if (track->isStopped()) {
5013 track->reset();
5014 }
5015 tracksToRemove->add(track);
5016 }
5017 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005018 // No buffers for this track. Give it a few chances to
5019 // fill a buffer, then remove it from active list.
5020 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005021 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5022 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005023 tracksToRemove->add(track);
5024 // indicate to client process that the track was disabled because of underrun;
5025 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005026 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005027 // If one track is not ready, mark the mixer also not ready if:
5028 // - the mixer was ready during previous round OR
5029 // - no other track is ready
5030 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5031 mixerStatus != MIXER_TRACKS_READY) {
5032 mixerStatus = MIXER_TRACKS_ENABLED;
5033 }
5034 }
Andy Hungc0691382018-09-12 18:01:57 -07005035 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005036 }
5037
5038 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005039
5040 }
5041
jiabin245cdd92018-12-07 17:55:15 -08005042 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5043 // When there is no fast track playing haptic and FastMixer exists,
5044 // enabling the first FastTrack, which provides mixed data from normal
5045 // tracks, to play haptic data.
5046 FastTrack *fastTrack = &state->mFastTracks[0];
5047 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5048 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5049 didModify = true;
5050 }
5051 }
5052
Eric Laurent81784c32012-11-19 14:55:58 -08005053 // Push the new FastMixer state if necessary
5054 bool pauseAudioWatchdog = false;
5055 if (didModify) {
5056 state->mFastTracksGen++;
5057 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5058 if (kUseFastMixer == FastMixer_Dynamic &&
5059 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5060 state->mCommand = FastMixerState::COLD_IDLE;
5061 state->mColdFutexAddr = &mFastMixerFutex;
5062 state->mColdGen++;
5063 mFastMixerFutex = 0;
5064 if (kUseFastMixer == FastMixer_Dynamic) {
5065 mNormalSink = mOutputSink;
5066 }
5067 // If we go into cold idle, need to wait for acknowledgement
5068 // so that fast mixer stops doing I/O.
5069 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5070 pauseAudioWatchdog = true;
5071 }
Eric Laurent81784c32012-11-19 14:55:58 -08005072 }
5073 if (sq != NULL) {
5074 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005075 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5076 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5077 // when bringing the output sink into standby.)
5078 //
5079 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5080 //
5081 // This occurs with BT suspend when we idle the FastMixer with
5082 // active tracks, which may be added or removed.
5083 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005084 }
5085#ifdef AUDIO_WATCHDOG
5086 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5087 mAudioWatchdog->pause();
5088 }
5089#endif
5090
5091 // Now perform the deferred reset on fast tracks that have stopped
5092 while (resetMask != 0) {
5093 size_t i = __builtin_ctz(resetMask);
5094 ALOG_ASSERT(i < count);
5095 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005096 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005097 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5098 track->reset();
5099 }
5100
Andy Hung80d03d22018-04-10 10:32:11 -07005101 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5102 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5103 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5104 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5105 // See also the implementation of destroyTrack_l().
5106 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005107 const int trackId = track->id();
5108 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5109 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005110 }
5111 }
5112
Eric Laurent81784c32012-11-19 14:55:58 -08005113 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005114 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005115
Eric Laurent97d547d2014-09-02 14:45:53 -07005116 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5117 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005118 }
5119
5120 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005121 // as long as there are effects we should clear the effects buffer, to avoid
5122 // passing a non-clean buffer to the effect chain
5123 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005124 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005125 // sink or mix buffer must be cleared if all tracks are connected to an
5126 // effect chain as in this case the mixer will not write to the sink or mix buffer
5127 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005128 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5129 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005130 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005131 if (mMixerBufferValid) {
5132 memset(mMixerBuffer, 0, mMixerBufferSize);
5133 // TODO: In testing, mSinkBuffer below need not be cleared because
5134 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5135 // after mixing.
5136 //
5137 // To enforce this guarantee:
5138 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5139 // (mixedTracks == 0 && fastTracks > 0))
5140 // must imply MIXER_TRACKS_READY.
5141 // Later, we may clear buffers regardless, and skip much of this logic.
5142 }
Andy Hung98ef9782014-03-04 14:46:50 -08005143 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005144 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005145 }
5146
5147 // if any fast tracks, then status is ready
5148 mMixerStatusIgnoringFastTracks = mixerStatus;
5149 if (fastTracks > 0) {
5150 mixerStatus = MIXER_TRACKS_READY;
5151 }
5152 return mixerStatus;
5153}
5154
Eric Laurentad7dd962016-09-22 12:38:37 -07005155// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005156uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005157{
5158 uint32_t trackCount = 0;
5159 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005160 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005161 trackCount++;
5162 }
5163 }
5164 return trackCount;
5165}
5166
Andy Hung1bc088a2018-02-09 15:57:31 -08005167// isTrackAllowed_l() must be called with ThreadBase::mLock held
5168bool AudioFlinger::MixerThread::isTrackAllowed_l(
5169 audio_channel_mask_t channelMask, audio_format_t format,
5170 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005171{
Andy Hung1bc088a2018-02-09 15:57:31 -08005172 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5173 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005174 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005175 // Check validity as we don't call AudioMixer::create() here.
5176 if (!AudioMixer::isValidFormat(format)) {
5177 ALOGW("%s: invalid format: %#x", __func__, format);
5178 return false;
5179 }
5180 if (!AudioMixer::isValidChannelMask(channelMask)) {
5181 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5182 return false;
5183 }
5184 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005185}
5186
Eric Laurent10351942014-05-08 18:49:52 -07005187// checkForNewParameter_l() must be called with ThreadBase::mLock held
5188bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5189 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005190{
Eric Laurent81784c32012-11-19 14:55:58 -08005191 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005192 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005193
Eric Laurent10351942014-05-08 18:49:52 -07005194 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005195
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005196 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005197
Eric Laurent10351942014-05-08 18:49:52 -07005198 AudioParameter param = AudioParameter(keyValuePair);
5199 int value;
5200 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5201 reconfig = true;
5202 }
5203 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005204 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005205 status = BAD_VALUE;
5206 } else {
5207 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005208 reconfig = true;
5209 }
Eric Laurent10351942014-05-08 18:49:52 -07005210 }
5211 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005212 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005213 status = BAD_VALUE;
5214 } else {
5215 // no need to save value, since it's constant
5216 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005217 }
Eric Laurent10351942014-05-08 18:49:52 -07005218 }
5219 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5220 // do not accept frame count changes if tracks are open as the track buffer
5221 // size depends on frame count and correct behavior would not be guaranteed
5222 // if frame count is changed after track creation
5223 if (!mTracks.isEmpty()) {
5224 status = INVALID_OPERATION;
5225 } else {
5226 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005227 }
Eric Laurent10351942014-05-08 18:49:52 -07005228 }
5229 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005230#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005231 // when changing the audio output device, call addBatteryData to notify
5232 // the change
5233 if (mOutDevice != value) {
5234 uint32_t params = 0;
5235 // check whether speaker is on
5236 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5237 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005238 }
Eric Laurent10351942014-05-08 18:49:52 -07005239
5240 audio_devices_t deviceWithoutSpeaker
5241 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5242 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005243 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005244 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5245 }
5246
5247 if (params != 0) {
5248 addBatteryData(params);
5249 }
5250 }
Eric Laurent81784c32012-11-19 14:55:58 -08005251#endif
5252
Eric Laurent10351942014-05-08 18:49:52 -07005253 // forward device change to effects that have requested to be
5254 // aware of attached audio device.
5255 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005256 a2dpDeviceChanged =
5257 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005258 mOutDevice = value;
5259 for (size_t i = 0; i < mEffectChains.size(); i++) {
5260 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005261 }
5262 }
Eric Laurent10351942014-05-08 18:49:52 -07005263 }
Eric Laurent81784c32012-11-19 14:55:58 -08005264
Eric Laurent10351942014-05-08 18:49:52 -07005265 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005266 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005267 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005268 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005269 mStandby = true;
5270 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005271 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005272 }
Eric Laurent10351942014-05-08 18:49:52 -07005273 if (status == NO_ERROR && reconfig) {
5274 readOutputParameters_l();
5275 delete mAudioMixer;
5276 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005277 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005278 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005279 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005280 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005281 track->mChannelMask,
5282 track->mFormat,
5283 track->mSessionId);
5284 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005285 "%s(): AudioMixer cannot create track(%d)"
5286 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005287 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005288 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005289 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005290 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005291 }
Eric Laurent81784c32012-11-19 14:55:58 -08005292 }
5293
Eric Laurent42537be2016-01-08 17:16:42 -08005294 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005295}
5296
5297
5298void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5299{
Eric Laurent81784c32012-11-19 14:55:58 -08005300 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005301 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005302 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005303 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005304 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5305 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5306 : mBalance.toString()).c_str());
Andy Hungf6ab58d2018-05-25 12:50:39 -07005307 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005308 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005309 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005310 } else {
5311 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005312 }
Eric Laurent81784c32012-11-19 14:55:58 -08005313
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005314 if (hasFastMixer()) {
5315 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5316
5317 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5318 // while we are dumping it. It may be inconsistent, but it won't mutate!
5319 // This is a large object so we place it on the heap.
5320 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005321 const std::unique_ptr<FastMixerDumpState> copy =
5322 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005323 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005324
5325#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005326 // Similar for state queue
5327 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5328 observerCopy.dump(fd);
5329 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5330 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005331#endif
5332
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005333#ifdef AUDIO_WATCHDOG
5334 if (mAudioWatchdog != 0) {
5335 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5336 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5337 wdCopy.dump(fd);
5338 }
5339#endif
5340
5341 } else {
5342 dprintf(fd, " No FastMixer\n");
5343 }
Eric Laurent81784c32012-11-19 14:55:58 -08005344}
5345
5346uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5347{
5348 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5349}
5350
5351uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5352{
5353 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5354}
5355
5356void AudioFlinger::MixerThread::cacheParameters_l()
5357{
5358 PlaybackThread::cacheParameters_l();
5359
5360 // FIXME: Relaxed timing because of a certain device that can't meet latency
5361 // Should be reduced to 2x after the vendor fixes the driver issue
5362 // increase threshold again due to low power audio mode. The way this warning
5363 // threshold is calculated and its usefulness should be reconsidered anyway.
5364 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5365}
5366
5367// ----------------------------------------------------------------------------
5368
5369AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Andy Hung48f59ed2019-01-28 15:06:59 -08005370 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005371 ThreadBase::type_t type, bool systemReady)
5372 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005373{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005374 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005375}
5376
Eric Laurent81784c32012-11-19 14:55:58 -08005377AudioFlinger::DirectOutputThread::~DirectOutputThread()
5378{
5379}
5380
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005381void AudioFlinger::DirectOutputThread::dumpInternals(int fd, const Vector<String16>& args)
5382{
5383 PlaybackThread::dumpInternals(fd, args);
5384 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5385 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5386}
5387
5388void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5389{
5390 Mutex::Autolock _l(mLock);
5391 if (mMasterBalance != balance) {
5392 mMasterBalance.store(balance);
5393 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5394 broadcast_l();
5395 }
5396}
5397
Eric Laurent5850c4c2016-11-10 13:04:31 -08005398void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005399{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005400 float left, right;
5401
5402 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5403 left = right = 0;
5404 } else {
5405 float typeVolume = mStreamTypes[track->streamType()].volume;
5406 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005407 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005408
Andy Hung10cbff12017-02-21 17:30:14 -08005409 // Get volumeshaper scaling
5410 std::pair<float /* volume */, bool /* active */>
5411 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005412 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005413 v *= vh.first;
5414 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005415
Glenn Kastenc56f3422014-03-21 17:53:17 -07005416 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5417 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5418 if (left > GAIN_FLOAT_UNITY) {
5419 left = GAIN_FLOAT_UNITY;
5420 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005421 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005422 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5423 if (right > GAIN_FLOAT_UNITY) {
5424 right = GAIN_FLOAT_UNITY;
5425 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005426 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005427 }
5428
5429 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005430 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005431 if (left != mLeftVolFloat || right != mRightVolFloat) {
5432 mLeftVolFloat = left;
5433 mRightVolFloat = right;
5434
Eric Laurentbfb1b832013-01-07 09:53:42 -08005435 // Delegate volume control to effect in track effect chain if needed
5436 // only one effect chain can be present on DirectOutputThread, so if
5437 // there is one, the track is connected to it
5438 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005439 // if effect chain exists, volume is handled by it.
5440 // Convert volumes from float to 8.24
5441 uint32_t vl = (uint32_t)(left * (1 << 24));
5442 uint32_t vr = (uint32_t)(right * (1 << 24));
5443 // Direct/Offload effect chains set output volume in setVolume_l().
5444 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5445 } else {
5446 // otherwise we directly set the volume.
5447 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005448 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005449 }
5450 }
5451}
5452
Phil Burk43b4dcc2015-06-09 16:53:44 -07005453void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5454{
5455 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005456 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005457
Eric Laurent0f0631e2015-07-06 18:01:25 -07005458 if (previousTrack != 0 && latestTrack != 0) {
5459 if (mType == DIRECT) {
5460 if (previousTrack.get() != latestTrack.get()) {
5461 mFlushPending = true;
5462 }
5463 } else /* mType == OFFLOAD */ {
5464 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5465 mFlushPending = true;
5466 }
5467 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005468 } else if (previousTrack == 0) {
5469 // there could be an old track added back during track transition for direct
5470 // output, so always issues flush to flush data of the previous track if it
5471 // was already destroyed with HAL paused, then flush can resume the playback
5472 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005473 }
5474 PlaybackThread::onAddNewTrack_l();
5475}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005476
Eric Laurent81784c32012-11-19 14:55:58 -08005477AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5478 Vector< sp<Track> > *tracksToRemove
5479)
5480{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005481 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005482 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005483 bool doHwPause = false;
5484 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005485
5486 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005487 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005488 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005489 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005490 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005491 continue;
5492 }
5493
Eric Laurent5850c4c2016-11-10 13:04:31 -08005494 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005495#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005496 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005497#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005498 // Only consider last track started for volume and mixer state control.
5499 // In theory an older track could underrun and restart after the new one starts
5500 // but as we only care about the transition phase between two tracks on a
5501 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005502 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005503 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005504
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005505 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005506 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005507 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005508 doHwPause = true;
5509 mHwPaused = true;
5510 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005511 } else if (track->isFlushPending()) {
5512 track->flushAck();
5513 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005514 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005515 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005516 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005517 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005518 if (last) {
5519 mLeftVolFloat = mRightVolFloat = -1.0;
5520 if (mHwPaused) {
5521 doHwResume = true;
5522 mHwPaused = false;
5523 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005524 }
5525 }
5526
Eric Laurent81784c32012-11-19 14:55:58 -08005527 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005528 // for all its buffers to be filled before processing it.
5529 // Allow draining the buffer in case the client
5530 // app does not call stop() and relies on underrun to stop:
5531 // hence the test on (track->mRetryCount > 1).
5532 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005533 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005534 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005535 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005536 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005537 minFrames = mNormalFrameCount;
5538 } else {
5539 minFrames = 1;
5540 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005541
Eric Laurentab5cdba2014-06-09 17:22:27 -07005542 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5543 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005544 {
Andy Hungc0691382018-09-12 18:01:57 -07005545 ALOGVV("track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005546
5547 if (track->mFillingUpStatus == Track::FS_FILLED) {
5548 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005549 if (last) {
5550 // make sure processVolume_l() will apply new volume even if 0
5551 mLeftVolFloat = mRightVolFloat = -1.0;
5552 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005553 if (!mHwSupportsPause) {
5554 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005555 }
5556 }
5557
5558 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005559 processVolume_l(track, last);
5560 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005561 sp<Track> previousTrack = mPreviousTrack.promote();
5562 if (previousTrack != 0) {
5563 if (track != previousTrack.get()) {
5564 // Flush any data still being written from last track
5565 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005566 // Invalidate previous track to force a seek when resuming.
5567 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005568 }
5569 }
5570 mPreviousTrack = track;
5571
Eric Laurentd595b7c2013-04-03 17:27:56 -07005572 // reset retry count
5573 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005574 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005575 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005576 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005577 doHwResume = true;
5578 mHwPaused = false;
5579 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005580 }
Eric Laurent81784c32012-11-19 14:55:58 -08005581 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005582 // clear effect chain input buffer if the last active track started underruns
5583 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005584 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005585 mEffectChains[0]->clearInputBuffer();
5586 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005587 if (track->isStopping_1()) {
5588 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005589 if (last && mHwPaused) {
5590 doHwResume = true;
5591 mHwPaused = false;
5592 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005593 }
5594 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5595 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005596 // We have consumed all the buffers of this track.
5597 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005598 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005599 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005600 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5601 } else {
5602 audioHALFrames = 0;
5603 }
5604
Andy Hung818e7a32016-02-16 18:08:07 -08005605 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005606 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005607 track->presentationComplete(framesWritten, audioHALFrames) ||
5608 track->isPaused()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005609 if (track->isStopping_2()) {
5610 track->mState = TrackBase::STOPPED;
5611 }
Eric Laurent81784c32012-11-19 14:55:58 -08005612 if (track->isStopped()) {
5613 track->reset();
5614 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005615 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005616 }
5617 } else {
5618 // No buffers for this track. Give it a few chances to
5619 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005620 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005621 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005622 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", track->id());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005623 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005624 // indicate to client process that the track was disabled because of underrun;
5625 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005626 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005627 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005628 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5629 "minFrames = %u, mFormat = %#x",
5630 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005631 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005632 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005633 doHwPause = true;
5634 mHwPaused = true;
5635 }
Eric Laurent81784c32012-11-19 14:55:58 -08005636 }
5637 }
5638 }
5639 }
5640
Eric Laurentd1f69b02014-12-15 14:33:13 -08005641 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005642 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005643 for (size_t i = 0; i < mTracks.size(); i++) {
5644 if (mTracks[i]->isFlushPending()) {
5645 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005646 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005647 }
5648 }
5649 }
5650
5651 // make sure the pause/flush/resume sequence is executed in the right order.
5652 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5653 // before flush and then resume HW. This can happen in case of pause/flush/resume
5654 // if resume is received before pause is executed.
5655 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005656 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005657 status_t result = mOutput->stream->pause();
5658 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005659 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005660 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005661 flushHw_l();
5662 }
5663 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005664 status_t result = mOutput->stream->resume();
5665 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005666 }
Eric Laurent81784c32012-11-19 14:55:58 -08005667 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005668 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005669
5670 return mixerStatus;
5671}
5672
5673void AudioFlinger::DirectOutputThread::threadLoop_mix()
5674{
Eric Laurent81784c32012-11-19 14:55:58 -08005675 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005676 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005677 // output audio to hardware
5678 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005679 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005680 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005681 status_t status = mActiveTrack->getNextBuffer(&buffer);
5682 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005683 // no need to pad with 0 for compressed audio
5684 if (audio_has_proportional_frames(mFormat)) {
5685 memset(curBuf, 0, frameCount * mFrameSize);
5686 }
Eric Laurent81784c32012-11-19 14:55:58 -08005687 break;
5688 }
5689 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5690 frameCount -= buffer.frameCount;
5691 curBuf += buffer.frameCount * mFrameSize;
5692 mActiveTrack->releaseBuffer(&buffer);
5693 }
Andy Hung2098f272014-02-27 14:00:06 -08005694 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005695 mSleepTimeUs = 0;
5696 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005697 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005698}
5699
5700void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5701{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005702 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005703 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005704 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005705 return;
5706 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005707 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005708 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005709 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005710 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005711 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005712 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005713 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005714 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005715 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005716 }
5717}
5718
Eric Laurentd1f69b02014-12-15 14:33:13 -08005719void AudioFlinger::DirectOutputThread::threadLoop_exit()
5720{
5721 {
5722 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005723 for (size_t i = 0; i < mTracks.size(); i++) {
5724 if (mTracks[i]->isFlushPending()) {
5725 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005726 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005727 }
5728 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005729 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005730 flushHw_l();
5731 }
5732 }
5733 PlaybackThread::threadLoop_exit();
5734}
5735
5736// must be called with thread mutex locked
5737bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5738{
5739 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005740 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005741
vivek mehta9cd7ad12016-03-17 00:18:29 -07005742 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5743 return !mStandby;
5744 }
5745
Eric Laurentd1f69b02014-12-15 14:33:13 -08005746 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5747 // after a timeout and we will enter standby then.
5748 if (mTracks.size() > 0) {
5749 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005750 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5751 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005752 }
5753
Eric Laurent5cff4032015-05-26 13:49:58 -07005754 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005755}
5756
Eric Laurent10351942014-05-08 18:49:52 -07005757// checkForNewParameter_l() must be called with ThreadBase::mLock held
5758bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5759 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005760{
5761 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005762 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005763
Eric Laurent10351942014-05-08 18:49:52 -07005764 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005765
Eric Laurent10351942014-05-08 18:49:52 -07005766 AudioParameter param = AudioParameter(keyValuePair);
5767 int value;
5768 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5769 // forward device change to effects that have requested to be
5770 // aware of attached audio device.
5771 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005772 a2dpDeviceChanged =
5773 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005774 mOutDevice = value;
5775 for (size_t i = 0; i < mEffectChains.size(); i++) {
5776 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005777 }
5778 }
Eric Laurent81784c32012-11-19 14:55:58 -08005779 }
Eric Laurent10351942014-05-08 18:49:52 -07005780 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5781 // do not accept frame count changes if tracks are open as the track buffer
5782 // size depends on frame count and correct behavior would not be garantied
5783 // if frame count is changed after track creation
5784 if (!mTracks.isEmpty()) {
5785 status = INVALID_OPERATION;
5786 } else {
5787 reconfig = true;
5788 }
5789 }
5790 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005791 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005792 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005793 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005794 mStandby = true;
5795 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005796 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005797 }
5798 if (status == NO_ERROR && reconfig) {
5799 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005800 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005801 }
5802 }
5803
Eric Laurent42537be2016-01-08 17:16:42 -08005804 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005805}
5806
5807uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5808{
5809 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005810 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005811 time = PlaybackThread::activeSleepTimeUs();
5812 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005813 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005814 }
5815 return time;
5816}
5817
5818uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5819{
5820 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005821 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005822 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5823 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005824 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005825 }
5826 return time;
5827}
5828
5829uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5830{
5831 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005832 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005833 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5834 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005835 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005836 }
5837 return time;
5838}
5839
5840void AudioFlinger::DirectOutputThread::cacheParameters_l()
5841{
5842 PlaybackThread::cacheParameters_l();
5843
5844 // use shorter standby delay as on normal output to release
5845 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005846 // no delay on outputs with HW A/V sync
5847 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005848 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005849 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005850 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005851 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005852 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005853 }
Eric Laurent81784c32012-11-19 14:55:58 -08005854}
5855
Eric Laurente659ef42014-09-29 13:06:46 -07005856void AudioFlinger::DirectOutputThread::flushHw_l()
5857{
Phil Burk062e67a2015-02-11 13:40:50 -08005858 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005859 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005860 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005861 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005862}
5863
Andy Hung10cbff12017-02-21 17:30:14 -08005864int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5865 // If a VolumeShaper is active, we must wake up periodically to update volume.
5866 const int64_t NS_PER_MS = 1000000;
5867 return mVolumeShaperActive ?
5868 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5869}
5870
Eric Laurent81784c32012-11-19 14:55:58 -08005871// ----------------------------------------------------------------------------
5872
Eric Laurentbfb1b832013-01-07 09:53:42 -08005873AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005874 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005875 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005876 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005877 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005878 mDrainSequence(0),
5879 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005880{
5881}
5882
5883AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5884{
5885}
5886
5887void AudioFlinger::AsyncCallbackThread::onFirstRef()
5888{
5889 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5890}
5891
5892bool AudioFlinger::AsyncCallbackThread::threadLoop()
5893{
5894 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005895 uint32_t writeAckSequence;
5896 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005897 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005898
5899 {
5900 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005901 while (!((mWriteAckSequence & 1) ||
5902 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005903 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005904 exitPending())) {
5905 mWaitWorkCV.wait(mLock);
5906 }
5907
Eric Laurentbfb1b832013-01-07 09:53:42 -08005908 if (exitPending()) {
5909 break;
5910 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005911 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5912 mWriteAckSequence, mDrainSequence);
5913 writeAckSequence = mWriteAckSequence;
5914 mWriteAckSequence &= ~1;
5915 drainSequence = mDrainSequence;
5916 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005917 asyncError = mAsyncError;
5918 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005919 }
5920 {
Eric Laurent4de95592013-09-26 15:28:21 -07005921 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5922 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005923 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005924 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005925 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005926 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005927 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005928 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005929 if (asyncError) {
5930 playbackThread->onAsyncError();
5931 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005932 }
5933 }
5934 }
5935 return false;
5936}
5937
5938void AudioFlinger::AsyncCallbackThread::exit()
5939{
5940 ALOGV("AsyncCallbackThread::exit");
5941 Mutex::Autolock _l(mLock);
5942 requestExit();
5943 mWaitWorkCV.broadcast();
5944}
5945
Eric Laurent3b4529e2013-09-05 18:09:19 -07005946void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005947{
5948 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005949 // bit 0 is cleared
5950 mWriteAckSequence = sequence << 1;
5951}
5952
5953void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5954{
5955 Mutex::Autolock _l(mLock);
5956 // ignore unexpected callbacks
5957 if (mWriteAckSequence & 2) {
5958 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005959 mWaitWorkCV.signal();
5960 }
5961}
5962
Eric Laurent3b4529e2013-09-05 18:09:19 -07005963void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005964{
5965 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005966 // bit 0 is cleared
5967 mDrainSequence = sequence << 1;
5968}
5969
5970void AudioFlinger::AsyncCallbackThread::resetDraining()
5971{
5972 Mutex::Autolock _l(mLock);
5973 // ignore unexpected callbacks
5974 if (mDrainSequence & 2) {
5975 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005976 mWaitWorkCV.signal();
5977 }
5978}
5979
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005980void AudioFlinger::AsyncCallbackThread::setAsyncError()
5981{
5982 Mutex::Autolock _l(mLock);
5983 mAsyncError = true;
5984 mWaitWorkCV.signal();
5985}
5986
Eric Laurentbfb1b832013-01-07 09:53:42 -08005987
5988// ----------------------------------------------------------------------------
5989AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005990 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5991 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005992 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5993 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005994{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005995 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005996 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005997 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005998}
5999
Eric Laurentbfb1b832013-01-07 09:53:42 -08006000void AudioFlinger::OffloadThread::threadLoop_exit()
6001{
6002 if (mFlushPending || mHwPaused) {
6003 // If a flush is pending or track was paused, just discard buffered data
6004 flushHw_l();
6005 } else {
6006 mMixerStatus = MIXER_DRAIN_ALL;
6007 threadLoop_drain();
6008 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006009 if (mUseAsyncWrite) {
6010 ALOG_ASSERT(mCallbackThread != 0);
6011 mCallbackThread->exit();
6012 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006013 PlaybackThread::threadLoop_exit();
6014}
6015
6016AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6017 Vector< sp<Track> > *tracksToRemove
6018)
6019{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006020 size_t count = mActiveTracks.size();
6021
6022 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006023 bool doHwPause = false;
6024 bool doHwResume = false;
6025
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006026 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006027
Eric Laurentbfb1b832013-01-07 09:53:42 -08006028 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006029 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006030 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006031#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006032 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006033#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006034 // Only consider last track started for volume and mixer state control.
6035 // In theory an older track could underrun and restart after the new one starts
6036 // but as we only care about the transition phase between two tracks on a
6037 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006038 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006039 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006040
Haynes Mathew George7844f672014-01-15 12:32:55 -08006041 if (track->isInvalid()) {
6042 ALOGW("An invalidated track shouldn't be in active list");
6043 tracksToRemove->add(track);
6044 continue;
6045 }
6046
6047 if (track->mState == TrackBase::IDLE) {
6048 ALOGW("An idle track shouldn't be in active list");
6049 continue;
6050 }
6051
Eric Laurentbfb1b832013-01-07 09:53:42 -08006052 if (track->isPausing()) {
6053 track->setPaused();
6054 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006055 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006056 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006057 mHwPaused = true;
6058 }
6059 // If we were part way through writing the mixbuffer to
6060 // the HAL we must save this until we resume
6061 // BUG - this will be wrong if a different track is made active,
6062 // in that case we want to discard the pending data in the
6063 // mixbuffer and tell the client to present it again when the
6064 // track is resumed
6065 mPausedWriteLength = mCurrentWriteLength;
6066 mPausedBytesRemaining = mBytesRemaining;
6067 mBytesRemaining = 0; // stop writing
6068 }
6069 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006070 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006071 if (track->isStopping_1()) {
6072 track->mRetryCount = kMaxTrackStopRetriesOffload;
6073 } else {
6074 track->mRetryCount = kMaxTrackRetriesOffload;
6075 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006076 track->flushAck();
6077 if (last) {
6078 mFlushPending = true;
6079 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006080 } else if (track->isResumePending()){
6081 track->resumeAck();
6082 if (last) {
6083 if (mPausedBytesRemaining) {
6084 // Need to continue write that was interrupted
6085 mCurrentWriteLength = mPausedWriteLength;
6086 mBytesRemaining = mPausedBytesRemaining;
6087 mPausedBytesRemaining = 0;
6088 }
6089 if (mHwPaused) {
6090 doHwResume = true;
6091 mHwPaused = false;
6092 // threadLoop_mix() will handle the case that we need to
6093 // resume an interrupted write
6094 }
6095 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006096 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006097
Eric Laurent3df841a2016-07-15 15:15:40 -07006098 mLeftVolFloat = mRightVolFloat = -1.0;
6099
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006100 // Do not handle new data in this iteration even if track->framesReady()
6101 mixerStatus = MIXER_TRACKS_ENABLED;
6102 }
6103 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006104 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006105 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006106 if (track->mFillingUpStatus == Track::FS_FILLED) {
6107 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006108 if (last) {
6109 // make sure processVolume_l() will apply new volume even if 0
6110 mLeftVolFloat = mRightVolFloat = -1.0;
6111 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006112 }
6113
6114 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006115 sp<Track> previousTrack = mPreviousTrack.promote();
6116 if (previousTrack != 0) {
6117 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006118 // Flush any data still being written from last track
6119 mBytesRemaining = 0;
6120 if (mPausedBytesRemaining) {
6121 // Last track was paused so we also need to flush saved
6122 // mixbuffer state and invalidate track so that it will
6123 // re-submit that unwritten data when it is next resumed
6124 mPausedBytesRemaining = 0;
6125 // Invalidate is a bit drastic - would be more efficient
6126 // to have a flag to tell client that some of the
6127 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006128 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006129 }
6130 // flush data already sent to the DSP if changing audio session as audio
6131 // comes from a different source. Also invalidate previous track to force a
6132 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006133 if (previousTrack->sessionId() != track->sessionId()) {
6134 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006135 }
6136 }
6137 }
6138 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006139 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006140 if (track->isStopping_1()) {
6141 track->mRetryCount = kMaxTrackStopRetriesOffload;
6142 } else {
6143 track->mRetryCount = kMaxTrackRetriesOffload;
6144 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006145 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006146 mixerStatus = MIXER_TRACKS_READY;
6147 }
6148 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006149 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006150 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006151 if (--(track->mRetryCount) <= 0) {
6152 // Hardware buffer can hold a large amount of audio so we must
6153 // wait for all current track's data to drain before we say
6154 // that the track is stopped.
6155 if (mBytesRemaining == 0) {
6156 // Only start draining when all data in mixbuffer
6157 // has been written
6158 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6159 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6160 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6161 if (last && !mStandby) {
6162 // do not modify drain sequence if we are already draining. This happens
6163 // when resuming from pause after drain.
6164 if ((mDrainSequence & 1) == 0) {
6165 mSleepTimeUs = 0;
6166 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6167 mixerStatus = MIXER_DRAIN_TRACK;
6168 mDrainSequence += 2;
6169 }
6170 if (mHwPaused) {
6171 // It is possible to move from PAUSED to STOPPING_1 without
6172 // a resume so we must ensure hardware is running
6173 doHwResume = true;
6174 mHwPaused = false;
6175 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006176 }
6177 }
Eric Laurente93cc032016-05-05 10:15:10 -07006178 } else if (last) {
6179 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6180 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006181 }
6182 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006183 // Drain has completed or we are in standby, signal presentation complete
6184 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006185 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006186 uint32_t latency = 0;
6187 status_t result = mOutput->stream->getLatency(&latency);
6188 ALOGE_IF(result != OK,
6189 "Error when retrieving output stream latency: %d", result);
6190 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006191 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006192 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006193 track->presentationComplete(framesWritten, audioHALFrames);
6194 track->reset();
6195 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006196 // DIRECT and OFFLOADED stop resets frame counts.
6197 if (!mUseAsyncWrite) {
6198 // If we don't get explicit drain notification we must
6199 // register discontinuity regardless of whether this is
6200 // the previous (!last) or the upcoming (last) track
6201 // to avoid skipping the discontinuity.
6202 mTimestampVerifier.discontinuity();
6203 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006204 }
6205 } else {
6206 // No buffers for this track. Give it a few chances to
6207 // fill a buffer, then remove it from active list.
6208 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006209 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006210 uint64_t position = 0;
6211 struct timespec unused;
6212 // The running check restarts the retry counter at least once.
6213 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6214 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6215 running = true;
6216 mOffloadUnderrunPosition = position;
6217 }
6218 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006219 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6220 (long long)position, (long long)mOffloadUnderrunPosition);
6221 }
6222 if (running) { // still running, give us more time.
6223 track->mRetryCount = kMaxTrackRetriesOffload;
6224 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006225 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6226 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006227 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006228 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006229 // it will then automatically call start() when data is available
6230 track->disable();
6231 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006232 } else if (last){
6233 mixerStatus = MIXER_TRACKS_ENABLED;
6234 }
6235 }
6236 }
6237 // compute volume for this track
6238 processVolume_l(track, last);
6239 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006240
Eric Laurentea0fade2013-10-04 16:23:48 -07006241 // make sure the pause/flush/resume sequence is executed in the right order.
6242 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6243 // before flush and then resume HW. This can happen in case of pause/flush/resume
6244 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006245 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006246 status_t result = mOutput->stream->pause();
6247 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006248 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006249 if (mFlushPending) {
6250 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006251 }
Eric Laurentfd477972013-10-25 18:10:40 -07006252 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006253 status_t result = mOutput->stream->resume();
6254 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006255 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006256
Eric Laurentbfb1b832013-01-07 09:53:42 -08006257 // remove all the tracks that need to be...
6258 removeTracks_l(*tracksToRemove);
6259
6260 return mixerStatus;
6261}
6262
Eric Laurentbfb1b832013-01-07 09:53:42 -08006263// must be called with thread mutex locked
6264bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6265{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006266 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6267 mWriteAckSequence, mDrainSequence);
6268 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006269 return true;
6270 }
6271 return false;
6272}
6273
Eric Laurentbfb1b832013-01-07 09:53:42 -08006274bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6275{
6276 Mutex::Autolock _l(mLock);
6277 return waitingAsyncCallback_l();
6278}
6279
6280void AudioFlinger::OffloadThread::flushHw_l()
6281{
Eric Laurente659ef42014-09-29 13:06:46 -07006282 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006283 // Flush anything still waiting in the mixbuffer
6284 mCurrentWriteLength = 0;
6285 mBytesRemaining = 0;
6286 mPausedWriteLength = 0;
6287 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006288 // reset bytes written count to reflect that DSP buffers are empty after flush.
6289 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006290 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006291
Eric Laurentbfb1b832013-01-07 09:53:42 -08006292 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006293 // discard any pending drain or write ack by incrementing sequence
6294 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6295 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006296 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006297 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6298 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006299 }
6300}
6301
Haynes Mathew George05317d22016-05-03 16:34:26 -07006302void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6303{
6304 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006305 if (PlaybackThread::invalidateTracks_l(streamType)) {
6306 mFlushPending = true;
6307 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006308}
6309
Eric Laurentbfb1b832013-01-07 09:53:42 -08006310// ----------------------------------------------------------------------------
6311
Eric Laurent81784c32012-11-19 14:55:58 -08006312AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006313 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006314 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006315 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006316 mWaitTimeMs(UINT_MAX)
6317{
6318 addOutputTrack(mainThread);
6319}
6320
6321AudioFlinger::DuplicatingThread::~DuplicatingThread()
6322{
6323 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6324 mOutputTracks[i]->destroy();
6325 }
6326}
6327
6328void AudioFlinger::DuplicatingThread::threadLoop_mix()
6329{
6330 // mix buffers...
6331 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006332 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006333 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006334 if (mMixerBufferValid) {
6335 memset(mMixerBuffer, 0, mMixerBufferSize);
6336 } else {
6337 memset(mSinkBuffer, 0, mSinkBufferSize);
6338 }
Eric Laurent81784c32012-11-19 14:55:58 -08006339 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006340 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006341 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006342 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006343 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006344}
6345
6346void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6347{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006348 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006349 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006350 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006351 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006352 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006353 }
6354 } else if (mBytesWritten != 0) {
6355 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6356 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006357 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006358 } else {
6359 // flush remaining overflow buffers in output tracks
6360 writeFrames = 0;
6361 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006362 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006363 }
6364}
6365
Eric Laurentbfb1b832013-01-07 09:53:42 -08006366ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006367{
6368 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006369 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6370
6371 // Consider the first OutputTrack for timestamp and frame counting.
6372
6373 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6374 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6375 // we always claim success.
6376 if (i == 0) {
6377 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6378 ALOGD_IF(correction != 0 && writeFrames != 0,
6379 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6380 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6381 mFramesWritten -= correction;
6382 }
6383
6384 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006385 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006386 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006387 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006388}
6389
6390void AudioFlinger::DuplicatingThread::threadLoop_standby()
6391{
6392 // DuplicatingThread implements standby by stopping all tracks
6393 for (size_t i = 0; i < outputTracks.size(); i++) {
6394 outputTracks[i]->stop();
6395 }
6396}
6397
Andy Hung1bc088a2018-02-09 15:57:31 -08006398void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6399{
6400 MixerThread::dumpInternals(fd, args);
6401
6402 std::stringstream ss;
6403 const size_t numTracks = mOutputTracks.size();
6404 ss << " " << numTracks << " OutputTracks";
6405 if (numTracks > 0) {
6406 ss << ":";
6407 for (const auto &track : mOutputTracks) {
6408 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006409 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006410 if (thread.get() != nullptr) {
6411 ss << thread.get() << ", " << thread->id();
6412 } else {
6413 ss << "null";
6414 }
6415 ss << ")";
6416 }
6417 }
6418 ss << "\n";
6419 std::string result = ss.str();
6420 write(fd, result.c_str(), result.size());
6421}
6422
Eric Laurent81784c32012-11-19 14:55:58 -08006423void AudioFlinger::DuplicatingThread::saveOutputTracks()
6424{
6425 outputTracks = mOutputTracks;
6426}
6427
6428void AudioFlinger::DuplicatingThread::clearOutputTracks()
6429{
6430 outputTracks.clear();
6431}
6432
6433void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6434{
6435 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006436 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6437 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6438 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6439 const size_t frameCount =
6440 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6441 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6442 // from different OutputTracks and their associated MixerThreads (e.g. one may
6443 // nearly empty and the other may be dropping data).
6444
6445 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006446 this,
6447 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006448 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006449 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006450 frameCount,
6451 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006452 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6453 if (status != NO_ERROR) {
6454 ALOGE("addOutputTrack() initCheck failed %d", status);
6455 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006456 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006457 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6458 mOutputTracks.add(outputTrack);
6459 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6460 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006461}
6462
6463void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6464{
6465 Mutex::Autolock _l(mLock);
6466 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6467 if (mOutputTracks[i]->thread() == thread) {
6468 mOutputTracks[i]->destroy();
6469 mOutputTracks.removeAt(i);
6470 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006471 if (thread->getOutput() == mOutput) {
6472 mOutput = NULL;
6473 }
Eric Laurent81784c32012-11-19 14:55:58 -08006474 return;
6475 }
6476 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006477 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006478}
6479
6480// caller must hold mLock
6481void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6482{
6483 mWaitTimeMs = UINT_MAX;
6484 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6485 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6486 if (strong != 0) {
6487 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6488 if (waitTimeMs < mWaitTimeMs) {
6489 mWaitTimeMs = waitTimeMs;
6490 }
6491 }
6492 }
6493}
6494
6495
6496bool AudioFlinger::DuplicatingThread::outputsReady(
6497 const SortedVector< sp<OutputTrack> > &outputTracks)
6498{
6499 for (size_t i = 0; i < outputTracks.size(); i++) {
6500 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6501 if (thread == 0) {
6502 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6503 outputTracks[i].get());
6504 return false;
6505 }
6506 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6507 // see note at standby() declaration
6508 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6509 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6510 thread.get());
6511 return false;
6512 }
6513 }
6514 return true;
6515}
6516
Kevin Rocard12381092018-04-11 09:19:59 -07006517void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6518 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006519{
Kevin Rocard12381092018-04-11 09:19:59 -07006520 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6521 outputTrack->setMetadatas(metadata.tracks);
6522 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006523}
6524
Eric Laurent81784c32012-11-19 14:55:58 -08006525uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6526{
6527 return (mWaitTimeMs * 1000) / 2;
6528}
6529
6530void AudioFlinger::DuplicatingThread::cacheParameters_l()
6531{
6532 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6533 updateWaitTime_l();
6534
6535 MixerThread::cacheParameters_l();
6536}
6537
Eric Laurent6acd1d42017-01-04 14:23:29 -08006538
Eric Laurent81784c32012-11-19 14:55:58 -08006539// ----------------------------------------------------------------------------
6540// Record
6541// ----------------------------------------------------------------------------
6542
6543AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6544 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006545 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006546 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006547 audio_devices_t inDevice,
6548 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006549 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006550 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006551 mInput(input),
6552 mActiveTracks(&this->mLocalLog),
6553 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006554 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006555 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006556 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6557 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006558 // mFastCapture below
6559 , mFastCaptureFutex(0)
6560 // mInputSource
6561 // mPipeSink
6562 // mPipeSource
6563 , mPipeFramesP2(0)
6564 // mPipeMemory
6565 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006566 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006567 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006568{
Glenn Kastend7dca052015-03-05 16:05:54 -08006569 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6570 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006571
Andy Hungc8fddf32018-08-08 18:32:37 -07006572 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6573 mIsMsdDevice = strcmp(
6574 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6575 }
6576
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006577 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006578
Andy Hungc8fddf32018-08-08 18:32:37 -07006579 // TODO: We may also match on address as well as device type for
6580 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
6581 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
6582 "audio.timestamp.corrected_input_devices",
6583 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6584 : AUDIO_DEVICE_NONE));
6585
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006586 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006587 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006588 size_t numCounterOffers = 0;
6589 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006590#if !LOG_NDEBUG
6591 ssize_t index =
6592#else
6593 (void)
6594#endif
6595 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006596 ALOG_ASSERT(index == 0);
6597
6598 // initialize fast capture depending on configuration
6599 bool initFastCapture;
6600 switch (kUseFastCapture) {
6601 case FastCapture_Never:
6602 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006603 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006604 break;
6605 case FastCapture_Always:
6606 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006607 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006608 break;
6609 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006610 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006611 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6612 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6613 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006614 break;
6615 // case FastCapture_Dynamic:
6616 }
6617
6618 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006619 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006620 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006621 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6622 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006623 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006624 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006625 const sp<MemoryDealer> roHeap(readOnlyHeap());
6626 sp<IMemory> pipeMemory;
6627 if ((roHeap == 0) ||
6628 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006629 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6630 ALOGE("not enough memory for pipe buffer size=%zu; "
6631 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6632 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6633 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006634 goto failed;
6635 }
6636 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6637 memset(pipeBuffer, 0, pipeSize);
6638 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6639 const NBAIO_Format offers[1] = {format};
6640 size_t numCounterOffers = 0;
6641 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6642 ALOG_ASSERT(index == 0);
6643 mPipeSink = pipe;
6644 PipeReader *pipeReader = new PipeReader(*pipe);
6645 numCounterOffers = 0;
6646 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6647 ALOG_ASSERT(index == 0);
6648 mPipeSource = pipeReader;
6649 mPipeFramesP2 = pipeFramesP2;
6650 mPipeMemory = pipeMemory;
6651
6652 // create fast capture
6653 mFastCapture = new FastCapture();
6654 FastCaptureStateQueue *sq = mFastCapture->sq();
6655#ifdef STATE_QUEUE_DUMP
6656 // FIXME
6657#endif
6658 FastCaptureState *state = sq->begin();
6659 state->mCblk = NULL;
6660 state->mInputSource = mInputSource.get();
6661 state->mInputSourceGen++;
6662 state->mPipeSink = pipe;
6663 state->mPipeSinkGen++;
6664 state->mFrameCount = mFrameCount;
6665 state->mCommand = FastCaptureState::COLD_IDLE;
6666 // already done in constructor initialization list
6667 //mFastCaptureFutex = 0;
6668 state->mColdFutexAddr = &mFastCaptureFutex;
6669 state->mColdGen++;
6670 state->mDumpState = &mFastCaptureDumpState;
6671#ifdef TEE_SINK
6672 // FIXME
6673#endif
6674 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6675 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6676 sq->end();
6677 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6678
6679 // start the fast capture
6680 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6681 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006682 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006683 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006684#ifdef AUDIO_WATCHDOG
6685 // FIXME
6686#endif
6687
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006688 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006689 }
Andy Hung8946a282018-04-19 20:04:56 -07006690#ifdef TEE_SINK
6691 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6692 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6693#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006694failed: ;
6695
6696 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006697}
6698
Eric Laurent81784c32012-11-19 14:55:58 -08006699AudioFlinger::RecordThread::~RecordThread()
6700{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006701 if (mFastCapture != 0) {
6702 FastCaptureStateQueue *sq = mFastCapture->sq();
6703 FastCaptureState *state = sq->begin();
6704 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6705 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6706 if (old == -1) {
6707 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6708 }
6709 }
6710 state->mCommand = FastCaptureState::EXIT;
6711 sq->end();
6712 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6713 mFastCapture->join();
6714 mFastCapture.clear();
6715 }
6716 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006717 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006718 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006719}
6720
6721void AudioFlinger::RecordThread::onFirstRef()
6722{
Glenn Kastend7dca052015-03-05 16:05:54 -08006723 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006724}
6725
Eric Laurent555530a2017-02-07 18:17:24 -08006726void AudioFlinger::RecordThread::preExit()
6727{
6728 ALOGV(" preExit()");
6729 Mutex::Autolock _l(mLock);
6730 for (size_t i = 0; i < mTracks.size(); i++) {
6731 sp<RecordTrack> track = mTracks[i];
6732 track->invalidate();
6733 }
6734 mActiveTracks.clear();
6735 mStartStopCond.broadcast();
6736}
6737
Eric Laurent81784c32012-11-19 14:55:58 -08006738bool AudioFlinger::RecordThread::threadLoop()
6739{
Eric Laurent81784c32012-11-19 14:55:58 -08006740 nsecs_t lastWarning = 0;
6741
6742 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006743
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006744reacquire_wakelock:
6745 sp<RecordTrack> activeTrack;
6746 {
6747 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006748 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006749 }
6750
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006751 // used to request a deferred sleep, to be executed later while mutex is unlocked
6752 uint32_t sleepUs = 0;
6753
6754 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006755 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006756 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006757
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006758 // activeTracks accumulates a copy of a subset of mActiveTracks
6759 Vector< sp<RecordTrack> > activeTracks;
6760
Glenn Kasten735f45f2014-08-18 15:51:59 -07006761 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006762 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006763
Glenn Kasten735f45f2014-08-18 15:51:59 -07006764 // reference to a fast track which is about to be removed
6765 sp<RecordTrack> fastTrackToRemove;
6766
Eric Laurent81784c32012-11-19 14:55:58 -08006767 { // scope for mLock
6768 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006769
Eric Laurent021cf962014-05-13 10:18:14 -07006770 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006771
Eric Laurent000a4192014-01-29 15:17:32 -08006772 // check exitPending here because checkForNewParameters_l() and
6773 // checkForNewParameters_l() can temporarily release mLock
6774 if (exitPending()) {
6775 break;
6776 }
6777
Eric Laurent5c25d562016-07-13 17:17:45 -07006778 // sleep with mutex unlocked
6779 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006780 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006781 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6782 ATRACE_END();
6783 sleepUs = 0;
6784 continue;
6785 }
6786
Glenn Kasten2b806402013-11-20 16:37:38 -08006787 // if no active track(s), then standby and release wakelock
6788 size_t size = mActiveTracks.size();
6789 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006790 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006791 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006792 releaseWakeLock_l();
6793 ALOGV("RecordThread: loop stopping");
6794 // go to sleep
6795 mWaitWorkCV.wait(mLock);
6796 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006797 goto reacquire_wakelock;
6798 }
6799
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006800 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006801 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006802 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006803
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006804 activeTrack = mActiveTracks[i];
6805 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006806 if (activeTrack->isFastTrack()) {
6807 ALOG_ASSERT(fastTrackToRemove == 0);
6808 fastTrackToRemove = activeTrack;
6809 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006810 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006811 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006812 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006813 continue;
6814 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006815
6816 TrackBase::track_state activeTrackState = activeTrack->mState;
6817 switch (activeTrackState) {
6818
6819 case TrackBase::PAUSING:
6820 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006821 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006822 doBroadcast = true;
6823 size--;
6824 continue;
6825
6826 case TrackBase::STARTING_1:
6827 sleepUs = 10000;
6828 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006829 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006830 continue;
6831
6832 case TrackBase::STARTING_2:
6833 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006834 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006835 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006836 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006837 break;
6838
6839 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006840 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006841 break;
6842
Andy Hungce685402018-10-05 17:23:27 -07006843 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6844 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6845 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006846 default:
Andy Hungce685402018-10-05 17:23:27 -07006847 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6848 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006849 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006850
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006851 activeTracks.add(activeTrack);
6852 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006853
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006854 if (activeTrack->isFastTrack()) {
6855 ALOG_ASSERT(!mFastTrackAvail);
6856 ALOG_ASSERT(fastTrack == 0);
6857 fastTrack = activeTrack;
6858 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006859 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006860
Andy Hungdae27702016-10-31 14:01:16 -07006861 mActiveTracks.updatePowerState(this);
6862
Kevin Rocard069c2712018-03-29 19:09:14 -07006863 updateMetadata_l();
6864
Eric Laurent5c25d562016-07-13 17:17:45 -07006865 if (allStopped) {
6866 standbyIfNotAlreadyInStandby();
6867 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006868 if (doBroadcast) {
6869 mStartStopCond.broadcast();
6870 }
6871
6872 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006873 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006874 if (sleepUs == 0) {
6875 sleepUs = kRecordThreadSleepUs;
6876 }
6877 continue;
6878 }
6879 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006880
Eric Laurent81784c32012-11-19 14:55:58 -08006881 lockEffectChains_l(effectChains);
6882 }
6883
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006884 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006885
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006886 size_t size = effectChains.size();
6887 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006888 // thread mutex is not locked, but effect chain is locked
6889 effectChains[i]->process_l();
6890 }
6891
Glenn Kasten735f45f2014-08-18 15:51:59 -07006892 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006893 if (mFastCapture != 0) {
6894 FastCaptureStateQueue *sq = mFastCapture->sq();
6895 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006896 bool didModify = false;
6897 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006898 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6899 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6900 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6901 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6902 if (old == -1) {
6903 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6904 }
6905 }
6906 state->mCommand = FastCaptureState::READ_WRITE;
6907#if 0 // FIXME
6908 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006909 FastThreadDumpState::kSamplingNforLowRamDevice :
6910 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006911#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006912 didModify = true;
6913 }
6914 audio_track_cblk_t *cblkOld = state->mCblk;
6915 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6916 if (cblkNew != cblkOld) {
6917 state->mCblk = cblkNew;
6918 // block until acked if removing a fast track
6919 if (cblkOld != NULL) {
6920 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6921 }
6922 didModify = true;
6923 }
jiabin01c8f562018-07-19 17:47:28 -07006924 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
6925 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
6926 if (state->mFastPatchRecordBufferProvider != abp) {
6927 state->mFastPatchRecordBufferProvider = abp;
6928 state->mFastPatchRecordFormat = fastTrack == 0 ?
6929 AUDIO_FORMAT_INVALID : fastTrack->format();
6930 didModify = true;
6931 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07006932 sq->end(didModify);
6933 if (didModify) {
6934 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006935#if 0
6936 if (kUseFastCapture == FastCapture_Dynamic) {
6937 mNormalSource = mPipeSource;
6938 }
6939#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006940 }
6941 }
6942
Glenn Kasten735f45f2014-08-18 15:51:59 -07006943 // now run the fast track destructor with thread mutex unlocked
6944 fastTrackToRemove.clear();
6945
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006946 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6947 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6948 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6949 // If destination is non-contiguous, first read past the nominal end of buffer, then
6950 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006951
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006952 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006953 ssize_t framesRead;
6954
6955 // If an NBAIO source is present, use it to read the normal capture's data
6956 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07006957 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006958
6959 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6960 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6961 // we immediately retry the read() to get data and prevent another overflow.
6962 for (int retries = 0; retries <= 2; ++retries) {
6963 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6964 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6965 framesToRead);
6966 if (framesRead != OVERRUN) break;
6967 }
6968
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006969 const ssize_t availableToRead = mPipeSource->availableToRead();
6970 if (availableToRead >= 0) {
6971 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6972 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6973 "more frames to read than fifo size, %zd > %zu",
6974 availableToRead, mPipeFramesP2);
6975 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6976 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6977 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6978 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006979 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6980 }
6981 if (framesRead < 0) {
6982 status_t status = (status_t) framesRead;
6983 switch (status) {
6984 case OVERRUN:
6985 ALOGW("overrun on read from pipe");
6986 framesRead = 0;
6987 break;
6988 case NEGOTIATE:
6989 ALOGE("re-negotiation is needed");
6990 framesRead = -1; // Will cause an attempt to recover.
6991 break;
6992 default:
6993 ALOGE("unknown error %d on read from pipe", status);
6994 break;
6995 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006996 }
6997 // otherwise use the HAL / AudioStreamIn directly
6998 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006999 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007000 size_t bytesRead;
7001 status_t result = mInput->stream->read(
7002 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007003 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007004 if (result < 0) {
7005 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007006 } else {
7007 framesRead = bytesRead / mFrameSize;
7008 }
7009 }
7010
Andy Hung3f0c9022016-01-15 17:49:46 -08007011 // Update server timestamp with server stats
7012 // systemTime() is optional if the hardware supports timestamps.
7013 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7014 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7015
7016 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007017 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007018 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007019 if (mStandby) {
7020 mTimestampVerifier.discontinuity();
Andy Hungc8fddf32018-08-08 18:32:37 -07007021 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR
7022 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7023
7024 mTimestampVerifier.add(position, time, mSampleRate);
7025
7026 // Correct timestamps
7027 if (isTimestampCorrectionEnabled()) {
7028 ALOGV("TS_BEFORE: %d %lld %lld",
7029 id(), (long long)time, (long long)position);
7030 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7031 position = correctedTimestamp.mFrames;
7032 time = correctedTimestamp.mTimeNs;
7033 ALOGV("TS_AFTER: %d %lld %lld",
7034 id(), (long long)time, (long long)position);
7035 }
7036
Andy Hung3f0c9022016-01-15 17:49:46 -08007037 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7038 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7039 // Note: In general record buffers should tend to be empty in
7040 // a properly running pipeline.
7041 //
7042 // Also, it is not advantageous to call get_presentation_position during the read
7043 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007044 } else {
7045 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007046 }
7047 }
7048 // Use this to track timestamp information
7049 // ALOGD("%s", mTimestamp.toString().c_str());
7050
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007051 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007052 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007053 // Force input into standby so that it tries to recover at next read attempt
7054 inputStandBy();
7055 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007056 }
7057 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007058 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007059 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007060 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007061 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007062
Andy Hung8946a282018-04-19 20:04:56 -07007063#ifdef TEE_SINK
7064 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7065#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007066 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007067 {
7068 size_t part1 = mRsmpInFramesP2 - rear;
7069 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007070 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007071 (framesRead - part1) * mFrameSize);
7072 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007073 }
7074 rear = mRsmpInRear += framesRead;
7075
7076 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007077
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007078 // loop over each active track
7079 for (size_t i = 0; i < size; i++) {
7080 activeTrack = activeTracks[i];
7081
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007082 // skip fast tracks, as those are handled directly by FastCapture
7083 if (activeTrack->isFastTrack()) {
7084 continue;
7085 }
7086
Andy Hung73c02e42015-03-29 01:13:58 -07007087 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007088 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7089
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007090 enum {
7091 OVERRUN_UNKNOWN,
7092 OVERRUN_TRUE,
7093 OVERRUN_FALSE
7094 } overrun = OVERRUN_UNKNOWN;
7095
7096 // loop over getNextBuffer to handle circular sink
7097 for (;;) {
7098
7099 activeTrack->mSink.frameCount = ~0;
7100 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7101 size_t framesOut = activeTrack->mSink.frameCount;
7102 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7103
Andy Hung73c02e42015-03-29 01:13:58 -07007104 // check available frames and handle overrun conditions
7105 // if the record track isn't draining fast enough.
7106 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007107 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007108 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7109 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007110 overrun = OVERRUN_TRUE;
7111 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007112 if (framesOut == 0 || framesIn == 0) {
7113 break;
7114 }
7115
Andy Hung6770c6f2015-04-07 13:43:36 -07007116 // Don't allow framesOut to be larger than what is possible with resampling
7117 // from framesIn.
7118 // This isn't strictly necessary but helps limit buffer resizing in
7119 // RecordBufferConverter. TODO: remove when no longer needed.
7120 framesOut = min(framesOut,
7121 destinationFramesPossible(
7122 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007123
7124 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007125 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007126 // straight from RecordThread buffer to RecordTrack buffer.
7127 AudioBufferProvider::Buffer buffer;
7128 buffer.frameCount = framesOut;
7129 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7130 if (status == OK && buffer.frameCount != 0) {
7131 ALOGV_IF(buffer.frameCount != framesOut,
7132 "%s() read less than expected (%zu vs %zu)",
7133 __func__, buffer.frameCount, framesOut);
7134 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007135 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007136 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7137 } else {
7138 framesOut = 0;
7139 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7140 __func__, status, buffer.frameCount);
7141 }
7142 } else {
7143 // process frames from the RecordThread buffer provider to the RecordTrack
7144 // buffer
7145 framesOut = activeTrack->mRecordBufferConverter->convert(
7146 activeTrack->mSink.raw,
7147 activeTrack->mResamplerBufferProvider,
7148 framesOut);
7149 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007150
7151 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7152 overrun = OVERRUN_FALSE;
7153 }
7154
7155 if (activeTrack->mFramesToDrop == 0) {
7156 if (framesOut > 0) {
7157 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007158 // Sanitize before releasing if the track has no access to the source data
7159 // An idle UID receives silence from non virtual devices until active
7160 if (activeTrack->isSilenced()) {
7161 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
7162 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007163 activeTrack->releaseBuffer(&activeTrack->mSink);
7164 }
7165 } else {
7166 // FIXME could do a partial drop of framesOut
7167 if (activeTrack->mFramesToDrop > 0) {
7168 activeTrack->mFramesToDrop -= framesOut;
7169 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007170 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007171 }
7172 } else {
7173 activeTrack->mFramesToDrop += framesOut;
7174 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7175 activeTrack->mSyncStartEvent->isCancelled()) {
7176 ALOGW("Synced record %s, session %d, trigger session %d",
7177 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7178 activeTrack->sessionId(),
7179 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007180 activeTrack->mSyncStartEvent->triggerSession() :
7181 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007182 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007183 }
7184 }
7185 }
7186
7187 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007188 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007189 }
7190 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007191
7192 switch (overrun) {
7193 case OVERRUN_TRUE:
7194 // client isn't retrieving buffers fast enough
7195 if (!activeTrack->setOverflow()) {
7196 nsecs_t now = systemTime();
7197 // FIXME should lastWarning per track?
7198 if ((now - lastWarning) > kWarningThrottleNs) {
7199 ALOGW("RecordThread: buffer overflow");
7200 lastWarning = now;
7201 }
7202 }
7203 break;
7204 case OVERRUN_FALSE:
7205 activeTrack->clearOverflow();
7206 break;
7207 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007208 break;
7209 }
7210
Andy Hung3f0c9022016-01-15 17:49:46 -08007211 // update frame information and push timestamp out
7212 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007213 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007214 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7215 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007216 }
7217
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007218unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007219 // enable changes in effect chain
7220 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007221 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08007222 }
7223
Glenn Kasten93e471f2013-08-19 08:40:07 -07007224 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007225
7226 {
7227 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007228 for (size_t i = 0; i < mTracks.size(); i++) {
7229 sp<RecordTrack> track = mTracks[i];
7230 track->invalidate();
7231 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007232 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007233 mStartStopCond.broadcast();
7234 }
7235
7236 releaseWakeLock();
7237
7238 ALOGV("RecordThread %p exiting", this);
7239 return false;
7240}
7241
Glenn Kasten93e471f2013-08-19 08:40:07 -07007242void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007243{
7244 if (!mStandby) {
7245 inputStandBy();
7246 mStandby = true;
7247 }
7248}
7249
7250void AudioFlinger::RecordThread::inputStandBy()
7251{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007252 // Idle the fast capture if it's currently running
7253 if (mFastCapture != 0) {
7254 FastCaptureStateQueue *sq = mFastCapture->sq();
7255 FastCaptureState *state = sq->begin();
7256 if (!(state->mCommand & FastCaptureState::IDLE)) {
7257 state->mCommand = FastCaptureState::COLD_IDLE;
7258 state->mColdFutexAddr = &mFastCaptureFutex;
7259 state->mColdGen++;
7260 mFastCaptureFutex = 0;
7261 sq->end();
7262 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7263 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7264#if 0
7265 if (kUseFastCapture == FastCapture_Dynamic) {
7266 // FIXME
7267 }
7268#endif
7269#ifdef AUDIO_WATCHDOG
7270 // FIXME
7271#endif
7272 } else {
7273 sq->end(false /*didModify*/);
7274 }
7275 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007276 status_t result = mInput->stream->standby();
7277 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007278
7279 // If going into standby, flush the pipe source.
7280 if (mPipeSource.get() != nullptr) {
7281 const ssize_t flushed = mPipeSource->flush();
7282 if (flushed > 0) {
7283 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7284 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7285 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7286 }
7287 }
Eric Laurent81784c32012-11-19 14:55:58 -08007288}
7289
Glenn Kasten05997e22014-03-13 15:08:33 -07007290// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007291sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007292 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007293 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007294 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007295 audio_format_t format,
7296 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007297 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007298 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007299 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007300 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007301 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007302 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007303 status_t *status,
7304 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007305{
Glenn Kasten74935e42013-12-19 08:56:45 -08007306 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007307 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007308 sp<RecordTrack> track;
7309 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007310 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007311 audio_input_flags_t requestedFlags = *flags;
7312 uint32_t sampleRate;
7313
7314 lStatus = initCheck();
7315 if (lStatus != NO_ERROR) {
7316 ALOGE("createRecordTrack_l() audio driver not initialized");
7317 goto Exit;
7318 }
7319
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007320 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7321 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7322 lStatus = BAD_VALUE;
7323 goto Exit;
7324 }
7325
Eric Laurentf14db3c2017-12-08 14:20:36 -08007326 if (*pSampleRate == 0) {
7327 *pSampleRate = mSampleRate;
7328 }
7329 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007330
7331 // special case for FAST flag considered OK if fast capture is present
7332 if (hasFastCapture()) {
7333 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7334 }
7335
Eric Laurentf14db3c2017-12-08 14:20:36 -08007336 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007337 if ((*flags & inputFlags) != *flags) {
7338 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7339 " input flags (%08x)",
7340 *flags, inputFlags);
7341 *flags = (audio_input_flags_t)(*flags & inputFlags);
7342 }
Eric Laurent81784c32012-11-19 14:55:58 -08007343
Glenn Kasten90e58b12013-07-31 16:16:02 -07007344 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007345 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007346 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007347 // we formerly checked for a callback handler (non-0 tid),
7348 // but that is no longer required for TRANSFER_OBTAIN mode
7349 //
Glenn Kasten74105912014-07-03 12:28:53 -07007350 // frame count is not specified, or is exactly the pipe depth
7351 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007352 // PCM data
7353 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007354 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007355 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007356 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007357 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007358 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007359 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007360 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007361 hasFastCapture() &&
7362 // there are sufficient fast track slots available
7363 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007364 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007365 // check compatibility with audio effects.
7366 Mutex::Autolock _l(mLock);
7367 // Do not accept FAST flag if the session has software effects
7368 sp<EffectChain> chain = getEffectChain_l(sessionId);
7369 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007370 audio_input_flags_t old = *flags;
7371 chain->checkInputFlagCompatibility(flags);
7372 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007373 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7374 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007375 }
7376 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007377 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007378 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7379 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007380 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007381 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7382 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007383 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007384 this, frameCount, mFrameCount, mPipeFramesP2,
7385 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007386 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007387 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007388 }
7389 }
7390
Eric Laurentf14db3c2017-12-08 14:20:36 -08007391 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7392 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7393 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7394 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7395 lStatus = BAD_TYPE;
7396 goto Exit;
7397 }
7398
Glenn Kasten74105912014-07-03 12:28:53 -07007399 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007400 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007401 // fast track: frame count is exactly the pipe depth
7402 frameCount = mPipeFramesP2;
7403 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007404 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007405 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007406 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7407 // or 20 ms if there is a fast capture
7408 // TODO This could be a roundupRatio inline, and const
7409 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7410 * sampleRate + mSampleRate - 1) / mSampleRate;
7411 // minimum number of notification periods is at least kMinNotifications,
7412 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7413 static const size_t kMinNotifications = 3;
7414 static const uint32_t kMinMs = 30;
7415 // TODO This could be a roundupRatio inline
7416 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7417 // TODO This could be a roundupRatio inline
7418 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7419 maxNotificationFrames;
7420 const size_t minFrameCount = maxNotificationFrames *
7421 max(kMinNotifications, minNotificationsByMs);
7422 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007423 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7424 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007425 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007426 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007427 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007428 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007429
7430 { // scope for mLock
7431 Mutex::Autolock _l(mLock);
7432
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007433 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007434 format, channelMask, frameCount,
7435 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007436 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007437
Glenn Kasten03003332013-08-06 15:40:54 -07007438 lStatus = track->initCheck();
7439 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007440 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007441 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007442 goto Exit;
7443 }
7444 mTracks.add(track);
7445
Eric Laurent05067782016-06-01 18:27:28 -07007446 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007447 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7448 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7449 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007450 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007451 }
Eric Laurent81784c32012-11-19 14:55:58 -08007452 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007453
Eric Laurent81784c32012-11-19 14:55:58 -08007454 lStatus = NO_ERROR;
7455
7456Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007457 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007458 return track;
7459}
7460
7461status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7462 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007463 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007464{
7465 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7466 sp<ThreadBase> strongMe = this;
7467 status_t status = NO_ERROR;
7468
7469 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007470 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007471 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007472 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007473 triggerSession,
7474 recordTrack->sessionId(),
7475 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007476 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007477 // Sync event can be cancelled by the trigger session if the track is not in a
7478 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007479 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007480 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007481 } else {
7482 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007483 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007484 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007485 }
7486 }
7487
7488 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007489 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007490 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007491 if (recordTrack->isInvalid()) {
7492 recordTrack->clearSyncStartEvent();
7493 return INVALID_OPERATION;
7494 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007495 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7496 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007497 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7498 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007499 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007500 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007501 } else {
7502 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007503 }
7504 return status;
7505 }
7506
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007507 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7508 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7509 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007510 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007511 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007512 status_t status = NO_ERROR;
7513 if (recordTrack->isExternalTrack()) {
7514 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007515 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007516 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007517 if (recordTrack->isInvalid()) {
7518 recordTrack->clearSyncStartEvent();
7519 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7520 recordTrack->mState = TrackBase::STARTING_2;
7521 // STARTING_2 forces destroy to call stopInput.
7522 }
7523 return INVALID_OPERATION;
7524 }
7525 if (recordTrack->mState != TrackBase::STARTING_1) {
7526 ALOGW("%s(%d): unsynchronized mState:%d change",
7527 __func__, recordTrack->id(), recordTrack->mState);
7528 // Someone else has changed state, let them take over,
7529 // leave mState in the new state.
7530 recordTrack->clearSyncStartEvent();
7531 return INVALID_OPERATION;
7532 }
7533 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007534 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007535 ALOGW("%s(%d): startInput failed, status %d",
7536 __func__, recordTrack->id(), status);
7537 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7538 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007539 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007540 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007541 return status;
7542 }
Eric Laurent81784c32012-11-19 14:55:58 -08007543 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007544 // Catch up with current buffer indices if thread is already running.
7545 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7546 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7547 // see previously buffered data before it called start(), but with greater risk of overrun.
7548
Andy Hung73c02e42015-03-29 01:13:58 -07007549 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007550 if (!recordTrack->isDirect()) {
7551 // clear any converter state as new data will be discontinuous
7552 recordTrack->mRecordBufferConverter->reset();
7553 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007554 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007555 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007556 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007557 return status;
7558 }
Eric Laurent81784c32012-11-19 14:55:58 -08007559}
7560
Eric Laurent81784c32012-11-19 14:55:58 -08007561void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7562{
7563 sp<SyncEvent> strongEvent = event.promote();
7564
7565 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007566 sp<RefBase> ptr = strongEvent->cookie().promote();
7567 if (ptr != 0) {
7568 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7569 recordTrack->handleSyncStartEvent(strongEvent);
7570 }
Eric Laurent81784c32012-11-19 14:55:58 -08007571 }
7572}
7573
Glenn Kastena8356f62013-07-25 14:37:52 -07007574bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007575 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007576 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007577 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007578 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007579 return false;
7580 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007581 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007582 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007583
7584 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7585 mWaitWorkCV.broadcast(); // signal thread to stop
7586 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007587 }
Andy Hungce685402018-10-05 17:23:27 -07007588
7589 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007590 ALOGV("Record stopped OK");
7591 return true;
7592 }
Andy Hungce685402018-10-05 17:23:27 -07007593
7594 // don't handle anything - we've been invalidated or restarted and in a different state
7595 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7596 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007597 return false;
7598}
7599
Glenn Kasten0f11b512014-01-31 16:18:54 -08007600bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007601{
7602 return false;
7603}
7604
Glenn Kasten0f11b512014-01-31 16:18:54 -08007605status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007606{
7607#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7608 if (!isValidSyncEvent(event)) {
7609 return BAD_VALUE;
7610 }
7611
Glenn Kastend848eb42016-03-08 13:42:11 -08007612 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007613 status_t ret = NAME_NOT_FOUND;
7614
7615 Mutex::Autolock _l(mLock);
7616
7617 for (size_t i = 0; i < mTracks.size(); i++) {
7618 sp<RecordTrack> track = mTracks[i];
7619 if (eventSession == track->sessionId()) {
7620 (void) track->setSyncEvent(event);
7621 ret = NO_ERROR;
7622 }
7623 }
7624 return ret;
7625#else
7626 return BAD_VALUE;
7627#endif
7628}
7629
jiabin653cc0a2018-01-17 17:54:10 -08007630status_t AudioFlinger::RecordThread::getActiveMicrophones(
7631 std::vector<media::MicrophoneInfo>* activeMicrophones)
7632{
7633 ALOGV("RecordThread::getActiveMicrophones");
7634 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007635 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7636 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007637}
7638
Paul McLean03a6e6a2018-12-04 10:54:13 -07007639status_t AudioFlinger::RecordThread::setMicrophoneDirection(audio_microphone_direction_t direction)
7640{
7641 ALOGV("RecordThread::setMicrophoneDirection");
7642 AutoMutex _l(mLock);
7643 return mInput->stream->setMicrophoneDirection(direction);
7644}
7645
7646status_t AudioFlinger::RecordThread::setMicrophoneFieldDimension(float zoom)
7647{
7648 ALOGV("RecordThread::setMicrophoneFieldDimension");
7649 AutoMutex _l(mLock);
7650 return mInput->stream->setMicrophoneFieldDimension(zoom);
7651}
7652
Kevin Rocard069c2712018-03-29 19:09:14 -07007653void AudioFlinger::RecordThread::updateMetadata_l()
7654{
7655 if (mInput == nullptr || mInput->stream == nullptr ||
7656 !mActiveTracks.readAndClearHasChanged()) {
7657 return;
7658 }
7659 StreamInHalInterface::SinkMetadata metadata;
7660 for (const sp<RecordTrack> &track : mActiveTracks) {
7661 // No track is invalid as this is called after prepareTrack_l in the same critical section
7662 metadata.tracks.push_back({
7663 .source = track->attributes().source,
7664 .gain = 1, // capture tracks do not have volumes
7665 });
7666 }
7667 mInput->stream->updateSinkMetadata(metadata);
7668}
7669
Eric Laurent81784c32012-11-19 14:55:58 -08007670// destroyTrack_l() must be called with ThreadBase::mLock held
7671void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7672{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007673 track->terminate();
7674 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007675 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007676 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007677 removeTrack_l(track);
7678 }
7679}
7680
7681void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7682{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007683 String8 result;
7684 track->appendDump(result, false /* active */);
7685 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7686
Eric Laurent81784c32012-11-19 14:55:58 -08007687 mTracks.remove(track);
7688 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007689 if (track->isFastTrack()) {
7690 ALOG_ASSERT(!mFastTrackAvail);
7691 mFastTrackAvail = true;
7692 }
Eric Laurent81784c32012-11-19 14:55:58 -08007693}
7694
7695void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7696{
7697 dumpInternals(fd, args);
7698 dumpTracks(fd, args);
7699 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007700 dprintf(fd, " Local log:\n");
7701 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007702}
7703
7704void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7705{
Glenn Kasten44182c22015-03-05 17:12:23 -08007706 dumpBase(fd, args);
7707
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007708 AudioStreamIn *input = mInput;
7709 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7710 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7711 input, flags, inputFlagsToString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007712 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007713 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007714 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007715 }
Andy Hungbfa64962017-06-12 14:43:19 -07007716
7717 if (input != nullptr) {
7718 dprintf(fd, " Hal stream dump:\n");
7719 (void)input->stream->dump(fd);
7720 }
7721
Mikhail Naganovf4a342a2018-12-04 08:55:41 -08007722 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hung7f39f562018-08-08 17:30:20 -07007723 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
Andy Hung20bd30b2018-06-01 15:39:35 -07007724 if (latencyMs != 0.) {
7725 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7726 } else {
7727 dprintf(fd, " NormalRecord latency ms: unavail\n");
7728 }
7729
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007730 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007731 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007732
Glenn Kasten2f90c512015-12-02 11:40:09 -08007733 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7734 // while we are dumping it. It may be inconsistent, but it won't mutate!
7735 // This is a large object so we place it on the heap.
7736 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007737 const std::unique_ptr<FastCaptureDumpState> copy =
7738 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007739 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007740}
7741
Glenn Kasten0f11b512014-01-31 16:18:54 -08007742void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007743{
Eric Laurent81784c32012-11-19 14:55:58 -08007744 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007745 size_t numtracks = mTracks.size();
7746 size_t numactive = mActiveTracks.size();
7747 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007748 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007749 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007750 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007751 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007752 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007753 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007754 for (size_t i = 0; i < numtracks ; ++i) {
7755 sp<RecordTrack> track = mTracks[i];
7756 if (track != 0) {
7757 bool active = mActiveTracks.indexOf(track) >= 0;
7758 if (active) {
7759 numactiveseen++;
7760 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007761 result.append(prefix);
7762 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007763 }
Eric Laurent81784c32012-11-19 14:55:58 -08007764 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007765 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007766 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007767 }
7768
Marco Nelissenb2208842014-02-07 14:00:50 -08007769 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007770 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007771 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007772 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007773 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007774 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007775 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007776 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007777 result.append(prefix);
7778 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007779 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007780 }
Eric Laurent81784c32012-11-19 14:55:58 -08007781
7782 }
7783 write(fd, result.string(), result.size());
7784}
7785
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007786void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7787{
7788 Mutex::Autolock _l(mLock);
7789 for (size_t i = 0; i < mTracks.size() ; i++) {
7790 sp<RecordTrack> track = mTracks[i];
7791 if (track != 0 && track->uid() == uid) {
7792 track->setSilenced(silenced);
7793 }
7794 }
7795}
Andy Hung73c02e42015-03-29 01:13:58 -07007796
7797void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7798{
7799 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7800 RecordThread *recordThread = (RecordThread *) threadBase.get();
7801 mRsmpInFront = recordThread->mRsmpInRear;
7802 mRsmpInUnrel = 0;
7803}
7804
7805void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7806 size_t *framesAvailable, bool *hasOverrun)
7807{
7808 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7809 RecordThread *recordThread = (RecordThread *) threadBase.get();
7810 const int32_t rear = recordThread->mRsmpInRear;
7811 const int32_t front = mRsmpInFront;
7812 const ssize_t filled = rear - front;
7813
7814 size_t framesIn;
7815 bool overrun = false;
7816 if (filled < 0) {
7817 // should not happen, but treat like a massive overrun and re-sync
7818 framesIn = 0;
7819 mRsmpInFront = rear;
7820 overrun = true;
7821 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7822 framesIn = (size_t) filled;
7823 } else {
7824 // client is not keeping up with server, but give it latest data
7825 framesIn = recordThread->mRsmpInFrames;
7826 mRsmpInFront = /* front = */ rear - framesIn;
7827 overrun = true;
7828 }
7829 if (framesAvailable != NULL) {
7830 *framesAvailable = framesIn;
7831 }
7832 if (hasOverrun != NULL) {
7833 *hasOverrun = overrun;
7834 }
7835}
7836
Eric Laurent81784c32012-11-19 14:55:58 -08007837// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007838status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007839 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007840{
Andy Hung73c02e42015-03-29 01:13:58 -07007841 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007842 if (threadBase == 0) {
7843 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007844 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007845 return NOT_ENOUGH_DATA;
7846 }
7847 RecordThread *recordThread = (RecordThread *) threadBase.get();
7848 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007849 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007850 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007851 // FIXME should not be P2 (don't want to increase latency)
7852 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007853 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007854 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007855 front &= recordThread->mRsmpInFramesP2 - 1;
7856 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007857 if (part1 > (size_t) filled) {
7858 part1 = filled;
7859 }
7860 size_t ask = buffer->frameCount;
7861 ALOG_ASSERT(ask > 0);
7862 if (part1 > ask) {
7863 part1 = ask;
7864 }
7865 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007866 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007867 buffer->raw = NULL;
7868 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007869 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007870 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007871 }
7872
Andy Hung57446612015-04-19 23:56:46 -07007873 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007874 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007875 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007876 return NO_ERROR;
7877}
7878
7879// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007880void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7881 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007882{
Glenn Kasten85948432013-08-19 12:09:05 -07007883 size_t stepCount = buffer->frameCount;
7884 if (stepCount == 0) {
7885 return;
7886 }
Andy Hung73c02e42015-03-29 01:13:58 -07007887 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7888 mRsmpInUnrel -= stepCount;
7889 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007890 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007891 buffer->frameCount = 0;
7892}
7893
Eric Laurentd8365c52017-07-16 15:27:05 -07007894void AudioFlinger::RecordThread::checkBtNrec()
7895{
7896 Mutex::Autolock _l(mLock);
7897 checkBtNrec_l();
7898}
7899
7900void AudioFlinger::RecordThread::checkBtNrec_l()
7901{
7902 // disable AEC and NS if the device is a BT SCO headset supporting those
7903 // pre processings
7904 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7905 mAudioFlinger->btNrecIsOff();
7906 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7907 for (size_t i = 0; i < mEffectChains.size(); i++) {
7908 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7909 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7910 }
7911 }
7912}
7913
Andy Hung97a893e2015-03-29 01:03:07 -07007914
Eric Laurent10351942014-05-08 18:49:52 -07007915bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7916 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007917{
7918 bool reconfig = false;
7919
Eric Laurent10351942014-05-08 18:49:52 -07007920 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007921
Eric Laurent10351942014-05-08 18:49:52 -07007922 audio_format_t reqFormat = mFormat;
7923 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007924 // 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 -07007925 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7926
7927 AudioParameter param = AudioParameter(keyValuePair);
7928 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007929
7930 // scope for AutoPark extends to end of method
7931 AutoPark<FastCapture> park(mFastCapture);
7932
Eric Laurent10351942014-05-08 18:49:52 -07007933 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7934 // channel count change can be requested. Do we mandate the first client defines the
7935 // HAL sampling rate and channel count or do we allow changes on the fly?
7936 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7937 samplingRate = value;
7938 reconfig = true;
7939 }
7940 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007941 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007942 status = BAD_VALUE;
7943 } else {
7944 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007945 reconfig = true;
7946 }
Eric Laurent10351942014-05-08 18:49:52 -07007947 }
7948 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7949 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007950 if (!audio_is_input_channel(mask) ||
7951 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007952 status = BAD_VALUE;
7953 } else {
7954 channelMask = mask;
7955 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007956 }
Eric Laurent10351942014-05-08 18:49:52 -07007957 }
7958 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7959 // do not accept frame count changes if tracks are open as the track buffer
7960 // size depends on frame count and correct behavior would not be guaranteed
7961 // if frame count is changed after track creation
7962 if (mActiveTracks.size() > 0) {
7963 status = INVALID_OPERATION;
7964 } else {
7965 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007966 }
Eric Laurent10351942014-05-08 18:49:52 -07007967 }
7968 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7969 // forward device change to effects that have requested to be
7970 // aware of attached audio device.
7971 for (size_t i = 0; i < mEffectChains.size(); i++) {
7972 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007973 }
Eric Laurent81784c32012-11-19 14:55:58 -08007974
Eric Laurent10351942014-05-08 18:49:52 -07007975 // store input device and output device but do not forward output device to audio HAL.
7976 // Note that status is ignored by the caller for output device
7977 // (see AudioFlinger::setParameters()
7978 if (audio_is_output_devices(value)) {
7979 mOutDevice = value;
7980 status = BAD_VALUE;
7981 } else {
7982 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007983 if (value != AUDIO_DEVICE_NONE) {
7984 mPrevInDevice = value;
7985 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007986 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007987 }
Eric Laurent10351942014-05-08 18:49:52 -07007988 }
7989 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7990 mAudioSource != (audio_source_t)value) {
7991 // forward device change to effects that have requested to be
7992 // aware of attached audio device.
7993 for (size_t i = 0; i < mEffectChains.size(); i++) {
7994 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007995 }
Eric Laurent10351942014-05-08 18:49:52 -07007996 mAudioSource = (audio_source_t)value;
7997 }
Glenn Kastene198c362013-08-13 09:13:36 -07007998
Eric Laurent10351942014-05-08 18:49:52 -07007999 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008000 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008001 if (status == INVALID_OPERATION) {
8002 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008003 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008004 }
8005 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008006 if (status == BAD_VALUE) {
8007 uint32_t sRate;
8008 audio_channel_mask_t channelMask;
8009 audio_format_t format;
8010 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8011 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8012 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8013 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8014 status = NO_ERROR;
8015 }
Eric Laurent81784c32012-11-19 14:55:58 -08008016 }
Eric Laurent10351942014-05-08 18:49:52 -07008017 if (status == NO_ERROR) {
8018 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008019 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008020 }
8021 }
Eric Laurent81784c32012-11-19 14:55:58 -08008022 }
Eric Laurent10351942014-05-08 18:49:52 -07008023
Eric Laurent81784c32012-11-19 14:55:58 -08008024 return reconfig;
8025}
8026
8027String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8028{
Eric Laurent81784c32012-11-19 14:55:58 -08008029 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008030 if (initCheck() == NO_ERROR) {
8031 String8 out_s8;
8032 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8033 return out_s8;
8034 }
Eric Laurent81784c32012-11-19 14:55:58 -08008035 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008036 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008037}
8038
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008039void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008040 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8041
8042 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008043
8044 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008045 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008046 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008047 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008048 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008049 desc->mChannelMask = mChannelMask;
8050 desc->mSamplingRate = mSampleRate;
8051 desc->mFormat = mFormat;
8052 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008053 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008054 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008055 break;
8056
Eric Laurent73e26b62015-04-27 16:55:58 -07008057 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008058 default:
8059 break;
8060 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008061 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008062}
8063
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008064void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008065{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008066 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8067 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008068 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008069 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8070 if (audio_is_linear_pcm(mFormat)) {
8071 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8072 mChannelCount, FCC_8);
8073 } else {
8074 // Can have more that FCC_8 channels in encoded streams.
8075 ALOGI("HAL format %#x is not linear pcm", mFormat);
8076 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008077 result = mInput->stream->getFrameSize(&mFrameSize);
8078 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8079 result = mInput->stream->getBufferSize(&mBufferSize);
8080 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008081 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008082 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
8083 "mBufferSize=%lld, mFrameCount=%lld",
8084 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
8085 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008086 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008087 // 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 -07008088 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008089 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008090 // A larger value should allow more old data to be read after a track calls start(),
8091 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008092 //
8093 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008094 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008095 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008096 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008097 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008098
8099 // TODO optimize audio capture buffer sizes ...
8100 // Here we calculate the size of the sliding buffer used as a source
8101 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8102 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8103 // be better to have it derived from the pipe depth in the long term.
8104 // The current value is higher than necessary. However it should not add to latency.
8105
Glenn Kasten85948432013-08-19 12:09:05 -07008106 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008107 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8108 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008109 // if posix_memalign fails, will segv here.
8110 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008111
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008112 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8113 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08008114}
8115
Glenn Kasten5f972c02014-01-13 09:59:31 -08008116uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008117{
8118 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008119 uint32_t result;
8120 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8121 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008122 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008123 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008124}
8125
Eric Laurent4c415062016-06-17 16:14:16 -07008126// hasAudioSession_l() must be called with ThreadBase::mLock held
8127uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08008128{
Eric Laurent81784c32012-11-19 14:55:58 -08008129 uint32_t result = 0;
8130 if (getEffectChain_l(sessionId) != 0) {
8131 result = EFFECT_SESSION;
8132 }
8133
8134 for (size_t i = 0; i < mTracks.size(); ++i) {
8135 if (sessionId == mTracks[i]->sessionId()) {
8136 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07008137 if (mTracks[i]->isFastTrack()) {
8138 result |= FAST_SESSION;
8139 }
Eric Laurent81784c32012-11-19 14:55:58 -08008140 break;
8141 }
8142 }
8143
8144 return result;
8145}
8146
Glenn Kastend848eb42016-03-08 13:42:11 -08008147KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008148{
Glenn Kastend848eb42016-03-08 13:42:11 -08008149 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008150 Mutex::Autolock _l(mLock);
8151 for (size_t j = 0; j < mTracks.size(); ++j) {
8152 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008153 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008154 if (ids.indexOfKey(sessionId) < 0) {
8155 ids.add(sessionId, true);
8156 }
8157 }
8158 return ids;
8159}
8160
8161AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8162{
8163 Mutex::Autolock _l(mLock);
8164 AudioStreamIn *input = mInput;
8165 mInput = NULL;
8166 return input;
8167}
8168
8169// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008170sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008171{
8172 if (mInput == NULL) {
8173 return NULL;
8174 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008175 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008176}
8177
8178status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8179{
8180 // only one chain per input thread
Eric Tan39ec8d62018-07-24 09:49:29 -07008181 if (!mEffectChains.isEmpty()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07008182 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08008183 return INVALID_OPERATION;
8184 }
8185 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008186 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008187 chain->setInBuffer(NULL);
8188 chain->setOutBuffer(NULL);
8189
8190 checkSuspendOnAddEffectChain_l(chain);
8191
Eric Laurent1b928682014-10-02 19:41:47 -07008192 // make sure enabled pre processing effects state is communicated to the HAL as we
8193 // just moved them to a new input stream.
8194 chain->syncHalEffectsState();
8195
Eric Laurent81784c32012-11-19 14:55:58 -08008196 mEffectChains.add(chain);
8197
8198 return NO_ERROR;
8199}
8200
8201size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8202{
8203 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
8204 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008205 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08008206 chain.get(), mEffectChains.size(), this);
8207 if (mEffectChains.size() == 1) {
8208 mEffectChains.removeAt(0);
8209 }
8210 return 0;
8211}
8212
Eric Laurent1c333e22014-05-20 10:48:17 -07008213status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8214 audio_patch_handle_t *handle)
8215{
8216 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008217
8218 // store new device and send to effects
8219 mInDevice = patch->sources[0].ext.device.type;
François Gaffie0c280aa2018-07-25 10:02:15 +02008220 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent296fb132015-05-01 11:38:42 -07008221 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07008222 for (size_t i = 0; i < mEffectChains.size(); i++) {
8223 mEffectChains[i]->setDevice_l(mInDevice);
8224 }
8225
Eric Laurentd8365c52017-07-16 15:27:05 -07008226 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008227
8228 // store new source and send to effects
8229 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8230 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008231 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008232 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008233 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008234 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008235
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008236 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008237 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8238 status = hwDevice->createAudioPatch(patch->num_sources,
8239 patch->sources,
8240 patch->num_sinks,
8241 patch->sinks,
8242 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008243 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008244 char *address;
8245 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8246 address = audio_device_address_to_parameter(
8247 patch->sources[0].ext.device.type,
8248 patch->sources[0].ext.device.address);
8249 } else {
8250 address = (char *)calloc(1, 1);
8251 }
8252 AudioParameter param = AudioParameter(String8(address));
8253 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008254 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008255 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008256 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008257 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008258 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008259 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008260 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008261
François Gaffie0c280aa2018-07-25 10:02:15 +02008262 if ((mInDevice != mPrevInDevice) || (mDeviceId != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008263 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8264 mPrevInDevice = mInDevice;
François Gaffie0c280aa2018-07-25 10:02:15 +02008265 mDeviceId = deviceId;
Eric Laurente8726fe2015-06-26 09:39:24 -07008266 }
Eric Laurent296fb132015-05-01 11:38:42 -07008267
Eric Laurent1c333e22014-05-20 10:48:17 -07008268 return status;
8269}
8270
8271status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8272{
8273 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008274
8275 mInDevice = AUDIO_DEVICE_NONE;
8276
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008277 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008278 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8279 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008280 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008281 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008282 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008283 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008284 }
8285 return status;
8286}
8287
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008288void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008289{
8290 Mutex::Autolock _l(mLock);
8291 mTracks.add(record);
8292}
8293
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008294void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008295{
8296 Mutex::Autolock _l(mLock);
8297 destroyTrack_l(record);
8298}
8299
Mikhail Naganovdc769682018-05-04 15:34:08 -07008300void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008301{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008302 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008303 config->role = AUDIO_PORT_ROLE_SINK;
8304 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8305 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008306 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8307 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8308 config->flags.input = mInput->flags;
8309 }
Eric Laurent83b88082014-06-20 18:31:16 -07008310}
Eric Laurent1c333e22014-05-20 10:48:17 -07008311
Eric Laurent6acd1d42017-01-04 14:23:29 -08008312// ----------------------------------------------------------------------------
8313// Mmap
8314// ----------------------------------------------------------------------------
8315
8316AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8317 : mThread(thread)
8318{
Phil Burk9fabbf82017-08-03 12:02:00 -07008319 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008320}
8321
8322AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8323{
Phil Burk9fabbf82017-08-03 12:02:00 -07008324 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008325}
8326
8327status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8328 struct audio_mmap_buffer_info *info)
8329{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008330 return mThread->createMmapBuffer(minSizeFrames, info);
8331}
8332
8333status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8334{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008335 return mThread->getMmapPosition(position);
8336}
8337
Eric Laurenta54f1282017-07-01 19:39:32 -07008338status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008339 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008340
8341{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008342 return mThread->start(client, handle);
8343}
8344
8345status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8346{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008347 return mThread->stop(handle);
8348}
8349
Eric Laurent18b57012017-02-13 16:23:52 -08008350status_t AudioFlinger::MmapThreadHandle::standby()
8351{
Eric Laurent18b57012017-02-13 16:23:52 -08008352 return mThread->standby();
8353}
8354
Eric Laurent6acd1d42017-01-04 14:23:29 -08008355
8356AudioFlinger::MmapThread::MmapThread(
8357 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8358 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8359 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8360 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008361 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008362 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008363 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008364 mActiveTracks(&this->mLocalLog),
8365 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8366 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008367{
Eric Laurent18b57012017-02-13 16:23:52 -08008368 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008369 readHalParameters_l();
8370}
8371
8372AudioFlinger::MmapThread::~MmapThread()
8373{
Eric Laurent18b57012017-02-13 16:23:52 -08008374 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008375}
8376
8377void AudioFlinger::MmapThread::onFirstRef()
8378{
8379 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8380}
8381
8382void AudioFlinger::MmapThread::disconnect()
8383{
Eric Laurent331679c2018-04-16 17:03:16 -07008384 ActiveTracks<MmapTrack> activeTracks;
8385 {
8386 Mutex::Autolock _l(mLock);
8387 for (const sp<MmapTrack> &t : mActiveTracks) {
8388 activeTracks.add(t);
8389 }
8390 }
8391 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008392 stop(t->portId());
8393 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008394 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008395 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008396 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008397 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008398 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008399 }
8400}
8401
8402
8403void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8404 audio_stream_type_t streamType __unused,
8405 audio_session_t sessionId,
8406 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008407 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008408 audio_port_handle_t portId)
8409{
8410 mAttr = *attr;
8411 mSessionId = sessionId;
8412 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008413 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008414 mPortId = portId;
8415}
8416
8417status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8418 struct audio_mmap_buffer_info *info)
8419{
8420 if (mHalStream == 0) {
8421 return NO_INIT;
8422 }
Eric Laurent18b57012017-02-13 16:23:52 -08008423 mStandby = true;
8424 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008425 return mHalStream->createMmapBuffer(minSizeFrames, info);
8426}
8427
8428status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8429{
8430 if (mHalStream == 0) {
8431 return NO_INIT;
8432 }
8433 return mHalStream->getMmapPosition(position);
8434}
8435
Eric Laurent331679c2018-04-16 17:03:16 -07008436status_t AudioFlinger::MmapThread::exitStandby()
8437{
8438 status_t ret = mHalStream->start();
8439 if (ret != NO_ERROR) {
8440 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8441 return ret;
8442 }
8443 mStandby = false;
8444 return NO_ERROR;
8445}
8446
Eric Laurenta54f1282017-07-01 19:39:32 -07008447status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008448 audio_port_handle_t *handle)
8449{
Eric Laurenta54f1282017-07-01 19:39:32 -07008450 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8451 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008452 if (mHalStream == 0) {
8453 return NO_INIT;
8454 }
8455
8456 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008457
Eric Laurenta54f1282017-07-01 19:39:32 -07008458 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008459 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008460 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008461 }
8462
8463 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8464
8465 audio_io_handle_t io = mId;
8466 if (isOutput()) {
8467 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8468 config.sample_rate = mSampleRate;
8469 config.channel_mask = mChannelMask;
8470 config.format = mFormat;
8471 audio_stream_type_t stream = streamType();
8472 audio_output_flags_t flags =
8473 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008474 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008475 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008476 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8477 mSessionId,
8478 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008479 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008480 client.clientUid,
8481 &config,
8482 flags,
8483 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008484 &portId,
8485 &secondaryOutputs);
8486 ALOGD_IF(!secondaryOutputs.empty(),
8487 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008488 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008489 audio_config_base_t config;
8490 config.sample_rate = mSampleRate;
8491 config.channel_mask = mChannelMask;
8492 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008493 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008494 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8495 mSessionId,
8496 client.clientPid,
8497 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008498 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008499 &config,
8500 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8501 &deviceId,
8502 &portId);
8503 }
8504 // APM should not chose a different input or output stream for the same set of attributes
8505 // and audo configuration
8506 if (ret != NO_ERROR || io != mId) {
8507 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8508 __FUNCTION__, ret, io, mId);
8509 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008510 }
8511
8512 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008513 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008514 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008515 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008516 }
8517
Eric Laurent331679c2018-04-16 17:03:16 -07008518 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008519 // abort if start is rejected by audio policy manager
8520 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008521 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008522 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008523 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008524 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008525 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008526 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008527 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008528 }
Eric Laurent331679c2018-04-16 17:03:16 -07008529 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008530 } else {
8531 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008532 }
8533 return PERMISSION_DENIED;
8534 }
8535
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008536 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8537 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008538 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008539
Eric Laurent4eb58f12018-12-07 16:41:02 -08008540 if (isOutput()) {
8541 // force volume update when a new track is added
8542 mHalVolFloat = -1.0f;
8543 } else if (!track->isSilenced_l()) {
8544 for (const sp<MmapTrack> &t : mActiveTracks) {
8545 if (t->isSilenced_l() && t->uid() != client.clientUid)
8546 t->invalidate();
8547 }
8548 }
8549
8550
Eric Laurent6acd1d42017-01-04 14:23:29 -08008551 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008552 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008553 if (chain != 0) {
8554 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8555 chain->incTrackCnt();
8556 chain->incActiveTrackCnt();
8557 }
8558
8559 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008560 broadcast_l();
8561
Eric Laurenta54f1282017-07-01 19:39:32 -07008562 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008563
8564 return NO_ERROR;
8565}
8566
8567status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8568{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008569 ALOGV("%s handle %d", __FUNCTION__, handle);
8570
8571 if (mHalStream == 0) {
8572 return NO_INIT;
8573 }
8574
Eric Laurenta54f1282017-07-01 19:39:32 -07008575 if (handle == mPortId) {
8576 mHalStream->stop();
8577 return NO_ERROR;
8578 }
8579
Eric Laurent331679c2018-04-16 17:03:16 -07008580 Mutex::Autolock _l(mLock);
8581
Eric Laurent6acd1d42017-01-04 14:23:29 -08008582 sp<MmapTrack> track;
8583 for (const sp<MmapTrack> &t : mActiveTracks) {
8584 if (handle == t->portId()) {
8585 track = t;
8586 break;
8587 }
8588 }
8589 if (track == 0) {
8590 return BAD_VALUE;
8591 }
8592
8593 mActiveTracks.remove(track);
8594
Eric Laurent331679c2018-04-16 17:03:16 -07008595 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008596 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008597 AudioSystem::stopOutput(track->portId());
8598 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008599 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008600 AudioSystem::stopInput(track->portId());
8601 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008602 }
Eric Laurent331679c2018-04-16 17:03:16 -07008603 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008604
8605 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8606 if (chain != 0) {
8607 chain->decActiveTrackCnt();
8608 chain->decTrackCnt();
8609 }
8610
8611 broadcast_l();
8612
Eric Laurent6acd1d42017-01-04 14:23:29 -08008613 return NO_ERROR;
8614}
8615
Eric Laurent18b57012017-02-13 16:23:52 -08008616status_t AudioFlinger::MmapThread::standby()
8617{
8618 ALOGV("%s", __FUNCTION__);
8619
8620 if (mHalStream == 0) {
8621 return NO_INIT;
8622 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008623 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008624 return INVALID_OPERATION;
8625 }
8626 mHalStream->standby();
8627 mStandby = true;
8628 releaseWakeLock();
8629 return NO_ERROR;
8630}
8631
Eric Laurent6acd1d42017-01-04 14:23:29 -08008632
8633void AudioFlinger::MmapThread::readHalParameters_l()
8634{
8635 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8636 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8637 mFormat = mHALFormat;
8638 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8639 result = mHalStream->getFrameSize(&mFrameSize);
8640 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8641 result = mHalStream->getBufferSize(&mBufferSize);
8642 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8643 mFrameCount = mBufferSize / mFrameSize;
8644}
8645
8646bool AudioFlinger::MmapThread::threadLoop()
8647{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008648 checkSilentMode_l();
8649
8650 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8651
8652 while (!exitPending())
8653 {
8654 Mutex::Autolock _l(mLock);
8655 Vector< sp<EffectChain> > effectChains;
8656
8657 if (mSignalPending) {
8658 // A signal was raised while we were unlocked
8659 mSignalPending = false;
8660 } else {
8661 if (mConfigEvents.isEmpty()) {
8662 // we're about to wait, flush the binder command buffer
8663 IPCThreadState::self()->flushCommands();
8664
8665 if (exitPending()) {
8666 break;
8667 }
8668
Eric Laurent6acd1d42017-01-04 14:23:29 -08008669 // wait until we have something to do...
8670 ALOGV("%s going to sleep", myName.string());
8671 mWaitWorkCV.wait(mLock);
8672 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008673
8674 checkSilentMode_l();
8675
8676 continue;
8677 }
8678 }
8679
8680 processConfigEvents_l();
8681
8682 processVolume_l();
8683
8684 checkInvalidTracks_l();
8685
8686 mActiveTracks.updatePowerState(this);
8687
Kevin Rocard069c2712018-03-29 19:09:14 -07008688 updateMetadata_l();
8689
Eric Laurent6acd1d42017-01-04 14:23:29 -08008690 lockEffectChains_l(effectChains);
8691 for (size_t i = 0; i < effectChains.size(); i ++) {
8692 effectChains[i]->process_l();
8693 }
8694 // enable changes in effect chain
8695 unlockEffectChains(effectChains);
8696 // Effect chains will be actually deleted here if they were removed from
8697 // mEffectChains list during mixing or effects processing
8698 }
8699
8700 threadLoop_exit();
8701
8702 if (!mStandby) {
8703 threadLoop_standby();
8704 mStandby = true;
8705 }
8706
Eric Laurent6acd1d42017-01-04 14:23:29 -08008707 ALOGV("Thread %p type %d exiting", this, mType);
8708 return false;
8709}
8710
8711// checkForNewParameter_l() must be called with ThreadBase::mLock held
8712bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8713 status_t& status)
8714{
8715 AudioParameter param = AudioParameter(keyValuePair);
8716 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008717 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008718 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008719 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008720 // forward device change to effects that have requested to be
8721 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008722 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008723 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008724 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008725 }
8726 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008727 if (audio_is_output_devices(device)) {
8728 mOutDevice = device;
8729 if (!isOutput()) {
8730 sendToHal = false;
8731 }
8732 } else {
8733 mInDevice = device;
8734 if (device != AUDIO_DEVICE_NONE) {
8735 mPrevInDevice = value;
8736 }
8737 // TODO: implement and call checkBtNrec_l();
8738 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008739 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008740 if (sendToHal) {
8741 status = mHalStream->setParameters(keyValuePair);
8742 } else {
8743 status = NO_ERROR;
8744 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008745
8746 return false;
8747}
8748
8749String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8750{
8751 Mutex::Autolock _l(mLock);
8752 String8 out_s8;
8753 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8754 return out_s8;
8755 }
8756 return String8();
8757}
8758
8759void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8760 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8761
8762 desc->mIoHandle = mId;
8763
8764 switch (event) {
8765 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008766 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008767 case AUDIO_INPUT_CONFIG_CHANGED:
8768 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008769 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008770 case AUDIO_OUTPUT_CONFIG_CHANGED:
8771 desc->mPatch = mPatch;
8772 desc->mChannelMask = mChannelMask;
8773 desc->mSamplingRate = mSampleRate;
8774 desc->mFormat = mFormat;
8775 desc->mFrameCount = mFrameCount;
8776 desc->mFrameCountHAL = mFrameCount;
8777 desc->mLatency = 0;
8778 break;
8779
8780 case AUDIO_INPUT_CLOSED:
8781 case AUDIO_OUTPUT_CLOSED:
8782 default:
8783 break;
8784 }
8785 mAudioFlinger->ioConfigChanged(event, desc, pid);
8786}
8787
8788status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8789 audio_patch_handle_t *handle)
8790{
8791 status_t status = NO_ERROR;
8792
8793 // store new device and send to effects
8794 audio_devices_t type = AUDIO_DEVICE_NONE;
8795 audio_port_handle_t deviceId;
8796 if (isOutput()) {
8797 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8798 type |= patch->sinks[i].ext.device.type;
8799 }
8800 deviceId = patch->sinks[0].id;
8801 } else {
8802 type = patch->sources[0].ext.device.type;
8803 deviceId = patch->sources[0].id;
8804 }
8805
8806 for (size_t i = 0; i < mEffectChains.size(); i++) {
8807 mEffectChains[i]->setDevice_l(type);
8808 }
8809
8810 if (isOutput()) {
8811 mOutDevice = type;
8812 } else {
8813 mInDevice = type;
8814 // store new source and send to effects
8815 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8816 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8817 for (size_t i = 0; i < mEffectChains.size(); i++) {
8818 mEffectChains[i]->setAudioSource_l(mAudioSource);
8819 }
8820 }
8821 }
8822
8823 if (mAudioHwDev->supportsAudioPatches()) {
8824 status = mHalDevice->createAudioPatch(patch->num_sources,
8825 patch->sources,
8826 patch->num_sinks,
8827 patch->sinks,
8828 handle);
8829 } else {
8830 char *address;
8831 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8832 //FIXME: we only support address on first sink with HAL version < 3.0
8833 address = audio_device_address_to_parameter(
8834 patch->sinks[0].ext.device.type,
8835 patch->sinks[0].ext.device.address);
8836 } else {
8837 address = (char *)calloc(1, 1);
8838 }
8839 AudioParameter param = AudioParameter(String8(address));
8840 free(address);
8841 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8842 if (!isOutput()) {
8843 param.addInt(String8(AudioParameter::keyInputSource),
8844 (int)patch->sinks[0].ext.mix.usecase.source);
8845 }
8846 status = mHalStream->setParameters(param.toString());
8847 *handle = AUDIO_PATCH_HANDLE_NONE;
8848 }
8849
François Gaffie0c280aa2018-07-25 10:02:15 +02008850 if (isOutput() && (mPrevOutDevice != mOutDevice || mDeviceId != deviceId)) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008851 mPrevOutDevice = type;
8852 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008853 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008854 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008855 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008856 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008857 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008858 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008859 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008860 }
François Gaffie0c280aa2018-07-25 10:02:15 +02008861 if (!isOutput() && (mPrevInDevice != mInDevice || mDeviceId != deviceId)) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008862 mPrevInDevice = type;
8863 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008864 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008865 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008866 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008867 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008868 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008869 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008870 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008871 }
8872 return status;
8873}
8874
8875status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8876{
8877 status_t status = NO_ERROR;
8878
8879 mInDevice = AUDIO_DEVICE_NONE;
8880
8881 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8882 supportsAudioPatches : false;
8883
8884 if (supportsAudioPatches) {
8885 status = mHalDevice->releaseAudioPatch(handle);
8886 } else {
8887 AudioParameter param;
8888 param.addInt(String8(AudioParameter::keyRouting), 0);
8889 status = mHalStream->setParameters(param.toString());
8890 }
8891 return status;
8892}
8893
Mikhail Naganovdc769682018-05-04 15:34:08 -07008894void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008895{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008896 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008897 if (isOutput()) {
8898 config->role = AUDIO_PORT_ROLE_SOURCE;
8899 config->ext.mix.hw_module = mAudioHwDev->handle();
8900 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8901 } else {
8902 config->role = AUDIO_PORT_ROLE_SINK;
8903 config->ext.mix.hw_module = mAudioHwDev->handle();
8904 config->ext.mix.usecase.source = mAudioSource;
8905 }
8906}
8907
8908status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8909{
8910 audio_session_t session = chain->sessionId();
8911
8912 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8913 // Attach all tracks with same session ID to this chain.
8914 // indicate all active tracks in the chain
8915 for (const sp<MmapTrack> &track : mActiveTracks) {
8916 if (session == track->sessionId()) {
8917 chain->incTrackCnt();
8918 chain->incActiveTrackCnt();
8919 }
8920 }
8921
8922 chain->setThread(this);
8923 chain->setInBuffer(nullptr);
8924 chain->setOutBuffer(nullptr);
8925 chain->syncHalEffectsState();
8926
8927 mEffectChains.add(chain);
8928 checkSuspendOnAddEffectChain_l(chain);
8929 return NO_ERROR;
8930}
8931
8932size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8933{
8934 audio_session_t session = chain->sessionId();
8935
8936 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8937
8938 for (size_t i = 0; i < mEffectChains.size(); i++) {
8939 if (chain == mEffectChains[i]) {
8940 mEffectChains.removeAt(i);
8941 // detach all active tracks from the chain
8942 // detach all tracks with same session ID from this chain
8943 for (const sp<MmapTrack> &track : mActiveTracks) {
8944 if (session == track->sessionId()) {
8945 chain->decActiveTrackCnt();
8946 chain->decTrackCnt();
8947 }
8948 }
8949 break;
8950 }
8951 }
8952 return mEffectChains.size();
8953}
8954
8955// hasAudioSession_l() must be called with ThreadBase::mLock held
8956uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8957{
8958 uint32_t result = 0;
8959 if (getEffectChain_l(sessionId) != 0) {
8960 result = EFFECT_SESSION;
8961 }
8962
8963 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8964 sp<MmapTrack> track = mActiveTracks[i];
8965 if (sessionId == track->sessionId()) {
8966 result |= TRACK_SESSION;
8967 if (track->isFastTrack()) {
8968 result |= FAST_SESSION;
8969 }
8970 break;
8971 }
8972 }
8973
8974 return result;
8975}
8976
8977void AudioFlinger::MmapThread::threadLoop_standby()
8978{
8979 mHalStream->standby();
8980}
8981
8982void AudioFlinger::MmapThread::threadLoop_exit()
8983{
Phil Burk7dce7282017-09-27 13:51:41 -07008984 // Do not call callback->onTearDown() because it is redundant for thread exit
8985 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008986}
8987
8988status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8989{
8990 return BAD_VALUE;
8991}
8992
8993bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8994{
8995 return false;
8996}
8997
8998status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8999 const effect_descriptor_t *desc, audio_session_t sessionId)
9000{
9001 // No global effect sessions on mmap threads
9002 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
9003 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
9004 desc->name, mThreadName);
9005 return BAD_VALUE;
9006 }
9007
9008 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9009 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9010 desc->name);
9011 return BAD_VALUE;
9012 }
9013 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009014 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9015 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009016 return BAD_VALUE;
9017 }
9018
9019 // Only allow effects without processing load or latency
9020 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9021 return BAD_VALUE;
9022 }
9023
9024 return NO_ERROR;
9025
9026}
9027
9028void AudioFlinger::MmapThread::checkInvalidTracks_l()
9029{
9030 for (const sp<MmapTrack> &track : mActiveTracks) {
9031 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009032 sp<MmapStreamCallback> callback = mCallback.promote();
9033 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009034 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009035 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009036 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009037 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9038 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9039 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009040 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009041 }
9042 }
9043}
9044
9045void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
9046{
9047 dumpInternals(fd, args);
9048 dumpTracks(fd, args);
9049 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009050 dprintf(fd, " Local log:\n");
9051 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009052}
9053
9054void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
9055{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009056 dumpBase(fd, args);
9057
9058 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9059 mAttr.content_type, mAttr.usage, mAttr.source);
9060 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009061 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009062 dprintf(fd, " No active clients\n");
9063 }
9064}
9065
9066void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
9067{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009068 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009069 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009070 dprintf(fd, " %zu Tracks\n", numtracks);
9071 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009072 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009073 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009074 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009075 for (size_t i = 0; i < numtracks ; ++i) {
9076 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009077 result.append(prefix);
9078 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009079 }
9080 } else {
9081 dprintf(fd, "\n");
9082 }
9083 write(fd, result.string(), result.size());
9084}
9085
9086AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9087 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9088 AudioHwDevice *hwDev, AudioStreamOut *output,
9089 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9090 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
9091 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009092 mStreamVolume(1.0),
9093 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009094 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009095{
9096 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9097 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9098 mMasterVolume = audioFlinger->masterVolume_l();
9099 mMasterMute = audioFlinger->masterMute_l();
9100 if (mAudioHwDev) {
9101 if (mAudioHwDev->canSetMasterVolume()) {
9102 mMasterVolume = 1.0;
9103 }
9104
9105 if (mAudioHwDev->canSetMasterMute()) {
9106 mMasterMute = false;
9107 }
9108 }
9109}
9110
9111void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9112 audio_stream_type_t streamType,
9113 audio_session_t sessionId,
9114 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009115 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009116 audio_port_handle_t portId)
9117{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009118 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009119 mStreamType = streamType;
9120}
9121
9122AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9123{
9124 Mutex::Autolock _l(mLock);
9125 AudioStreamOut *output = mOutput;
9126 mOutput = NULL;
9127 return output;
9128}
9129
9130void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9131{
9132 Mutex::Autolock _l(mLock);
9133 // Don't apply master volume in SW if our HAL can do it for us.
9134 if (mAudioHwDev &&
9135 mAudioHwDev->canSetMasterVolume()) {
9136 mMasterVolume = 1.0;
9137 } else {
9138 mMasterVolume = value;
9139 }
9140}
9141
9142void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9143{
9144 Mutex::Autolock _l(mLock);
9145 // Don't apply master mute in SW if our HAL can do it for us.
9146 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9147 mMasterMute = false;
9148 } else {
9149 mMasterMute = muted;
9150 }
9151}
9152
9153void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9154{
9155 Mutex::Autolock _l(mLock);
9156 if (stream == mStreamType) {
9157 mStreamVolume = value;
9158 broadcast_l();
9159 }
9160}
9161
9162float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9163{
9164 Mutex::Autolock _l(mLock);
9165 if (stream == mStreamType) {
9166 return mStreamVolume;
9167 }
9168 return 0.0f;
9169}
9170
9171void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9172{
9173 Mutex::Autolock _l(mLock);
9174 if (stream == mStreamType) {
9175 mStreamMute= muted;
9176 broadcast_l();
9177 }
9178}
9179
9180void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9181{
9182 Mutex::Autolock _l(mLock);
9183 if (streamType == mStreamType) {
9184 for (const sp<MmapTrack> &track : mActiveTracks) {
9185 track->invalidate();
9186 }
9187 broadcast_l();
9188 }
9189}
9190
9191void AudioFlinger::MmapPlaybackThread::processVolume_l()
9192{
9193 float volume;
9194
9195 if (mMasterMute || mStreamMute) {
9196 volume = 0;
9197 } else {
9198 volume = mMasterVolume * mStreamVolume;
9199 }
9200
9201 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009202
9203 // Convert volumes from float to 8.24
9204 uint32_t vol = (uint32_t)(volume * (1 << 24));
9205
9206 // Delegate volume control to effect in track effect chain if needed
9207 // only one effect chain can be present on DirectOutputThread, so if
9208 // there is one, the track is connected to it
9209 if (!mEffectChains.isEmpty()) {
9210 mEffectChains[0]->setVolume_l(&vol, &vol);
9211 volume = (float)vol / (1 << 24);
9212 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009213 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009214 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9215 mHalVolFloat = volume; // HW volume control worked, so update value.
9216 mNoCallbackWarningCount = 0;
9217 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009218 sp<MmapStreamCallback> callback = mCallback.promote();
9219 if (callback != 0) {
9220 int channelCount;
9221 if (isOutput()) {
9222 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9223 } else {
9224 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9225 }
9226 Vector<float> values;
9227 for (int i = 0; i < channelCount; i++) {
9228 values.add(volume);
9229 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009230 mHalVolFloat = volume; // SW volume control worked, so update value.
9231 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009232 mLock.unlock();
9233 callback->onVolumeChanged(mChannelMask, values);
9234 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009235 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009236 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9237 ALOGW("Could not set MMAP stream volume: no volume callback!");
9238 mNoCallbackWarningCount++;
9239 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009240 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009241 }
9242 }
9243}
9244
Kevin Rocard069c2712018-03-29 19:09:14 -07009245void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9246{
9247 if (mOutput == nullptr || mOutput->stream == nullptr ||
9248 !mActiveTracks.readAndClearHasChanged()) {
9249 return;
9250 }
9251 StreamOutHalInterface::SourceMetadata metadata;
9252 for (const sp<MmapTrack> &track : mActiveTracks) {
9253 // No track is invalid as this is called after prepareTrack_l in the same critical section
9254 metadata.tracks.push_back({
9255 .usage = track->attributes().usage,
9256 .content_type = track->attributes().content_type,
9257 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9258 });
9259 }
9260 mOutput->stream->updateSourceMetadata(metadata);
9261}
9262
Eric Laurent6acd1d42017-01-04 14:23:29 -08009263void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9264{
9265 if (!mMasterMute) {
9266 char value[PROPERTY_VALUE_MAX];
9267 if (property_get("ro.audio.silent", value, "0") > 0) {
9268 char *endptr;
9269 unsigned long ul = strtoul(value, &endptr, 0);
9270 if (*endptr == '\0' && ul != 0) {
9271 ALOGD("Silence is golden");
9272 // The setprop command will not allow a property to be changed after
9273 // the first time it is set, so we don't have to worry about un-muting.
9274 setMasterMute_l(true);
9275 }
9276 }
9277 }
9278}
9279
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009280void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9281{
9282 MmapThread::toAudioPortConfig(config);
9283 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9284 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9285 config->flags.output = mOutput->flags;
9286 }
9287}
9288
Eric Laurent6acd1d42017-01-04 14:23:29 -08009289void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9290{
9291 MmapThread::dumpInternals(fd, args);
9292
Glenn Kastend3bb6452016-12-05 18:14:37 -08009293 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9294 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009295 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9296}
9297
9298AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9299 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9300 AudioHwDevice *hwDev, AudioStreamIn *input,
9301 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9302 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9303 mInput(input)
9304{
9305 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9306 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9307}
9308
Eric Laurent331679c2018-04-16 17:03:16 -07009309status_t AudioFlinger::MmapCaptureThread::exitStandby()
9310{
Phil Burkf054fc32018-12-06 09:45:59 -08009311 {
9312 // mInput might have been cleared by clearInput()
9313 Mutex::Autolock _l(mLock);
9314 if (mInput != nullptr && mInput->stream != nullptr) {
9315 mInput->stream->setGain(1.0f);
9316 }
9317 }
Eric Laurent331679c2018-04-16 17:03:16 -07009318 return MmapThread::exitStandby();
9319}
9320
Eric Laurent6acd1d42017-01-04 14:23:29 -08009321AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9322{
9323 Mutex::Autolock _l(mLock);
9324 AudioStreamIn *input = mInput;
9325 mInput = NULL;
9326 return input;
9327}
Kevin Rocard069c2712018-03-29 19:09:14 -07009328
Eric Laurent331679c2018-04-16 17:03:16 -07009329
9330void AudioFlinger::MmapCaptureThread::processVolume_l()
9331{
9332 bool changed = false;
9333 bool silenced = false;
9334
9335 sp<MmapStreamCallback> callback = mCallback.promote();
9336 if (callback == 0) {
9337 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9338 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9339 mNoCallbackWarningCount++;
9340 }
9341 }
9342
9343 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9344 // track is silenced and unmute otherwise
9345 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9346 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9347 changed = true;
9348 silenced = mActiveTracks[i]->isSilenced_l();
9349 }
9350 }
9351
9352 if (changed) {
9353 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9354 }
9355}
9356
Kevin Rocard069c2712018-03-29 19:09:14 -07009357void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9358{
9359 if (mInput == nullptr || mInput->stream == nullptr ||
9360 !mActiveTracks.readAndClearHasChanged()) {
9361 return;
9362 }
9363 StreamInHalInterface::SinkMetadata metadata;
9364 for (const sp<MmapTrack> &track : mActiveTracks) {
9365 // No track is invalid as this is called after prepareTrack_l in the same critical section
9366 metadata.tracks.push_back({
9367 .source = track->attributes().source,
9368 .gain = 1, // capture tracks do not have volumes
9369 });
9370 }
9371 mInput->stream->updateSinkMetadata(metadata);
9372}
9373
Eric Laurent331679c2018-04-16 17:03:16 -07009374void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9375{
9376 Mutex::Autolock _l(mLock);
9377 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9378 if (mActiveTracks[i]->uid() == uid) {
9379 mActiveTracks[i]->setSilenced_l(silenced);
9380 broadcast_l();
9381 }
9382 }
9383}
9384
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009385void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9386{
9387 MmapThread::toAudioPortConfig(config);
9388 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9389 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9390 config->flags.input = mInput->flags;
9391 }
9392}
9393
Glenn Kasten63238ef2015-03-02 15:50:29 -08009394} // namespace android