blob: 8f181a4038ebb8b62152c96bd8affc8bab972a80 [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
Eric Laurent81784c32012-11-19 14:55:58 -0800460AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700461 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800462 : Thread(false /*canCallJava*/),
463 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700464 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700465 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800466 // are set by PlaybackThread::readOutputParameters_l() or
467 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700468 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800469 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700470 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
471 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800472 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700473 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800474 mSystemReady(systemReady),
475 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800476{
Eric Laurent296fb132015-05-01 11:38:42 -0700477 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800478}
479
480AudioFlinger::ThreadBase::~ThreadBase()
481{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700482 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700483 mConfigEvents.clear();
484
Eric Laurent81784c32012-11-19 14:55:58 -0800485 // do not lock the mutex in destructor
486 releaseWakeLock_l();
487 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800488 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800489 binder->unlinkToDeath(mDeathRecipient);
490 }
491}
492
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700493status_t AudioFlinger::ThreadBase::readyToRun()
494{
495 status_t status = initCheck();
496 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800497 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700498 } else {
499 ALOGE("No working audio driver found.");
500 }
501 return status;
502}
503
Eric Laurent81784c32012-11-19 14:55:58 -0800504void AudioFlinger::ThreadBase::exit()
505{
506 ALOGV("ThreadBase::exit");
507 // do any cleanup required for exit to succeed
508 preExit();
509 {
510 // This lock prevents the following race in thread (uniprocessor for illustration):
511 // if (!exitPending()) {
512 // // context switch from here to exit()
513 // // exit() calls requestExit(), what exitPending() observes
514 // // exit() calls signal(), which is dropped since no waiters
515 // // context switch back from exit() to here
516 // mWaitWorkCV.wait(...);
517 // // now thread is hung
518 // }
519 AutoMutex lock(mLock);
520 requestExit();
521 mWaitWorkCV.broadcast();
522 }
523 // When Thread::requestExitAndWait is made virtual and this method is renamed to
524 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
525 requestExitAndWait();
526}
527
528status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
529{
Eric Laurent81784c32012-11-19 14:55:58 -0800530 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
531 Mutex::Autolock _l(mLock);
532
Eric Laurent10351942014-05-08 18:49:52 -0700533 return sendSetParameterConfigEvent_l(keyValuePairs);
534}
535
536// sendConfigEvent_l() must be called with ThreadBase::mLock held
537// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
538status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
539{
540 status_t status = NO_ERROR;
541
Eric Laurent72e3f392015-05-20 14:43:50 -0700542 if (event->mRequiresSystemReady && !mSystemReady) {
543 event->mWaitStatus = false;
544 mPendingConfigEvents.add(event);
545 return status;
546 }
Eric Laurent10351942014-05-08 18:49:52 -0700547 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700548 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800549 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700550 mLock.unlock();
551 {
552 Mutex::Autolock _l(event->mLock);
553 while (event->mWaitStatus) {
554 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
555 event->mStatus = TIMED_OUT;
556 event->mWaitStatus = false;
557 }
558 }
559 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800560 }
Eric Laurent10351942014-05-08 18:49:52 -0700561 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800562 return status;
563}
564
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700565void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800566{
567 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700568 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800569}
570
571// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700572void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800573{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700574 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700575 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800576}
577
Mikhail Naganov83f04272017-02-07 10:45:09 -0800578void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700579{
580 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800581 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700582}
583
Eric Laurent81784c32012-11-19 14:55:58 -0800584// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800585void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
586 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800587{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800588 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700589 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800590}
591
Eric Laurent10351942014-05-08 18:49:52 -0700592// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
593status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800594{
Andy Hung2ddee192015-12-18 17:34:44 -0800595 sp<ConfigEvent> configEvent;
596 AudioParameter param(keyValuePair);
597 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700598 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800599 setMasterMono_l(value != 0);
600 if (param.size() == 1) {
601 return NO_ERROR; // should be a solo parameter - we don't pass down
602 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700603 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800604 configEvent = new SetParameterConfigEvent(param.toString());
605 } else {
606 configEvent = new SetParameterConfigEvent(keyValuePair);
607 }
Eric Laurent10351942014-05-08 18:49:52 -0700608 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700609}
610
Eric Laurent1c333e22014-05-20 10:48:17 -0700611status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
612 const struct audio_patch *patch,
613 audio_patch_handle_t *handle)
614{
615 Mutex::Autolock _l(mLock);
616 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
617 status_t status = sendConfigEvent_l(configEvent);
618 if (status == NO_ERROR) {
619 CreateAudioPatchConfigEventData *data =
620 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
621 *handle = data->mHandle;
622 }
623 return status;
624}
625
626status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
627 const audio_patch_handle_t handle)
628{
629 Mutex::Autolock _l(mLock);
630 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
631 return sendConfigEvent_l(configEvent);
632}
633
634
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700635// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700636void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700637{
Eric Laurent10351942014-05-08 18:49:52 -0700638 bool configChanged = false;
639
Eric Laurent81784c32012-11-19 14:55:58 -0800640 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700641 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700642 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800643 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700644 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700645 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700646 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
647 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800648 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700649 true /*asynchronous*/);
650 if (err != 0) {
651 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700652 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700653 }
654 } break;
655 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700656 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700657 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700658 } break;
659 case CFG_EVENT_SET_PARAMETER: {
660 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
661 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
662 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700663 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
664 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700665 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700666 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700667 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700668 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700669 CreateAudioPatchConfigEventData *data =
670 (CreateAudioPatchConfigEventData *)event->mData.get();
671 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700672 const audio_devices_t newDevice = getDevice();
673 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
Andy Hung9b181952019-02-25 14:53:36 -0800674 (unsigned)oldDevice, toString(oldDevice).c_str(),
675 (unsigned)newDevice, toString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700676 } break;
677 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700678 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700679 ReleaseAudioPatchConfigEventData *data =
680 (ReleaseAudioPatchConfigEventData *)event->mData.get();
681 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700682 const audio_devices_t newDevice = getDevice();
683 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
Andy Hung9b181952019-02-25 14:53:36 -0800684 (unsigned)oldDevice, toString(oldDevice).c_str(),
685 (unsigned)newDevice, toString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700686 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700687 default:
Eric Laurent10351942014-05-08 18:49:52 -0700688 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700689 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800690 }
Eric Laurent10351942014-05-08 18:49:52 -0700691 {
692 Mutex::Autolock _l(event->mLock);
693 if (event->mWaitStatus) {
694 event->mWaitStatus = false;
695 event->mCond.signal();
696 }
697 }
698 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
699 }
700
701 if (configChanged) {
702 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800703 }
Eric Laurent81784c32012-11-19 14:55:58 -0800704}
705
Marco Nelissenb2208842014-02-07 14:00:50 -0800706String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
707 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700708 const audio_channel_representation_t representation =
709 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700710
711 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800712 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700713 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
714 if (output) {
715 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
716 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
717 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
718 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
719 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
720 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
721 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
722 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
723 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
724 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
725 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
726 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
727 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
728 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
729 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
730 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
731 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
732 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700733 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
734 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800735 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
736 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700737 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
738 } else {
739 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
740 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
741 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
742 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
743 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
744 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
745 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
746 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
747 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
748 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
749 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
750 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700751 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
752 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
753 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
754 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
755 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
756 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700757 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
758 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
759 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
760 }
761 const int len = s.length();
762 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700763 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700764 s.unlockBuffer(len - 2); // remove trailing ", "
765 }
766 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800767 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700768 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
769 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
770 return s;
771 default:
772 s.appendFormat("unknown mask, representation:%d bits:%#x",
773 representation, audio_channel_mask_get_bits(mask));
774 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800775 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800776}
777
Glenn Kasten0f11b512014-01-31 16:18:54 -0800778void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800779{
780 const size_t SIZE = 256;
781 char buffer[SIZE];
782 String8 result;
783
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800784 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
785 this, mThreadName, getTid(), type(), threadTypeToString(type()));
786
Eric Laurent81784c32012-11-19 14:55:58 -0800787 bool locked = AudioFlinger::dumpTryLock(mLock);
788 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800789 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800790 }
791
Elliott Hughes87cebad2014-05-22 10:14:43 -0700792 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700793 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700794 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700795 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700796 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700797 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700798 dprintf(fd, " Channel count: %u\n", mChannelCount);
799 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800800 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700801 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700802 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700803 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800804 size_t numConfig = mConfigEvents.size();
805 if (numConfig) {
806 for (size_t i = 0; i < numConfig; i++) {
807 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700808 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800809 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700810 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800811 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700812 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800813 }
Andy Hung293558a2017-03-21 12:19:20 -0700814 // Note: output device may be used by capture threads for effects such as AEC.
Andy Hung9b181952019-02-25 14:53:36 -0800815 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, toString(mOutDevice).c_str());
816 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, toString(mInDevice).c_str());
817 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800818
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700819 // Dump timestamp statistics for the Thread types that support it.
820 if (mType == RECORD
821 || mType == MIXER
822 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700823 || mType == DIRECT
824 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700825 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700826 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700827 }
828
Andy Hung446f4df2019-02-21 12:26:41 -0800829 if (mLastIoBeginNs > 0) { // MMAP may not set this
830 dprintf(fd, " Last %s occurred (msecs): %lld\n",
831 isOutput() ? "write" : "read",
832 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
833 }
834
835 if (mProcessTimeMs.getN() > 0) {
836 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
837 }
838
839 if (mIoJitterMs.getN() > 0) {
840 dprintf(fd, " Hal %s jitter ms stats: %s\n",
841 isOutput() ? "write" : "read",
842 mIoJitterMs.toString().c_str());
843 }
844
Andy Hunge6c37112019-02-26 17:38:10 -0800845 if (mLatencyMs.getN() > 0) {
846 dprintf(fd, " Threadloop %s latency stats: %s\n",
847 isOutput() ? "write" : "read",
848 mLatencyMs.toString().c_str());
849 }
850
Eric Laurent81784c32012-11-19 14:55:58 -0800851 if (locked) {
852 mLock.unlock();
853 }
854}
855
856void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
857{
858 const size_t SIZE = 256;
859 char buffer[SIZE];
860 String8 result;
861
Marco Nelissenb2208842014-02-07 14:00:50 -0800862 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000863 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800864 write(fd, buffer, strlen(buffer));
865
Marco Nelissenb2208842014-02-07 14:00:50 -0800866 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800867 sp<EffectChain> chain = mEffectChains[i];
868 if (chain != 0) {
869 chain->dump(fd, args);
870 }
871 }
872}
873
Andy Hungdae27702016-10-31 14:01:16 -0700874void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800875{
876 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700877 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800878}
879
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100880String16 AudioFlinger::ThreadBase::getWakeLockTag()
881{
882 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800883 case MIXER:
884 return String16("AudioMix");
885 case DIRECT:
886 return String16("AudioDirectOut");
887 case DUPLICATING:
888 return String16("AudioDup");
889 case RECORD:
890 return String16("AudioIn");
891 case OFFLOAD:
892 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800893 case MMAP:
894 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800895 default:
896 ALOG_ASSERT(false);
897 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100898 }
899}
900
Andy Hungdae27702016-10-31 14:01:16 -0700901void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800902{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800903 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800904 if (mPowerManager != 0) {
905 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700906 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
907 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700908 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100909 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700910 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700911 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800912 if (status == NO_ERROR) {
913 mWakeLockToken = binder;
914 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800915 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800916 }
Wei Jia3f273d12015-11-24 09:06:49 -0800917
Andy Hung3f0c9022016-01-15 17:49:46 -0800918 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800919 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
920 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800921}
922
923void AudioFlinger::ThreadBase::releaseWakeLock()
924{
925 Mutex::Autolock _l(mLock);
926 releaseWakeLock_l();
927}
928
929void AudioFlinger::ThreadBase::releaseWakeLock_l()
930{
Andy Hung3f0c9022016-01-15 17:49:46 -0800931 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800933 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800934 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700935 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
936 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800937 }
938 mWakeLockToken.clear();
939 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800940}
941
942void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700943 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800944 // use checkService() to avoid blocking if power service is not up yet
945 sp<IBinder> binder =
946 defaultServiceManager()->checkService(String16("power"));
947 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800948 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800949 } else {
950 mPowerManager = interface_cast<IPowerManager>(binder);
951 binder->linkToDeath(mDeathRecipient);
952 }
953 }
954}
955
Andy Hungd01b0f12016-11-07 16:10:30 -0800956void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700958
959#if !LOG_NDEBUG
960 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800961 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700962 s << uid << " ";
963 }
964 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
965#endif
966
Andy Hung438e7572015-12-14 15:51:17 -0800967 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
968 if (mSystemReady) {
969 ALOGE("no wake lock to update, but system ready!");
970 } else {
971 ALOGW("no wake lock to update, system not ready yet");
972 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800973 return;
974 }
975 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800976 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
977 status_t status = mPowerManager->updateWakeLockUids(
978 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
979 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800980 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800981 }
982}
983
Eric Laurent81784c32012-11-19 14:55:58 -0800984void AudioFlinger::ThreadBase::clearPowerManager()
985{
986 Mutex::Autolock _l(mLock);
987 releaseWakeLock_l();
988 mPowerManager.clear();
989}
990
Glenn Kasten0f11b512014-01-31 16:18:54 -0800991void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800992{
993 sp<ThreadBase> thread = mThread.promote();
994 if (thread != 0) {
995 thread->clearPowerManager();
996 }
997 ALOGW("power manager service died !!!");
998}
999
Eric Laurent81784c32012-11-19 14:55:58 -08001000void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001001 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001002{
1003 sp<EffectChain> chain = getEffectChain_l(sessionId);
1004 if (chain != 0) {
1005 if (type != NULL) {
1006 chain->setEffectSuspended_l(type, suspend);
1007 } else {
1008 chain->setEffectSuspendedAll_l(suspend);
1009 }
1010 }
1011
1012 updateSuspendedSessions_l(type, suspend, sessionId);
1013}
1014
1015void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1016{
1017 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1018 if (index < 0) {
1019 return;
1020 }
1021
1022 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1023 mSuspendedSessions.valueAt(index);
1024
1025 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001026 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001027 for (int j = 0; j < desc->mRefCount; j++) {
1028 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1029 chain->setEffectSuspendedAll_l(true);
1030 } else {
1031 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1032 desc->mType.timeLow);
1033 chain->setEffectSuspended_l(&desc->mType, true);
1034 }
1035 }
1036 }
1037}
1038
1039void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1040 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001041 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001042{
1043 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1044
1045 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1046
1047 if (suspend) {
1048 if (index >= 0) {
1049 sessionEffects = mSuspendedSessions.valueAt(index);
1050 } else {
1051 mSuspendedSessions.add(sessionId, sessionEffects);
1052 }
1053 } else {
1054 if (index < 0) {
1055 return;
1056 }
1057 sessionEffects = mSuspendedSessions.valueAt(index);
1058 }
1059
1060
1061 int key = EffectChain::kKeyForSuspendAll;
1062 if (type != NULL) {
1063 key = type->timeLow;
1064 }
1065 index = sessionEffects.indexOfKey(key);
1066
1067 sp<SuspendedSessionDesc> desc;
1068 if (suspend) {
1069 if (index >= 0) {
1070 desc = sessionEffects.valueAt(index);
1071 } else {
1072 desc = new SuspendedSessionDesc();
1073 if (type != NULL) {
1074 desc->mType = *type;
1075 }
1076 sessionEffects.add(key, desc);
1077 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1078 }
1079 desc->mRefCount++;
1080 } else {
1081 if (index < 0) {
1082 return;
1083 }
1084 desc = sessionEffects.valueAt(index);
1085 if (--desc->mRefCount == 0) {
1086 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1087 sessionEffects.removeItemsAt(index);
1088 if (sessionEffects.isEmpty()) {
1089 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1090 sessionId);
1091 mSuspendedSessions.removeItem(sessionId);
1092 }
1093 }
1094 }
1095 if (!sessionEffects.isEmpty()) {
1096 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1097 }
1098}
1099
1100void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1101 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001102 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001103{
1104 Mutex::Autolock _l(mLock);
1105 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1106}
1107
1108void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1109 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001110 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001111{
1112 if (mType != RECORD) {
1113 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1114 // another session. This gives the priority to well behaved effect control panels
1115 // and applications not using global effects.
1116 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1117 // global effects
1118 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1119 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1120 }
1121 }
1122
1123 sp<EffectChain> chain = getEffectChain_l(sessionId);
1124 if (chain != 0) {
1125 chain->checkSuspendOnEffectEnabled(effect, enabled);
1126 }
1127}
1128
Eric Laurent4c415062016-06-17 16:14:16 -07001129// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1130status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1131 const effect_descriptor_t *desc, audio_session_t sessionId)
1132{
1133 // No global effect sessions on record threads
1134 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1135 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1136 desc->name, mThreadName);
1137 return BAD_VALUE;
1138 }
1139 // only pre processing effects on record thread
1140 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1141 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1142 desc->name, mThreadName);
1143 return BAD_VALUE;
1144 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001145
1146 // always allow effects without processing load or latency
1147 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1148 return NO_ERROR;
1149 }
1150
Eric Laurent4c415062016-06-17 16:14:16 -07001151 audio_input_flags_t flags = mInput->flags;
1152 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1153 if (flags & AUDIO_INPUT_FLAG_RAW) {
1154 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1155 desc->name, mThreadName);
1156 return BAD_VALUE;
1157 }
1158 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1159 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1160 desc->name, mThreadName);
1161 return BAD_VALUE;
1162 }
1163 }
1164 return NO_ERROR;
1165}
1166
1167// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1168status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1169 const effect_descriptor_t *desc, audio_session_t sessionId)
1170{
1171 // no preprocessing on playback threads
1172 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1173 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1174 " thread %s", desc->name, mThreadName);
1175 return BAD_VALUE;
1176 }
1177
Eric Laurent3e4de772017-07-16 16:55:08 -07001178 // always allow effects without processing load or latency
1179 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1180 return NO_ERROR;
1181 }
1182
Eric Laurent4c415062016-06-17 16:14:16 -07001183 switch (mType) {
1184 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001185#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001186 // Reject any effect on mixer multichannel sinks.
1187 // TODO: fix both format and multichannel issues with effects.
1188 if (mChannelCount != FCC_2) {
1189 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1190 " thread %s", desc->name, mChannelCount, mThreadName);
1191 return BAD_VALUE;
1192 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001193#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001194 audio_output_flags_t flags = mOutput->flags;
1195 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1196 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1197 // global effects are applied only to non fast tracks if they are SW
1198 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1199 break;
1200 }
1201 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1202 // only post processing on output stage session
1203 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1204 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1205 " on output stage session", desc->name);
1206 return BAD_VALUE;
1207 }
1208 } else {
1209 // no restriction on effects applied on non fast tracks
1210 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1211 break;
1212 }
1213 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001214
Eric Laurent4c415062016-06-17 16:14:16 -07001215 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1216 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1217 desc->name);
1218 return BAD_VALUE;
1219 }
1220 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1221 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1222 " in fast mode", desc->name);
1223 return BAD_VALUE;
1224 }
1225 }
1226 } break;
1227 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001228 // nothing actionable on offload threads, if the effect:
1229 // - is offloadable: the effect can be created
1230 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1231 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001232 break;
1233 case DIRECT:
1234 // Reject any effect on Direct output threads for now, since the format of
1235 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1236 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1237 desc->name, mThreadName);
1238 return BAD_VALUE;
1239 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001240#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001241 // Reject any effect on mixer multichannel sinks.
1242 // TODO: fix both format and multichannel issues with effects.
1243 if (mChannelCount != FCC_2) {
1244 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1245 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1246 return BAD_VALUE;
1247 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001248#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001249 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1250 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1251 " thread %s", desc->name, mThreadName);
1252 return BAD_VALUE;
1253 }
1254 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1255 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1256 " DUPLICATING thread %s", desc->name, mThreadName);
1257 return BAD_VALUE;
1258 }
1259 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1260 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1261 " DUPLICATING thread %s", desc->name, mThreadName);
1262 return BAD_VALUE;
1263 }
1264 break;
1265 default:
1266 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1267 }
1268
1269 return NO_ERROR;
1270}
1271
Eric Laurent81784c32012-11-19 14:55:58 -08001272// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1273sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1274 const sp<AudioFlinger::Client>& client,
1275 const sp<IEffectClient>& effectClient,
1276 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001277 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001278 effect_descriptor_t *desc,
1279 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001280 status_t *status,
1281 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001282{
1283 sp<EffectModule> effect;
1284 sp<EffectHandle> handle;
1285 status_t lStatus;
1286 sp<EffectChain> chain;
1287 bool chainCreated = false;
1288 bool effectCreated = false;
1289 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001290 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001291
1292 lStatus = initCheck();
1293 if (lStatus != NO_ERROR) {
1294 ALOGW("createEffect_l() Audio driver not initialized.");
1295 goto Exit;
1296 }
1297
Eric Laurent81784c32012-11-19 14:55:58 -08001298 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1299
1300 { // scope for mLock
1301 Mutex::Autolock _l(mLock);
1302
Eric Laurent4c415062016-06-17 16:14:16 -07001303 lStatus = checkEffectCompatibility_l(desc, sessionId);
1304 if (lStatus != NO_ERROR) {
1305 goto Exit;
1306 }
1307
Eric Laurent81784c32012-11-19 14:55:58 -08001308 // check for existing effect chain with the requested audio session
1309 chain = getEffectChain_l(sessionId);
1310 if (chain == 0) {
1311 // create a new chain for this session
1312 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1313 chain = new EffectChain(this, sessionId);
1314 addEffectChain_l(chain);
1315 chain->setStrategy(getStrategyForSession_l(sessionId));
1316 chainCreated = true;
1317 } else {
1318 effect = chain->getEffectFromDesc_l(desc);
1319 }
1320
1321 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1322
1323 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001324 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001325 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001326 lStatus = AudioSystem::registerEffect(
1327 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001328 if (lStatus != NO_ERROR) {
1329 goto Exit;
1330 }
1331 effectRegistered = true;
1332 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001333 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001334 if (lStatus != NO_ERROR) {
1335 goto Exit;
1336 }
1337 effectCreated = true;
1338
1339 effect->setDevice(mOutDevice);
1340 effect->setDevice(mInDevice);
1341 effect->setMode(mAudioFlinger->getMode());
1342 effect->setAudioSource(mAudioSource);
1343 }
1344 // create effect handle and connect it to effect module
1345 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001346 lStatus = handle->initCheck();
1347 if (lStatus == OK) {
1348 lStatus = effect->addHandle(handle.get());
1349 }
Eric Laurent81784c32012-11-19 14:55:58 -08001350 if (enabled != NULL) {
1351 *enabled = (int)effect->isEnabled();
1352 }
1353 }
1354
1355Exit:
1356 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1357 Mutex::Autolock _l(mLock);
1358 if (effectCreated) {
1359 chain->removeEffect_l(effect);
1360 }
1361 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001362 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001363 }
1364 if (chainCreated) {
1365 removeEffectChain_l(chain);
1366 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001367 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001368 }
1369
Glenn Kasten9156ef32013-08-06 15:39:08 -07001370 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001371 return handle;
1372}
1373
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001374void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1375 bool unpinIfLast)
1376{
1377 bool remove = false;
1378 sp<EffectModule> effect;
1379 {
1380 Mutex::Autolock _l(mLock);
1381
1382 effect = handle->effect().promote();
1383 if (effect == 0) {
1384 return;
1385 }
1386 // restore suspended effects if the disconnected handle was enabled and the last one.
1387 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1388 if (remove) {
1389 removeEffect_l(effect, true);
1390 }
1391 }
1392 if (remove) {
1393 mAudioFlinger->updateOrphanEffectChains(effect);
1394 AudioSystem::unregisterEffect(effect->id());
1395 if (handle->enabled()) {
1396 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1397 }
1398 }
1399}
1400
Glenn Kastend848eb42016-03-08 13:42:11 -08001401sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1402 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001403{
1404 Mutex::Autolock _l(mLock);
1405 return getEffect_l(sessionId, effectId);
1406}
1407
Glenn Kastend848eb42016-03-08 13:42:11 -08001408sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1409 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001410{
1411 sp<EffectChain> chain = getEffectChain_l(sessionId);
1412 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1413}
1414
1415// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1416// PlaybackThread::mLock held
1417status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1418{
1419 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001420 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001421 sp<EffectChain> chain = getEffectChain_l(sessionId);
1422 bool chainCreated = false;
1423
Eric Laurent5baf2af2013-09-12 17:37:00 -07001424 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001425 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001426 this, effect->desc().name, effect->desc().flags);
1427
Eric Laurent81784c32012-11-19 14:55:58 -08001428 if (chain == 0) {
1429 // create a new chain for this session
1430 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1431 chain = new EffectChain(this, sessionId);
1432 addEffectChain_l(chain);
1433 chain->setStrategy(getStrategyForSession_l(sessionId));
1434 chainCreated = true;
1435 }
1436 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1437
1438 if (chain->getEffectFromId_l(effect->id()) != 0) {
1439 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1440 this, effect->desc().name, chain.get());
1441 return BAD_VALUE;
1442 }
1443
Eric Laurent5baf2af2013-09-12 17:37:00 -07001444 effect->setOffloaded(mType == OFFLOAD, mId);
1445
Eric Laurent81784c32012-11-19 14:55:58 -08001446 status_t status = chain->addEffect_l(effect);
1447 if (status != NO_ERROR) {
1448 if (chainCreated) {
1449 removeEffectChain_l(chain);
1450 }
1451 return status;
1452 }
1453
1454 effect->setDevice(mOutDevice);
1455 effect->setDevice(mInDevice);
1456 effect->setMode(mAudioFlinger->getMode());
1457 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001458
Eric Laurent81784c32012-11-19 14:55:58 -08001459 return NO_ERROR;
1460}
1461
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001462void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001463
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001464 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001465 effect_descriptor_t desc = effect->desc();
1466 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1467 detachAuxEffect_l(effect->id());
1468 }
1469
1470 sp<EffectChain> chain = effect->chain().promote();
1471 if (chain != 0) {
1472 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001473 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001474 removeEffectChain_l(chain);
1475 }
1476 } else {
1477 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1478 }
1479}
1480
1481void AudioFlinger::ThreadBase::lockEffectChains_l(
1482 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1483{
1484 effectChains = mEffectChains;
1485 for (size_t i = 0; i < mEffectChains.size(); i++) {
1486 mEffectChains[i]->lock();
1487 }
1488}
1489
1490void AudioFlinger::ThreadBase::unlockEffectChains(
1491 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1492{
1493 for (size_t i = 0; i < effectChains.size(); i++) {
1494 effectChains[i]->unlock();
1495 }
1496}
1497
Glenn Kastend848eb42016-03-08 13:42:11 -08001498sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001499{
1500 Mutex::Autolock _l(mLock);
1501 return getEffectChain_l(sessionId);
1502}
1503
Glenn Kastend848eb42016-03-08 13:42:11 -08001504sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1505 const
Eric Laurent81784c32012-11-19 14:55:58 -08001506{
1507 size_t size = mEffectChains.size();
1508 for (size_t i = 0; i < size; i++) {
1509 if (mEffectChains[i]->sessionId() == sessionId) {
1510 return mEffectChains[i];
1511 }
1512 }
1513 return 0;
1514}
1515
1516void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1517{
1518 Mutex::Autolock _l(mLock);
1519 size_t size = mEffectChains.size();
1520 for (size_t i = 0; i < size; i++) {
1521 mEffectChains[i]->setMode_l(mode);
1522 }
1523}
1524
Mikhail Naganovdc769682018-05-04 15:34:08 -07001525void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001526{
1527 config->type = AUDIO_PORT_TYPE_MIX;
1528 config->ext.mix.handle = mId;
1529 config->sample_rate = mSampleRate;
1530 config->format = mFormat;
1531 config->channel_mask = mChannelMask;
1532 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1533 AUDIO_PORT_CONFIG_FORMAT;
1534}
1535
Eric Laurent72e3f392015-05-20 14:43:50 -07001536void AudioFlinger::ThreadBase::systemReady()
1537{
1538 Mutex::Autolock _l(mLock);
1539 if (mSystemReady) {
1540 return;
1541 }
1542 mSystemReady = true;
1543
1544 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1545 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1546 }
1547 mPendingConfigEvents.clear();
1548}
1549
Andy Hungdae27702016-10-31 14:01:16 -07001550template <typename T>
1551ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1552 ssize_t index = mActiveTracks.indexOf(track);
1553 if (index >= 0) {
1554 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1555 return index;
1556 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001557 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001558 mActiveTracksGeneration++;
1559 mLatestActiveTrack = track;
1560 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001561 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001562 return mActiveTracks.add(track);
1563}
1564
1565template <typename T>
1566ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1567 ssize_t index = mActiveTracks.remove(track);
1568 if (index < 0) {
1569 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1570 return index;
1571 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001572 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001573 mActiveTracksGeneration++;
1574 --mBatteryCounter[track->uid()].second;
1575 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001576 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001577#ifdef TEE_SINK
1578 track->dumpTee(-1 /* fd */, "_REMOVE");
1579#endif
Andy Hungdae27702016-10-31 14:01:16 -07001580 return index;
1581}
1582
1583template <typename T>
1584void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1585 for (const sp<T> &track : mActiveTracks) {
1586 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001587 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001588 }
1589 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001590 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001591 mActiveTracks.clear();
1592 mLatestActiveTrack.clear();
1593 mBatteryCounter.clear();
1594}
1595
1596template <typename T>
1597void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1598 sp<ThreadBase> thread, bool force) {
1599 // Updates ActiveTracks client uids to the thread wakelock.
1600 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1601 thread->updateWakeLockUids_l(getWakeLockUids());
1602 mLastActiveTracksGeneration = mActiveTracksGeneration;
1603 }
1604
1605 // Updates BatteryNotifier uids
1606 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1607 const uid_t uid = it->first;
1608 ssize_t &previous = it->second.first;
1609 ssize_t &current = it->second.second;
1610 if (current > 0) {
1611 if (previous == 0) {
1612 BatteryNotifier::getInstance().noteStartAudio(uid);
1613 }
1614 previous = current;
1615 ++it;
1616 } else if (current == 0) {
1617 if (previous > 0) {
1618 BatteryNotifier::getInstance().noteStopAudio(uid);
1619 }
1620 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1621 } else /* (current < 0) */ {
1622 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1623 }
1624 }
1625}
Eric Laurent83b88082014-06-20 18:31:16 -07001626
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001627template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001628bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1629 const bool hasChanged = mHasChanged;
1630 mHasChanged = false;
1631 return hasChanged;
1632}
1633
1634template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001635void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1636 const char *funcName, const sp<T> &track) const {
1637 if (mLocalLog != nullptr) {
1638 String8 result;
1639 track->appendDump(result, false /* active */);
1640 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1641 }
1642}
1643
Eric Laurent6acd1d42017-01-04 14:23:29 -08001644void AudioFlinger::ThreadBase::broadcast_l()
1645{
1646 // Thread could be blocked waiting for async
1647 // so signal it to handle state changes immediately
1648 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1649 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1650 mSignalPending = true;
1651 mWaitWorkCV.broadcast();
1652}
1653
Eric Laurent81784c32012-11-19 14:55:58 -08001654// ----------------------------------------------------------------------------
1655// Playback
1656// ----------------------------------------------------------------------------
1657
1658AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1659 AudioStreamOut* output,
1660 audio_io_handle_t id,
1661 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001662 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001663 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001664 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001665 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001666 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001667 mMixerBuffer(NULL),
1668 mMixerBufferSize(0),
1669 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1670 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001671 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001672 mEffectBuffer(NULL),
1673 mEffectBufferSize(0),
1674 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1675 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001676 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001677 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001678 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001679 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001680 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001681 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001682 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001683 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001684 mMixerStatus(MIXER_IDLE),
1685 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001686 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001687 mBytesRemaining(0),
1688 mCurrentWriteLength(0),
1689 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001690 mWriteAckSequence(0),
1691 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001692 mScreenState(AudioFlinger::mScreenState),
1693 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001694 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001695 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1696 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001697{
Glenn Kastend7dca052015-03-05 16:05:54 -08001698 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1699 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001700
1701 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1702 // it would be safer to explicitly pass initial masterVolume/masterMute as
1703 // parameter.
1704 //
1705 // If the HAL we are using has support for master volume or master mute,
1706 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1707 // and the mute set to false).
1708 mMasterVolume = audioFlinger->masterVolume_l();
1709 mMasterMute = audioFlinger->masterMute_l();
1710 if (mOutput && mOutput->audioHwDev) {
1711 if (mOutput->audioHwDev->canSetMasterVolume()) {
1712 mMasterVolume = 1.0;
1713 }
1714
1715 if (mOutput->audioHwDev->canSetMasterMute()) {
1716 mMasterMute = false;
1717 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001718 mIsMsdDevice = strcmp(
1719 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001720 }
1721
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001722 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001723
Andy Hungc8fddf32018-08-08 18:32:37 -07001724 // TODO: We may also match on address as well as device type for
1725 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
1726 if (type == MIXER || type == DIRECT) {
1727 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
1728 "audio.timestamp.corrected_output_devices",
1729 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1730 : AUDIO_DEVICE_NONE));
1731 }
1732
Eric Laurent223fd5c2014-11-11 13:43:36 -08001733 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001734 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001735 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001736 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001737 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1738 }
Eric Laurent98e38192018-02-15 18:31:53 -08001739 // Audio patch volume is always max
1740 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1741 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001742}
1743
1744AudioFlinger::PlaybackThread::~PlaybackThread()
1745{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001746 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001747 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001748 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001749 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001750}
1751
1752void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1753{
1754 dumpInternals(fd, args);
1755 dumpTracks(fd, args);
1756 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001757 dprintf(fd, " Local log:\n");
1758 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001759}
1760
Glenn Kasten0f11b512014-01-31 16:18:54 -08001761void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001762{
Eric Laurent81784c32012-11-19 14:55:58 -08001763 String8 result;
1764
Marco Nelissenb2208842014-02-07 14:00:50 -08001765 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001766 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1767 const stream_type_t *st = &mStreamTypes[i];
1768 if (i > 0) {
1769 result.appendFormat(", ");
1770 }
1771 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1772 if (st->mute) {
1773 result.append("M");
1774 }
1775 }
1776 result.append("\n");
1777 write(fd, result.string(), result.length());
1778 result.clear();
1779
Eric Laurent81784c32012-11-19 14:55:58 -08001780 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1781 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001782 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001783 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001784
1785 size_t numtracks = mTracks.size();
1786 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001787 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001788 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001789 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001790 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001791 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001792 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001793 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001794 for (size_t i = 0; i < numtracks; ++i) {
1795 sp<Track> track = mTracks[i];
1796 if (track != 0) {
1797 bool active = mActiveTracks.indexOf(track) >= 0;
1798 if (active) {
1799 numactiveseen++;
1800 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001801 result.append(prefix);
1802 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001803 }
1804 }
1805 } else {
1806 result.append("\n");
1807 }
1808 if (numactiveseen != numactive) {
1809 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001810 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001811 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001812 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001813 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001814 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001815 sp<Track> track = mActiveTracks[i];
1816 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001817 result.append(prefix);
1818 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001819 }
1820 }
1821 }
1822
1823 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001824}
1825
1826void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1827{
Glenn Kasten44182c22015-03-05 17:12:23 -08001828 dumpBase(fd, args);
1829
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07001830 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08001831 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
1832 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
1833 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
1834 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001835 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001836 dprintf(fd, " Total writes: %d\n", mNumWrites);
1837 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1838 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1839 dprintf(fd, " Suspend count: %d\n", mSuspended);
1840 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1841 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1842 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1843 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001844 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001845 AudioStreamOut *output = mOutput;
1846 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001847 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08001848 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001849 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1850 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1851 if (mPipeSink.get() != nullptr) {
1852 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1853 }
1854 if (output != nullptr) {
1855 dprintf(fd, " Hal stream dump:\n");
1856 (void)output->stream->dump(fd);
1857 }
Eric Laurent81784c32012-11-19 14:55:58 -08001858}
1859
1860// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001861
1862void AudioFlinger::PlaybackThread::onFirstRef()
1863{
Glenn Kastend7dca052015-03-05 16:05:54 -08001864 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001865}
1866
1867// ThreadBase virtuals
1868void AudioFlinger::PlaybackThread::preExit()
1869{
1870 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001871 // FIXME this is using hard-coded strings but in the future, this functionality will be
1872 // converted to use audio HAL extensions required to support tunneling
1873 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1874 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001875}
1876
1877// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1878sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1879 const sp<AudioFlinger::Client>& client,
1880 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001881 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001882 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001883 audio_format_t format,
1884 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001885 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001886 size_t *pNotificationFrameCount,
1887 uint32_t notificationsPerBuffer,
1888 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001889 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001890 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001891 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001892 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001893 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001894 status_t *status,
1895 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001896{
Glenn Kasten74935e42013-12-19 08:56:45 -08001897 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001898 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001899 sp<Track> track;
1900 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001901 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001902 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001903 uint32_t sampleRate;
1904
1905 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1906 lStatus = BAD_VALUE;
1907 goto Exit;
1908 }
Eric Laurent21da6472017-11-09 16:29:26 -08001909
1910 if (*pSampleRate == 0) {
1911 *pSampleRate = mSampleRate;
1912 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001913 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001914
1915 // special case for FAST flag considered OK if fast mixer is present
1916 if (hasFastMixer()) {
1917 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1918 }
1919
1920 // Check if requested flags are compatible with output stream flags
1921 if ((*flags & outputFlags) != *flags) {
1922 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1923 *flags, outputFlags);
1924 *flags = (audio_output_flags_t)(*flags & outputFlags);
1925 }
Eric Laurent81784c32012-11-19 14:55:58 -08001926
Eric Laurent81784c32012-11-19 14:55:58 -08001927 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001928 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001929 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001930 // PCM data
1931 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001932 // TODO: extract as a data library function that checks that a computationally
1933 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08001934 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07001935 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1936 (channelMask == AUDIO_CHANNEL_OUT_MONO
1937 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001938 // hardware sample rate
1939 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001940 // normal mixer has an associated fast mixer
1941 hasFastMixer() &&
1942 // there are sufficient fast track slots available
1943 (mFastTrackAvailMask != 0)
1944 // FIXME test that MixerThread for this fast track has a capable output HAL
1945 // FIXME add a permission test also?
1946 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001947 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1948 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001949 // read the fast track multiplier property the first time it is needed
1950 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1951 if (ok != 0) {
1952 ALOGE("%s pthread_once failed: %d", __func__, ok);
1953 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001954 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001955 }
Eric Laurent4c415062016-06-17 16:14:16 -07001956
1957 // check compatibility with audio effects.
1958 { // scope for mLock
1959 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001960 for (audio_session_t session : {
1961 AUDIO_SESSION_OUTPUT_STAGE,
1962 AUDIO_SESSION_OUTPUT_MIX,
1963 sessionId,
1964 }) {
1965 sp<EffectChain> chain = getEffectChain_l(session);
1966 if (chain.get() != nullptr) {
1967 audio_output_flags_t old = *flags;
1968 chain->checkOutputFlagCompatibility(flags);
1969 if (old != *flags) {
1970 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1971 (int)session, (int)old, (int)*flags);
1972 }
Eric Laurent4c415062016-06-17 16:14:16 -07001973 }
1974 }
1975 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001976 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001977 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1978 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001979 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001980 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1981 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001982 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001983 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001984 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001985 audio_is_linear_pcm(format),
1986 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001987 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001988 }
1989 }
Eric Laurent21da6472017-11-09 16:29:26 -08001990
1991 if (!audio_has_proportional_frames(format)) {
1992 if (sharedBuffer != 0) {
1993 // Same comment as below about ignoring frameCount parameter for set()
1994 frameCount = sharedBuffer->size();
1995 } else if (frameCount == 0) {
1996 frameCount = mNormalFrameCount;
1997 }
1998 if (notificationFrameCount != frameCount) {
1999 notificationFrameCount = frameCount;
2000 }
2001 } else if (sharedBuffer != 0) {
2002 // FIXME: Ensure client side memory buffers need
2003 // not have additional alignment beyond sample
2004 // (e.g. 16 bit stereo accessed as 32 bit frame).
2005 size_t alignment = audio_bytes_per_sample(format);
2006 if (alignment & 1) {
2007 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2008 alignment = 1;
2009 }
2010 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2011 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2012 if (channelCount > 1) {
2013 // More than 2 channels does not require stronger alignment than stereo
2014 alignment <<= 1;
2015 }
2016 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2017 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2018 sharedBuffer->pointer(), channelCount);
2019 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002020 goto Exit;
2021 }
Eric Laurent21da6472017-11-09 16:29:26 -08002022
2023 // When initializing a shared buffer AudioTrack via constructors,
2024 // there's no frameCount parameter.
2025 // But when initializing a shared buffer AudioTrack via set(),
2026 // there _is_ a frameCount parameter. We silently ignore it.
2027 frameCount = sharedBuffer->size() / frameSize;
2028 } else {
2029 size_t minFrameCount = 0;
2030 // For fast tracks we try to respect the application's request for notifications per buffer.
2031 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2032 if (notificationsPerBuffer > 0) {
2033 // Avoid possible arithmetic overflow during multiplication.
2034 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2035 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2036 notificationsPerBuffer, mFrameCount);
2037 } else {
2038 minFrameCount = mFrameCount * notificationsPerBuffer;
2039 }
2040 }
2041 } else {
2042 // For normal PCM streaming tracks, update minimum frame count.
2043 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2044 // cover audio hardware latency.
2045 // This is probably too conservative, but legacy application code may depend on it.
2046 // If you change this calculation, also review the start threshold which is related.
2047 uint32_t latencyMs = latency_l();
2048 if (latencyMs == 0) {
2049 ALOGE("Error when retrieving output stream latency");
2050 lStatus = UNKNOWN_ERROR;
2051 goto Exit;
2052 }
2053
2054 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2055 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2056
Eric Laurent81784c32012-11-19 14:55:58 -08002057 }
Eric Laurent21da6472017-11-09 16:29:26 -08002058 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002059 frameCount = minFrameCount;
2060 }
Eric Laurent81784c32012-11-19 14:55:58 -08002061 }
Eric Laurent21da6472017-11-09 16:29:26 -08002062
2063 // Make sure that application is notified with sufficient margin before underrun.
2064 // The client can divide the AudioTrack buffer into sub-buffers,
2065 // and expresses its desire to server as the notification frame count.
2066 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2067 size_t maxNotificationFrames;
2068 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2069 // notify every HAL buffer, regardless of the size of the track buffer
2070 maxNotificationFrames = mFrameCount;
2071 } else {
2072 // For normal tracks, use at least double-buffering if no sample rate conversion,
2073 // or at least triple-buffering if there is sample rate conversion
2074 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2075 maxNotificationFrames = frameCount / nBuffering;
2076 // If client requested a fast track but this was denied, then use the smaller maximum.
2077 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2078 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2079 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2080 maxNotificationFrames = maxNotificationFramesFastDenied;
2081 }
2082 }
2083 }
2084 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2085 if (notificationFrameCount == 0) {
2086 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2087 maxNotificationFrames, frameCount);
2088 } else {
2089 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2090 notificationFrameCount, maxNotificationFrames, frameCount);
2091 }
2092 notificationFrameCount = maxNotificationFrames;
2093 }
2094 }
2095
Glenn Kasten74935e42013-12-19 08:56:45 -08002096 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002097 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002098
Glenn Kastenc3df8382014-03-13 15:05:25 -07002099 switch (mType) {
2100
2101 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002102 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002103 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002104 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2105 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002106 sampleRate, format, channelMask, mOutput, mFormat);
2107 lStatus = BAD_VALUE;
2108 goto Exit;
2109 }
2110 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002111 break;
2112
2113 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002114 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002115 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2116 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002117 sampleRate, format, channelMask, mOutput, mFormat);
2118 lStatus = BAD_VALUE;
2119 goto Exit;
2120 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002121 break;
2122
2123 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002124 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002125 ALOGE("createTrack_l() Bad parameter: format %#x \""
2126 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002127 format, mOutput, mFormat);
2128 lStatus = BAD_VALUE;
2129 goto Exit;
2130 }
Andy Hungcd044842014-08-07 11:04:34 -07002131 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002132 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2133 lStatus = BAD_VALUE;
2134 goto Exit;
2135 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002136 break;
2137
Eric Laurent81784c32012-11-19 14:55:58 -08002138 }
2139
2140 lStatus = initCheck();
2141 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002142 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002143 goto Exit;
2144 }
2145
2146 { // scope for mLock
2147 Mutex::Autolock _l(mLock);
2148
2149 // all tracks in same audio session must share the same routing strategy otherwise
2150 // conflicts will happen when tracks are moved from one output to another by audio policy
2151 // manager
2152 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2153 for (size_t i = 0; i < mTracks.size(); ++i) {
2154 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002155 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002156 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2157 if (sessionId == t->sessionId() && strategy != actual) {
2158 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2159 strategy, actual);
2160 lStatus = BAD_VALUE;
2161 goto Exit;
2162 }
2163 }
2164 }
2165
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002166 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002167 channelMask, frameCount,
2168 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002169 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002170
Glenn Kasten03003332013-08-06 15:40:54 -07002171 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2172 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002173 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002174 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002175 goto Exit;
2176 }
2177 mTracks.add(track);
2178
2179 sp<EffectChain> chain = getEffectChain_l(sessionId);
2180 if (chain != 0) {
2181 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2182 track->setMainBuffer(chain->inBuffer());
2183 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2184 chain->incTrackCnt();
2185 }
2186
Eric Laurent05067782016-06-01 18:27:28 -07002187 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002188 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2189 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2190 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002191 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002192 }
2193 }
2194
2195 lStatus = NO_ERROR;
2196
2197Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002198 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002199 return track;
2200}
2201
Andy Hung1bc088a2018-02-09 15:57:31 -08002202template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002203ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2204{
Andy Hungc0691382018-09-12 18:01:57 -07002205 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002206 const ssize_t index = mTracks.remove(track);
2207 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002208 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002209 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002210 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002211 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002212 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002213 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002214 }
2215 return index;
2216}
2217
Eric Laurent81784c32012-11-19 14:55:58 -08002218uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2219{
2220 return latency;
2221}
2222
2223uint32_t AudioFlinger::PlaybackThread::latency() const
2224{
2225 Mutex::Autolock _l(mLock);
2226 return latency_l();
2227}
2228uint32_t AudioFlinger::PlaybackThread::latency_l() const
2229{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002230 uint32_t latency;
2231 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2232 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002233 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002234 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002235}
2236
2237void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2238{
2239 Mutex::Autolock _l(mLock);
2240 // Don't apply master volume in SW if our HAL can do it for us.
2241 if (mOutput && mOutput->audioHwDev &&
2242 mOutput->audioHwDev->canSetMasterVolume()) {
2243 mMasterVolume = 1.0;
2244 } else {
2245 mMasterVolume = value;
2246 }
2247}
2248
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002249void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2250{
2251 mMasterBalance.store(balance);
2252}
2253
Eric Laurent81784c32012-11-19 14:55:58 -08002254void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2255{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002256 if (isDuplicating()) {
2257 return;
2258 }
Eric Laurent81784c32012-11-19 14:55:58 -08002259 Mutex::Autolock _l(mLock);
2260 // Don't apply master mute in SW if our HAL can do it for us.
2261 if (mOutput && mOutput->audioHwDev &&
2262 mOutput->audioHwDev->canSetMasterMute()) {
2263 mMasterMute = false;
2264 } else {
2265 mMasterMute = muted;
2266 }
2267}
2268
2269void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2270{
2271 Mutex::Autolock _l(mLock);
2272 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002273 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002274}
2275
2276void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2277{
2278 Mutex::Autolock _l(mLock);
2279 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002280 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002281}
2282
2283float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2284{
2285 Mutex::Autolock _l(mLock);
2286 return mStreamTypes[stream].volume;
2287}
2288
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002289void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2290{
2291 mOutput->stream->setVolume(left, right);
2292}
2293
Eric Laurent81784c32012-11-19 14:55:58 -08002294// addTrack_l() must be called with ThreadBase::mLock held
2295status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2296{
2297 status_t status = ALREADY_EXISTS;
2298
Eric Laurent81784c32012-11-19 14:55:58 -08002299 if (mActiveTracks.indexOf(track) < 0) {
2300 // the track is newly added, make sure it fills up all its
2301 // buffers before playing. This is to ensure the client will
2302 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002303 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002304 TrackBase::track_state state = track->mState;
2305 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002306 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002307 mLock.lock();
2308 // abort track was stopped/paused while we released the lock
2309 if (state != track->mState) {
2310 if (status == NO_ERROR) {
2311 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002312 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002313 mLock.lock();
2314 }
2315 return INVALID_OPERATION;
2316 }
2317 // abort if start is rejected by audio policy manager
2318 if (status != NO_ERROR) {
2319 return PERMISSION_DENIED;
2320 }
2321#ifdef ADD_BATTERY_DATA
2322 // to track the speaker usage
2323 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2324#endif
2325 }
2326
Eric Laurent51716182016-02-29 18:00:56 -08002327 // set retry count for buffer fill
2328 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002329 if (track->isStopping_1()) {
2330 track->mRetryCount = kMaxTrackStopRetriesOffload;
2331 } else {
2332 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2333 }
2334 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002335 } else {
2336 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002337 track->mFillingUpStatus =
2338 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002339 }
2340
jiabin245cdd92018-12-07 17:55:15 -08002341 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2342 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002343 // Unlock due to VibratorService will lock for this call and will
2344 // call Tracks.mute/unmute which also require thread's lock.
2345 mLock.unlock();
2346 const int intensity = AudioFlinger::onExternalVibrationStart(
2347 track->getExternalVibration());
2348 mLock.lock();
jiabinbf6b0ec2019-02-12 12:30:12 -08002349 track->setHapticIntensity(static_cast<AudioMixer::haptic_intensity_t>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002350 // Haptic playback should be enabled by vibrator service.
2351 if (track->getHapticPlaybackEnabled()) {
2352 // Disable haptic playback of all active track to ensure only
2353 // one track playing haptic if current track should play haptic.
2354 for (const auto &t : mActiveTracks) {
2355 t->setHapticPlaybackEnabled(false);
2356 }
jiabin245cdd92018-12-07 17:55:15 -08002357 }
jiabin245cdd92018-12-07 17:55:15 -08002358 }
2359
Eric Laurent81784c32012-11-19 14:55:58 -08002360 track->mResetDone = false;
2361 track->mPresentationCompleteFrames = 0;
2362 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002363 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2364 if (chain != 0) {
2365 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2366 track->sessionId());
2367 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002368 }
2369
2370 status = NO_ERROR;
2371 }
2372
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002373 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002374 return status;
2375}
2376
Eric Laurentbfb1b832013-01-07 09:53:42 -08002377bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002378{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002379 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002380 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002381 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2382 track->mState = TrackBase::STOPPED;
2383 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002384 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002385 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002386 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002387 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002388
2389 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002390}
2391
2392void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2393{
2394 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002395
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002396 String8 result;
2397 track->appendDump(result, false /* active */);
2398 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002399
Eric Laurent81784c32012-11-19 14:55:58 -08002400 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002401 if (track->isFastTrack()) {
2402 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002403 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002404 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2405 mFastTrackAvailMask |= 1 << index;
2406 // redundant as track is about to be destroyed, for dumpsys only
2407 track->mFastIndex = -1;
2408 }
2409 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2410 if (chain != 0) {
2411 chain->decTrackCnt();
2412 }
2413}
2414
2415String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2416{
Eric Laurent81784c32012-11-19 14:55:58 -08002417 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002418 String8 out_s8;
2419 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2420 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002421 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002422 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002423}
2424
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002425status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2426 Mutex::Autolock _l(mLock);
2427 if (mOutput == nullptr || mOutput->stream == nullptr) {
2428 return NO_INIT;
2429 }
2430 return mOutput->stream->selectPresentation(presentationId, programId);
2431}
2432
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002433void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002434 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2435 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002436
Eric Laurent73e26b62015-04-27 16:55:58 -07002437 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002438
2439 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002440 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002441 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002442 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002443 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002444 desc->mChannelMask = mChannelMask;
2445 desc->mSamplingRate = mSampleRate;
2446 desc->mFormat = mFormat;
2447 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002448 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002449 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002450 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002451 break;
2452
Eric Laurent73e26b62015-04-27 16:55:58 -07002453 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002454 default:
2455 break;
2456 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002457 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002458}
2459
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002460void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002461{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002462 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002463}
2464
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002465void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002466{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002467 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002468}
2469
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002470void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002471{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002472 mCallbackThread->setAsyncError();
2473}
2474
Eric Laurent3b4529e2013-09-05 18:09:19 -07002475void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002476{
2477 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002478 // reject out of sequence requests
2479 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2480 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 mWaitWorkCV.signal();
2482 }
2483}
2484
Eric Laurent3b4529e2013-09-05 18:09:19 -07002485void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002486{
2487 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002488 // reject out of sequence requests
2489 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002490 // Register discontinuity when HW drain is completed because that can cause
2491 // the timestamp frame position to reset to 0 for direct and offload threads.
2492 // (Out of sequence requests are ignored, since the discontinuity would be handled
2493 // elsewhere, e.g. in flush).
2494 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002495 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002496 mWaitWorkCV.signal();
2497 }
2498}
2499
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002500void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002501{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002502 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002503 mSampleRate = mOutput->getSampleRate();
2504 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002505 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002506 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002507 }
Andy Hung9a592762014-07-21 21:56:01 -07002508 if ((mType == MIXER || mType == DUPLICATING)
2509 && !isValidPcmSinkChannelMask(mChannelMask)) {
2510 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2511 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002512 }
Andy Hunge5412692014-05-16 11:25:07 -07002513 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002514 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002515
2516 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002517 status_t result = mOutput->stream->getFormat(&mHALFormat);
2518 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002519 // Get format from the shim, which will be different than the HAL format
2520 // if playing compressed audio over HDMI passthrough.
2521 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002522 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002523 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002524 }
Andy Hung6146c082014-03-18 11:56:15 -07002525 if ((mType == MIXER || mType == DUPLICATING)
2526 && !isValidPcmSinkFormat(mFormat)) {
2527 LOG_FATAL("HAL format %#x not supported for mixed output",
2528 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002529 }
Phil Burk062e67a2015-02-11 13:40:50 -08002530 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002531 result = mOutput->stream->getBufferSize(&mBufferSize);
2532 LOG_ALWAYS_FATAL_IF(result != OK,
2533 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002534 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002535 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002536 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002537 mFrameCount);
2538 }
2539
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002540 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2541 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002542 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002543 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002544 }
2545 }
2546
Eric Laurentd1f69b02014-12-15 14:33:13 -08002547 mHwSupportsPause = false;
2548 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002549 bool supportsPause = false, supportsResume = false;
2550 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2551 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002552 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002553 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002554 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002555 } else if (supportsResume) {
2556 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002557 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002558 }
2559 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002560 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2561 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2562 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002563
Andy Hungfbfc3952015-01-15 13:33:51 -08002564 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2565 // For best precision, we use float instead of the associated output
2566 // device format (typically PCM 16 bit).
2567
2568 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2569 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2570 mBufferSize = mFrameSize * mFrameCount;
2571
2572 // TODO: We currently use the associated output device channel mask and sample rate.
2573 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2574 // (if a valid mask) to avoid premature downmix.
2575 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2576 // instead of the output device sample rate to avoid loss of high frequency information.
2577 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2578 }
2579
Andy Hung09a50072014-02-27 14:30:47 -08002580 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002581 double multiplier = 1.0;
2582 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2583 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002584 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2585 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002586
Eric Laurent81784c32012-11-19 14:55:58 -08002587 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2588 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2589 maxNormalFrameCount = maxNormalFrameCount & ~15;
2590 if (maxNormalFrameCount < minNormalFrameCount) {
2591 maxNormalFrameCount = minNormalFrameCount;
2592 }
2593 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2594 if (multiplier <= 1.0) {
2595 multiplier = 1.0;
2596 } else if (multiplier <= 2.0) {
2597 if (2 * mFrameCount <= maxNormalFrameCount) {
2598 multiplier = 2.0;
2599 } else {
2600 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2601 }
2602 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002603 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002604 }
2605 }
2606 mNormalFrameCount = multiplier * mFrameCount;
2607 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002608 if (mType == MIXER || mType == DUPLICATING) {
2609 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2610 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002611 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002612 mNormalFrameCount);
2613
Andy Hung08fb1742015-05-31 23:22:10 -07002614 // Check if we want to throttle the processing to no more than 2x normal rate
2615 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002616 mThreadThrottleTimeMs = 0;
2617 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002618 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2619
Andy Hung010a1a12014-03-13 13:57:33 -07002620 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2621 // Originally this was int16_t[] array, need to remove legacy implications.
2622 free(mSinkBuffer);
2623 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002624 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2625 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2626 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002627 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002628
Andy Hung69aed5f2014-02-25 17:24:40 -08002629 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2630 // drives the output.
2631 free(mMixerBuffer);
2632 mMixerBuffer = NULL;
2633 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002634 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002635 mMixerBufferSize = mNormalFrameCount * mChannelCount
2636 * audio_bytes_per_sample(mMixerBufferFormat);
2637 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2638 }
Andy Hung98ef9782014-03-04 14:46:50 -08002639 free(mEffectBuffer);
2640 mEffectBuffer = NULL;
2641 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002642 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002643 mEffectBufferSize = mNormalFrameCount * mChannelCount
2644 * audio_bytes_per_sample(mEffectBufferFormat);
2645 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2646 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002647
jiabin245cdd92018-12-07 17:55:15 -08002648 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2649 mChannelMask &= ~mHapticChannelMask;
2650 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2651 mChannelCount -= mHapticChannelCount;
2652
Eric Laurent81784c32012-11-19 14:55:58 -08002653 // force reconfiguration of effect chains and engines to take new buffer size and audio
2654 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002655 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002656 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2657 // matter.
2658 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2659 Vector< sp<EffectChain> > effectChains = mEffectChains;
2660 for (size_t i = 0; i < effectChains.size(); i ++) {
2661 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2662 }
2663}
2664
Kevin Rocard069c2712018-03-29 19:09:14 -07002665void AudioFlinger::PlaybackThread::updateMetadata_l()
2666{
Kevin Rocard12381092018-04-11 09:19:59 -07002667 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2668 return; // That should not happen
2669 }
2670 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2671 for (const sp<Track> &track : mActiveTracks) {
2672 // Do not short-circuit as all hasChanged states must be reset
2673 // as all the metadata are going to be sent
2674 hasChanged |= track->readAndClearHasChanged();
2675 }
2676 if (!hasChanged) {
2677 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002678 }
2679 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002680 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002681 for (const sp<Track> &track : mActiveTracks) {
2682 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002683 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002684 }
Kevin Rocard12381092018-04-11 09:19:59 -07002685 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002686}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002687
Kevin Rocard12381092018-04-11 09:19:59 -07002688void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2689 const StreamOutHalInterface::SourceMetadata& metadata)
2690{
2691 mOutput->stream->updateSourceMetadata(metadata);
2692};
2693
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002694status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002695{
2696 if (halFrames == NULL || dspFrames == NULL) {
2697 return BAD_VALUE;
2698 }
2699 Mutex::Autolock _l(mLock);
2700 if (initCheck() != NO_ERROR) {
2701 return INVALID_OPERATION;
2702 }
Andy Hung818e7a32016-02-16 18:08:07 -08002703 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002704 *halFrames = framesWritten;
2705
2706 if (isSuspended()) {
2707 // return an estimation of rendered frames when the output is suspended
2708 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002709 *dspFrames = (uint32_t)
2710 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002711 return NO_ERROR;
2712 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002713 status_t status;
2714 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002715 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002716 *dspFrames = (size_t)frames;
2717 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002718 }
2719}
2720
Eric Laurent4c415062016-06-17 16:14:16 -07002721// hasAudioSession_l() must be called with ThreadBase::mLock held
2722uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002723{
Eric Laurent81784c32012-11-19 14:55:58 -08002724 uint32_t result = 0;
2725 if (getEffectChain_l(sessionId) != 0) {
2726 result = EFFECT_SESSION;
2727 }
2728
2729 for (size_t i = 0; i < mTracks.size(); ++i) {
2730 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002731 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002732 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002733 if (track->isFastTrack()) {
2734 result |= FAST_SESSION;
2735 }
Eric Laurent81784c32012-11-19 14:55:58 -08002736 break;
2737 }
2738 }
2739
2740 return result;
2741}
2742
Glenn Kastend848eb42016-03-08 13:42:11 -08002743uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002744{
2745 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2746 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2747 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2748 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2749 }
2750 for (size_t i = 0; i < mTracks.size(); i++) {
2751 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002752 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002753 return AudioSystem::getStrategyForStream(track->streamType());
2754 }
2755 }
2756 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2757}
2758
2759
Phil Burk062e67a2015-02-11 13:40:50 -08002760AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002761{
2762 Mutex::Autolock _l(mLock);
2763 return mOutput;
2764}
2765
Phil Burk062e67a2015-02-11 13:40:50 -08002766AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002767{
2768 Mutex::Autolock _l(mLock);
2769 AudioStreamOut *output = mOutput;
2770 mOutput = NULL;
2771 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2772 // must push a NULL and wait for ack
2773 mOutputSink.clear();
2774 mPipeSink.clear();
2775 mNormalSink.clear();
2776 return output;
2777}
2778
2779// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002780sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002781{
2782 if (mOutput == NULL) {
2783 return NULL;
2784 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002785 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002786}
2787
2788uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2789{
2790 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2791}
2792
2793status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2794{
2795 if (!isValidSyncEvent(event)) {
2796 return BAD_VALUE;
2797 }
2798
2799 Mutex::Autolock _l(mLock);
2800
2801 for (size_t i = 0; i < mTracks.size(); ++i) {
2802 sp<Track> track = mTracks[i];
2803 if (event->triggerSession() == track->sessionId()) {
2804 (void) track->setSyncEvent(event);
2805 return NO_ERROR;
2806 }
2807 }
2808
2809 return NAME_NOT_FOUND;
2810}
2811
2812bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2813{
2814 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2815}
2816
2817void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2818 const Vector< sp<Track> >& tracksToRemove)
2819{
Andy Hungfe726a62018-09-27 15:17:25 -07002820 // Miscellaneous track cleanup when removed from the active list,
2821 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002822#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002823 for (const auto& track : tracksToRemove) {
2824 if (track->isExternalTrack()) {
2825 // to track the speaker usage
2826 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002827 }
2828 }
Andy Hungfe726a62018-09-27 15:17:25 -07002829#else
2830 (void)tracksToRemove; // suppress unused warning
2831#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002832}
2833
2834void AudioFlinger::PlaybackThread::checkSilentMode_l()
2835{
2836 if (!mMasterMute) {
2837 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002838 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2839 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2840 return;
2841 }
Eric Laurent81784c32012-11-19 14:55:58 -08002842 if (property_get("ro.audio.silent", value, "0") > 0) {
2843 char *endptr;
2844 unsigned long ul = strtoul(value, &endptr, 0);
2845 if (*endptr == '\0' && ul != 0) {
2846 ALOGD("Silence is golden");
2847 // The setprop command will not allow a property to be changed after
2848 // the first time it is set, so we don't have to worry about un-muting.
2849 setMasterMute_l(true);
2850 }
2851 }
2852 }
2853}
2854
2855// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002856ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002857{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002858 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002859 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002860 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002861 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002862
2863 // If an NBAIO sink is present, use it to write the normal mixer's submix
2864 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002865
Andy Hung010a1a12014-03-13 13:57:33 -07002866 const size_t count = mBytesRemaining / mFrameSize;
2867
Simon Wilson2d590962012-11-29 15:18:50 -08002868 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002869 // update the setpoint when AudioFlinger::mScreenState changes
2870 uint32_t screenState = AudioFlinger::mScreenState;
2871 if (screenState != mScreenState) {
2872 mScreenState = screenState;
2873 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2874 if (pipe != NULL) {
2875 pipe->setAvgFrames((mScreenState & 1) ?
2876 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2877 }
2878 }
Andy Hung010a1a12014-03-13 13:57:33 -07002879 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002880 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002881 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002882 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002883#ifdef TEE_SINK
2884 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2885#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002886 } else {
2887 bytesWritten = framesWritten;
2888 }
2889 // otherwise use the HAL / AudioStreamOut directly
2890 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002892
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002894 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2895 mWriteAckSequence += 2;
2896 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002898 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002900 // FIXME We should have an implementation of timestamps for direct output threads.
2901 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002902 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002903
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 if (mUseAsyncWrite &&
2905 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2906 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002907 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002909 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002910 }
Eric Laurent81784c32012-11-19 14:55:58 -08002911 }
2912
Eric Laurent81784c32012-11-19 14:55:58 -08002913 mNumWrites++;
2914 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002915 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002916 return bytesWritten;
2917}
2918
2919void AudioFlinger::PlaybackThread::threadLoop_drain()
2920{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002921 bool supportsDrain = false;
2922 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002923 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2924 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002925 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2926 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002927 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002928 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002929 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002930 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002931 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002932 }
2933}
2934
2935void AudioFlinger::PlaybackThread::threadLoop_exit()
2936{
Eric Laurent275e8e92014-11-30 15:14:47 -08002937 {
2938 Mutex::Autolock _l(mLock);
2939 for (size_t i = 0; i < mTracks.size(); i++) {
2940 sp<Track> track = mTracks[i];
2941 track->invalidate();
2942 }
Andy Hungdae27702016-10-31 14:01:16 -07002943 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2944 // After we exit there are no more track changes sent to BatteryNotifier
2945 // because that requires an active threadLoop.
2946 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2947 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002948 }
Eric Laurent81784c32012-11-19 14:55:58 -08002949}
2950
2951/*
2952The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002953 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002954 - mActiveSleepTimeUs from activeSleepTimeUs()
2955 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002956 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2957 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002958 - maxPeriod from frame count and sample rate (MIXER only)
2959
2960The parameters that affect these derived values are:
2961 - frame count
2962 - frame size
2963 - sample rate
2964 - device type: A2DP or not
2965 - device latency
2966 - format: PCM or not
2967 - active sleep time
2968 - idle sleep time
2969*/
2970
2971void AudioFlinger::PlaybackThread::cacheParameters_l()
2972{
Andy Hung25c2dac2014-02-27 14:56:00 -08002973 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002974 mActiveSleepTimeUs = activeSleepTimeUs();
2975 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002976
2977 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2978 // truncating audio when going to standby.
2979 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2980 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2981 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2982 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2983 }
2984 }
Eric Laurent81784c32012-11-19 14:55:58 -08002985}
2986
Eric Laurent13084622016-05-17 10:51:49 -07002987bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002988{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002989 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002990 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002991 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002992 size_t size = mTracks.size();
2993 for (size_t i = 0; i < size; i++) {
2994 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002995 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002996 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002997 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002998 }
2999 }
Eric Laurent13084622016-05-17 10:51:49 -07003000 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003001}
3002
Haynes Mathew George05317d22016-05-03 16:34:26 -07003003void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3004{
3005 Mutex::Autolock _l(mLock);
3006 invalidateTracks_l(streamType);
3007}
3008
Eric Laurent81784c32012-11-19 14:55:58 -08003009status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3010{
Glenn Kastend848eb42016-03-08 13:42:11 -08003011 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003012 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003013 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003014 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3015 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3016 &halInBuffer);
3017 if (result != OK) return result;
3018 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003019 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003020 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003021 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003022 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003023 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003024 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003025 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003026 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003027 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003028 &halInBuffer);
3029 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003030#ifdef FLOAT_EFFECT_CHAIN
3031 buffer = halInBuffer->audioBuffer()->f32;
3032#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003033 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003034#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003035 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3036 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003037 }
3038
3039 // Attach all tracks with same session ID to this chain.
3040 for (size_t i = 0; i < mTracks.size(); ++i) {
3041 sp<Track> track = mTracks[i];
3042 if (session == track->sessionId()) {
3043 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3044 buffer);
3045 track->setMainBuffer(buffer);
3046 chain->incTrackCnt();
3047 }
3048 }
3049
3050 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003051 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003052 if (session == track->sessionId()) {
3053 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3054 chain->incActiveTrackCnt();
3055 }
3056 }
3057 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003058 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003059 chain->setInBuffer(halInBuffer);
3060 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003061 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003062 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003063 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3064 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003065 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003066 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003067 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003068 // Effect chain for other sessions are inserted at beginning of effect
3069 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003070 // sessions is not important.
3071 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3072 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3073 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003074 size_t size = mEffectChains.size();
3075 size_t i = 0;
3076 for (i = 0; i < size; i++) {
3077 if (mEffectChains[i]->sessionId() < session) {
3078 break;
3079 }
3080 }
3081 mEffectChains.insertAt(chain, i);
3082 checkSuspendOnAddEffectChain_l(chain);
3083
3084 return NO_ERROR;
3085}
3086
3087size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3088{
Glenn Kastend848eb42016-03-08 13:42:11 -08003089 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003090
3091 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3092
3093 for (size_t i = 0; i < mEffectChains.size(); i++) {
3094 if (chain == mEffectChains[i]) {
3095 mEffectChains.removeAt(i);
3096 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003097 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003098 if (session == track->sessionId()) {
3099 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3100 chain.get(), session);
3101 chain->decActiveTrackCnt();
3102 }
3103 }
3104
3105 // detach all tracks with same session ID from this chain
3106 for (size_t i = 0; i < mTracks.size(); ++i) {
3107 sp<Track> track = mTracks[i];
3108 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003109 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003110 chain->decTrackCnt();
3111 }
3112 }
3113 break;
3114 }
3115 }
3116 return mEffectChains.size();
3117}
3118
3119status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003120 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003121{
3122 Mutex::Autolock _l(mLock);
3123 return attachAuxEffect_l(track, EffectId);
3124}
3125
3126status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003127 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003128{
3129 status_t status = NO_ERROR;
3130
3131 if (EffectId == 0) {
3132 track->setAuxBuffer(0, NULL);
3133 } else {
3134 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3135 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3136 if (effect != 0) {
3137 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3138 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3139 } else {
3140 status = INVALID_OPERATION;
3141 }
3142 } else {
3143 status = BAD_VALUE;
3144 }
3145 }
3146 return status;
3147}
3148
3149void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3150{
3151 for (size_t i = 0; i < mTracks.size(); ++i) {
3152 sp<Track> track = mTracks[i];
3153 if (track->auxEffectId() == effectId) {
3154 attachAuxEffect_l(track, 0);
3155 }
3156 }
3157}
3158
3159bool AudioFlinger::PlaybackThread::threadLoop()
3160{
Glenn Kasten388d5712017-04-07 14:38:41 -07003161 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003162
Eric Laurent81784c32012-11-19 14:55:58 -08003163 Vector< sp<Track> > tracksToRemove;
3164
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003165 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003166 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
3167 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003168
3169 // MIXER
3170 nsecs_t lastWarning = 0;
3171
3172 // DUPLICATING
3173 // FIXME could this be made local to while loop?
3174 writeFrames = 0;
3175
3176 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003177 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003178
3179 if (mType == MIXER) {
3180 sleepTimeShift = 0;
3181 }
3182
3183 CpuStats cpuStats;
3184 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3185
3186 acquireWakeLock();
3187
Glenn Kasteneef598c2017-04-03 14:41:13 -07003188 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3189 // thread associated with this PlaybackThread.
3190 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3191 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003192 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3193 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003194 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003195 const char *logString = NULL;
3196
rago1bb90822017-05-02 18:31:48 -07003197 // Estimated time for next buffer to be written to hal. This is used only on
3198 // suspended mode (for now) to help schedule the wait time until next iteration.
3199 nsecs_t timeLoopNextNs = 0;
3200
Eric Laurent664539d2013-09-23 18:24:31 -07003201 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003202
Andy Hungf3234512018-07-03 14:51:47 -07003203 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3204 // TODO: add confirmation checks:
3205 // 1) DIRECT threads and linear PCM format really resets to 0?
3206 // 2) Is frame count really valid if not linear pcm?
3207 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3208 if (mType == OFFLOAD || mType == DIRECT) {
3209 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3210 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003211 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003212
Andy Hung446f4df2019-02-21 12:26:41 -08003213 // loopCount is used for statistics and diagnostics.
3214 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003215 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003216 // Log merge requests are performed during AudioFlinger binder transactions, but
3217 // that does not cover audio playback. It's requested here for that reason.
3218 mAudioFlinger->requestLogMerge();
3219
Eric Laurent81784c32012-11-19 14:55:58 -08003220 cpuStats.sample(myName);
3221
3222 Vector< sp<EffectChain> > effectChains;
3223
Andy Hung2dbffc22018-08-08 18:50:41 -07003224 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3225 //
3226 // Note: we access outDevice() outside of mLock.
3227 if (isMsdDevice() && (outDevice() & AUDIO_DEVICE_OUT_BUS) != 0) {
3228 // Here, we try for the AF lock, but do not block on it as the latency
3229 // is more informational.
3230 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3231 std::vector<PatchPanel::SoftwarePatch> swPatches;
3232 double latencyMs;
3233 status_t status = INVALID_OPERATION;
3234 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3235 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3236 && swPatches.size() > 0) {
3237 status = swPatches[0].getLatencyMs_l(&latencyMs);
3238 downstreamPatchHandle = swPatches[0].getPatchHandle();
3239 }
3240 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003241 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003242 lastDownstreamPatchHandle = downstreamPatchHandle;
3243 }
3244 if (status == OK) {
3245 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003246 // latency of 5 seconds).
3247 const double minLatency = 0., maxLatency = 5000.;
3248 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003249 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003250 } else {
3251 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003252 if (latencyMs < minLatency) latencyMs = minLatency;
3253 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003254 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003255 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003256 }
3257 mAudioFlinger->mLock.unlock();
3258 }
3259 } else {
3260 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3261 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003262 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003263 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3264 }
3265 }
3266
Eric Laurent81784c32012-11-19 14:55:58 -08003267 { // scope for mLock
3268
3269 Mutex::Autolock _l(mLock);
3270
Eric Laurent021cf962014-05-13 10:18:14 -07003271 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003272
Glenn Kasteneef598c2017-04-03 14:41:13 -07003273 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003274 if (logString != NULL) {
3275 mNBLogWriter->logTimestamp();
3276 mNBLogWriter->log(logString);
3277 logString = NULL;
3278 }
3279
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003280 // Collect timestamp statistics for the Playback Thread types that support it.
3281 if (mType == MIXER
3282 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003283 || mType == DIRECT
3284 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003285 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003286 // and associate with the sink frames written out. We need
3287 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003288 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003289 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003290 if (mStandby) {
3291 mTimestampVerifier.discontinuity();
3292 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3293 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3294 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3295 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003296
3297 if (isTimestampCorrectionEnabled()) {
3298 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3299 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3300 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3301 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3302 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3303 = correctedTimestamp.mFrames;
3304 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3305 = correctedTimestamp.mTimeNs;
3306 ALOGV("TS_AFTER: %d %lld %lld", id(),
3307 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3308 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003309
3310 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003311 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003312 const int64_t newPosition =
3313 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003314 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003315 // prevent retrograde
3316 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3317 newPosition,
3318 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3319 - mSuspendedFrames));
3320 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003321 }
3322
Andy Hung818e7a32016-02-16 18:08:07 -08003323 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003324 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003325
3326 // We keep track of the last valid kernel position in case we are in underrun
3327 // and the normal mixer period is the same as the fast mixer period, or there
3328 // is some error from the HAL.
3329 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3330 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3331 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3332 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3333 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3334
3335 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3336 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3337 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3338 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003339 }
3340
3341 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3342 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003343 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003344 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003345 }
3346
Andy Hung818e7a32016-02-16 18:08:07 -08003347 // copy over kernel info
3348 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003349 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3350 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003351 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3352 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003353 } else {
3354 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003355 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003356
Andy Hungc54b1ff2016-02-23 14:07:07 -08003357 // mFramesWritten for non-offloaded tracks are contiguous
3358 // even after standby() is called. This is useful for the track frame
3359 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003360 bool serverLocationUpdate = false;
3361 if (mFramesWritten != lastFramesWritten) {
3362 serverLocationUpdate = true;
3363 lastFramesWritten = mFramesWritten;
3364 }
3365 // Only update timestamps if there is a meaningful change.
3366 // Either the kernel timestamp must be valid or we have written something.
3367 if (kernelLocationUpdate || serverLocationUpdate) {
3368 if (serverLocationUpdate) {
3369 // use the time before we called the HAL write - it is a bit more accurate
3370 // to when the server last read data than the current time here.
3371 //
Andy Hung446f4df2019-02-21 12:26:41 -08003372 // If we haven't written anything, mLastIoBeginNs will be -1
Andy Hung69488c42016-05-16 18:43:33 -07003373 // and we use systemTime().
3374 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
Andy Hung446f4df2019-02-21 12:26:41 -08003375 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
3376 ? systemTime() : mLastIoBeginNs;
Andy Hung69488c42016-05-16 18:43:33 -07003377 }
Andy Hungdae27702016-10-31 14:01:16 -07003378
3379 for (const sp<Track> &t : mActiveTracks) {
3380 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003381 t->updateTrackFrameInfo(
3382 t->mAudioTrackServerProxy->framesReleased(),
3383 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003384 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003385 mTimestamp);
3386 }
Andy Hunge10393e2015-06-12 13:59:33 -07003387 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003388 }
Andy Hunge6c37112019-02-26 17:38:10 -08003389
3390 if (audio_has_proportional_frames(mFormat)) {
3391 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
3392 if (latencyMs != 0.) { // note 0. means timestamp is empty.
3393 mLatencyMs.add(latencyMs);
3394 }
3395 }
3396
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003397 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003398#if 0
3399 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003400 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003401 timespec ts;
3402 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003403 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003404 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003405 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003406 }
3407 ++z;
3408#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003409 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003410 if (mSignalPending) {
3411 // A signal was raised while we were unlocked
3412 mSignalPending = false;
3413 } else if (waitingAsyncCallback_l()) {
3414 if (exitPending()) {
3415 break;
3416 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003417 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003418 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003419 releaseWakeLock_l();
3420 released = true;
3421 }
Andy Hung10cbff12017-02-21 17:30:14 -08003422
3423 const int64_t waitNs = computeWaitTimeNs_l();
3424 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3425 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3426 if (status == TIMED_OUT) {
3427 mSignalPending = true; // if timeout recheck everything
3428 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003429 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003430 if (released) {
3431 acquireWakeLock_l();
3432 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003433 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3434 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003435
3436 continue;
3437 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003438 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003439 isSuspended()) {
3440 // put audio hardware into standby after short delay
3441 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003442
3443 threadLoop_standby();
3444
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003445 // This is where we go into standby
3446 if (!mStandby) {
3447 LOG_AUDIO_STATE();
3448 }
Eric Laurent81784c32012-11-19 14:55:58 -08003449 mStandby = true;
3450 }
3451
Eric Tan39ec8d62018-07-24 09:49:29 -07003452 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003453 // we're about to wait, flush the binder command buffer
3454 IPCThreadState::self()->flushCommands();
3455
3456 clearOutputTracks();
3457
3458 if (exitPending()) {
3459 break;
3460 }
3461
3462 releaseWakeLock_l();
3463 // wait until we have something to do...
3464 ALOGV("%s going to sleep", myName.string());
3465 mWaitWorkCV.wait(mLock);
3466 ALOGV("%s waking up", myName.string());
3467 acquireWakeLock_l();
3468
3469 mMixerStatus = MIXER_IDLE;
3470 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3471 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003472 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003473 checkSilentMode_l();
3474
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003475 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3476 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003477 if (mType == MIXER) {
3478 sleepTimeShift = 0;
3479 }
3480
3481 continue;
3482 }
3483 }
Eric Laurent81784c32012-11-19 14:55:58 -08003484 // mMixerStatusIgnoringFastTracks is also updated internally
3485 mMixerStatus = prepareTracks_l(&tracksToRemove);
3486
Andy Hungdae27702016-10-31 14:01:16 -07003487 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003488
Kevin Rocard069c2712018-03-29 19:09:14 -07003489 updateMetadata_l();
3490
Eric Laurent81784c32012-11-19 14:55:58 -08003491 // prevent any changes in effect chain list and in each effect chain
3492 // during mixing and effect process as the audio buffers could be deleted
3493 // or modified if an effect is created or deleted
3494 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003495 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003496
Eric Laurentbfb1b832013-01-07 09:53:42 -08003497 if (mBytesRemaining == 0) {
3498 mCurrentWriteLength = 0;
3499 if (mMixerStatus == MIXER_TRACKS_READY) {
3500 // threadLoop_mix() sets mCurrentWriteLength
3501 threadLoop_mix();
3502 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3503 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003504 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003505 // must be written to HAL
3506 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003507 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003508 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003509 }
3510 }
Andy Hung98ef9782014-03-04 14:46:50 -08003511 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003512 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003513 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3514 // or mSinkBuffer (if there are no effects).
3515 //
3516 // This is done pre-effects computation; if effects change to
3517 // support higher precision, this needs to move.
3518 //
3519 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003520 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003521 if (mMixerBufferValid) {
3522 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3523 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3524
Andy Hung2ddee192015-12-18 17:34:44 -08003525 // mono blend occurs for mixer threads only (not direct or offloaded)
3526 // and is handled here if we're going directly to the sink.
3527 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003528 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3529 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003530 }
3531
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003532 if (!hasFastMixer()) {
3533 // Balance must take effect after mono conversion.
3534 // We do it here if there is no FastMixer.
3535 // mBalance detects zero balance within the class for speed (not needed here).
3536 mBalance.setBalance(mMasterBalance.load());
3537 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3538 }
3539
Andy Hung98ef9782014-03-04 14:46:50 -08003540 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003541 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3542
3543 // If we're going directly to the sink and there are haptic channels,
3544 // we should adjust channels as the sample data is partially interleaved
3545 // in this case.
3546 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3547 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3548 mChannelCount + mHapticChannelCount,
3549 audio_bytes_per_sample(format),
3550 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3551 }
Andy Hung98ef9782014-03-04 14:46:50 -08003552 }
3553
Eric Laurentbfb1b832013-01-07 09:53:42 -08003554 mBytesRemaining = mCurrentWriteLength;
3555 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003556 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3557 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3558 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3559 mBytesWritten += mBytesRemaining;
3560 mFramesWritten += framesRemaining;
3561 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003562 mBytesRemaining = 0;
3563 }
Eric Laurent81784c32012-11-19 14:55:58 -08003564
Eric Laurentbfb1b832013-01-07 09:53:42 -08003565 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003566 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003567 for (size_t i = 0; i < effectChains.size(); i ++) {
3568 effectChains[i]->process_l();
3569 }
Eric Laurent81784c32012-11-19 14:55:58 -08003570 }
3571 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003572 // Process effect chains for offloaded thread even if no audio
3573 // was read from audio track: process only updates effect state
3574 // and thus does have to be synchronized with audio writes but may have
3575 // to be called while waiting for async write callback
3576 if (mType == OFFLOAD) {
3577 for (size_t i = 0; i < effectChains.size(); i ++) {
3578 effectChains[i]->process_l();
3579 }
3580 }
Eric Laurent81784c32012-11-19 14:55:58 -08003581
Andy Hung98ef9782014-03-04 14:46:50 -08003582 // Only if the Effects buffer is enabled and there is data in the
3583 // Effects buffer (buffer valid), we need to
3584 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003585 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003586 if (mEffectBufferValid) {
3587 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003588
3589 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003590 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3591 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003592 }
3593
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003594 if (!hasFastMixer()) {
3595 // Balance must take effect after mono conversion.
3596 // We do it here if there is no FastMixer.
3597 // mBalance detects zero balance within the class for speed (not needed here).
3598 mBalance.setBalance(mMasterBalance.load());
3599 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3600 }
3601
Andy Hung98ef9782014-03-04 14:46:50 -08003602 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003603 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3604 // The sample data is partially interleaved when haptic channels exist,
3605 // we need to adjust channels here.
3606 if (mHapticChannelCount > 0) {
3607 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3608 mChannelCount + mHapticChannelCount,
3609 audio_bytes_per_sample(mFormat),
3610 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3611 }
Andy Hung98ef9782014-03-04 14:46:50 -08003612 }
3613
Eric Laurent81784c32012-11-19 14:55:58 -08003614 // enable changes in effect chain
3615 unlockEffectChains(effectChains);
3616
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003618 // mSleepTimeUs == 0 means we must write to audio hardware
3619 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003620 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003621 // writePeriodNs is updated >= 0 when ret > 0.
3622 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003623 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003624 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003625 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003626 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003627 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003628 if (ret < 0) {
3629 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003630 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003631 mBytesWritten += ret;
3632 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003633 const int64_t frames = ret / mFrameSize;
3634 mFramesWritten += frames;
3635
3636 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3637 // process information relating to write time.
3638 if (audio_has_proportional_frames(mFormat)) {
3639 // we are in a continuous mixing cycle
3640 if (mMixerStatus == MIXER_TRACKS_READY &&
3641 loopCount == lastLoopCountWritten + 1) {
3642
3643 const double jitterMs =
3644 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3645 {frames, writePeriodNs},
3646 {0, 0} /* lastTimestamp */, mSampleRate);
3647 const double processMs =
3648 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3649
3650 Mutex::Autolock _l(mLock);
3651 mIoJitterMs.add(jitterMs);
3652 mProcessTimeMs.add(processMs);
3653 }
3654
3655 // write blocked detection
3656 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3657 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3658 mNumDelayedWrites++;
3659 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3660 ATRACE_NAME("underrun");
3661 ALOGW("write blocked for %lld msecs, "
3662 "%d delayed writes, thread %d",
3663 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3664 mNumDelayedWrites, mId);
3665 lastWarning = lastIoEndNs;
3666 }
3667 }
3668 }
3669 // update timing info.
3670 mLastIoBeginNs = lastIoBeginNs;
3671 mLastIoEndNs = lastIoEndNs;
3672 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003673 }
3674 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3675 (mMixerStatus == MIXER_DRAIN_ALL)) {
3676 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003677 }
Andy Hung08fb1742015-05-31 23:22:10 -07003678 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003679
3680 if (mThreadThrottle
3681 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003682 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003683 // Limit MixerThread data processing to no more than twice the
3684 // expected processing rate.
3685 //
3686 // This helps prevent underruns with NuPlayer and other applications
3687 // which may set up buffers that are close to the minimum size, or use
3688 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3689 //
3690 // The throttle smooths out sudden large data drains from the device,
3691 // e.g. when it comes out of standby, which often causes problems with
3692 // (1) mixer threads without a fast mixer (which has its own warm-up)
3693 // (2) minimum buffer sized tracks (even if the track is full,
3694 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003695 //
3696 // Total time spent in last processing cycle equals time spent in
3697 // 1. threadLoop_write, as well as time spent in
3698 // 2. threadLoop_mix (significant for heavy mixing, especially
3699 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003700
Andy Hung446f4df2019-02-21 12:26:41 -08003701 // it's OK if deltaMs is an overestimate.
3702
3703 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003704
Ivan Lozanoea04d392017-11-07 14:37:07 -08003705 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003706 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3707 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003708 // notify of throttle start on verbose log
3709 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3710 "mixer(%p) throttle begin:"
3711 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003712 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003713 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003714 // Throttle must be attributed to the previous mixer loop's write time
3715 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003716 // This also ensures proper timing statistics.
3717 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003718 } else {
3719 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3720 if (diff > 0) {
3721 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003722 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003723 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3724 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003725 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003726 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3727 }
Andy Hung08fb1742015-05-31 23:22:10 -07003728 }
3729 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003730 }
Eric Laurent81784c32012-11-19 14:55:58 -08003731
Eric Laurentbfb1b832013-01-07 09:53:42 -08003732 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003733 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003734 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003735 // suspended requires accurate metering of sleep time.
3736 if (isSuspended()) {
3737 // advance by expected sleepTime
3738 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3739 const nsecs_t nowNs = systemTime();
3740
3741 // compute expected next time vs current time.
3742 // (negative deltas are treated as delays).
3743 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3744 if (deltaNs < -kMaxNextBufferDelayNs) {
3745 // Delays longer than the max allowed trigger a reset.
3746 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3747 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3748 timeLoopNextNs = nowNs + deltaNs;
3749 } else if (deltaNs < 0) {
3750 // Delays within the max delay allowed: zero the delta/sleepTime
3751 // to help the system catch up in the next iteration(s)
3752 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3753 deltaNs = 0;
3754 }
3755 // update sleep time (which is >= 0)
3756 mSleepTimeUs = deltaNs / 1000;
3757 }
Eric Laurente93cc032016-05-05 10:15:10 -07003758 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3759 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003760 }
Glenn Kastene7754022014-10-31 12:11:26 -07003761 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003762 }
Eric Laurent81784c32012-11-19 14:55:58 -08003763 }
3764
3765 // Finally let go of removed track(s), without the lock held
3766 // since we can't guarantee the destructors won't acquire that
3767 // same lock. This will also mutate and push a new fast mixer state.
3768 threadLoop_removeTracks(tracksToRemove);
3769 tracksToRemove.clear();
3770
3771 // FIXME I don't understand the need for this here;
3772 // it was in the original code but maybe the
3773 // assignment in saveOutputTracks() makes this unnecessary?
3774 clearOutputTracks();
3775
3776 // Effect chains will be actually deleted here if they were removed from
3777 // mEffectChains list during mixing or effects processing
3778 effectChains.clear();
3779
3780 // FIXME Note that the above .clear() is no longer necessary since effectChains
3781 // is now local to this block, but will keep it for now (at least until merge done).
3782 }
3783
Eric Laurentbfb1b832013-01-07 09:53:42 -08003784 threadLoop_exit();
3785
Eric Laurentcf817a22014-08-04 20:36:31 -07003786 if (!mStandby) {
3787 threadLoop_standby();
3788 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003789 }
3790
3791 releaseWakeLock();
3792
3793 ALOGV("Thread %p type %d exiting", this, mType);
3794 return false;
3795}
3796
Eric Laurentbfb1b832013-01-07 09:53:42 -08003797// removeTracks_l() must be called with ThreadBase::mLock held
3798void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3799{
Andy Hungfe726a62018-09-27 15:17:25 -07003800 for (const auto& track : tracksToRemove) {
3801 mActiveTracks.remove(track);
3802 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3803 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3804 if (chain != 0) {
3805 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3806 __func__, track->id(), chain.get(), track->sessionId());
3807 chain->decActiveTrackCnt();
3808 }
3809 // If an external client track, inform APM we're no longer active, and remove if needed.
3810 // We do this under lock so that the state is consistent if the Track is destroyed.
3811 if (track->isExternalTrack()) {
3812 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003813 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003814 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003815 }
3816 }
Andy Hungfe726a62018-09-27 15:17:25 -07003817 if (track->isTerminated()) {
3818 // remove from our tracks vector
3819 removeTrack_l(track);
3820 }
jiabin57303cc2018-12-18 15:45:57 -08003821 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
3822 && mHapticChannelCount > 0) {
3823 mLock.unlock();
3824 // Unlock due to VibratorService will lock for this call and will
3825 // call Tracks.mute/unmute which also require thread's lock.
3826 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
3827 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08003828 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003829 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003830}
Eric Laurent81784c32012-11-19 14:55:58 -08003831
Eric Laurentaccc1472013-09-20 09:36:34 -07003832status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3833{
3834 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003835 ExtendedTimestamp ets;
3836 status_t status = mNormalSink->getTimestamp(ets);
3837 if (status == NO_ERROR) {
3838 status = ets.getBestTimestamp(&timestamp);
3839 }
3840 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003841 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003842 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003843 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003844 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003845 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11003846 if (mDownstreamLatencyStatMs.getN() > 0) {
3847 const uint32_t positionOffset =
3848 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3849 if (positionOffset > timestamp.mPosition) {
3850 timestamp.mPosition = 0;
3851 } else {
3852 timestamp.mPosition -= positionOffset;
3853 }
3854 }
Eric Laurentaccc1472013-09-20 09:36:34 -07003855 return NO_ERROR;
3856 }
3857 }
3858 return INVALID_OPERATION;
3859}
Eric Laurent1c333e22014-05-20 10:48:17 -07003860
Eric Laurent054d9d32015-04-24 08:48:48 -07003861status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3862 audio_patch_handle_t *handle)
3863{
Andy Hungf60abce2016-08-26 11:37:54 -07003864 status_t status;
3865 if (property_get_bool("af.patch_park", false /* default_value */)) {
3866 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3867 // or if HAL does not properly lock against access.
3868 AutoPark<FastMixer> park(mFastMixer);
3869 status = PlaybackThread::createAudioPatch_l(patch, handle);
3870 } else {
3871 status = PlaybackThread::createAudioPatch_l(patch, handle);
3872 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003873 return status;
3874}
3875
Eric Laurent1c333e22014-05-20 10:48:17 -07003876status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3877 audio_patch_handle_t *handle)
3878{
3879 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003880
3881 // store new device and send to effects
3882 audio_devices_t type = AUDIO_DEVICE_NONE;
3883 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3884 type |= patch->sinks[i].ext.device.type;
3885 }
3886
François Gaffie0c280aa2018-07-25 10:02:15 +02003887 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07003888#ifdef ADD_BATTERY_DATA
3889 // when changing the audio output device, call addBatteryData to notify
3890 // the change
3891 if (mOutDevice != type) {
3892 uint32_t params = 0;
3893 // check whether speaker is on
3894 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3895 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003896 }
3897
Eric Laurent054d9d32015-04-24 08:48:48 -07003898 audio_devices_t deviceWithoutSpeaker
3899 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3900 // check if any other device (except speaker) is on
3901 if (type & deviceWithoutSpeaker) {
3902 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3903 }
3904
3905 if (params != 0) {
3906 addBatteryData(params);
3907 }
3908 }
3909#endif
3910
3911 for (size_t i = 0; i < mEffectChains.size(); i++) {
3912 mEffectChains[i]->setDevice_l(type);
3913 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003914
3915 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3916 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
François Gaffie0c280aa2018-07-25 10:02:15 +02003917 bool configChanged = (mPrevOutDevice != type) || (mDeviceId != sinkPortId);
Eric Laurent054d9d32015-04-24 08:48:48 -07003918 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003919 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003920
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003921 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003922 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3923 status = hwDevice->createAudioPatch(patch->num_sources,
3924 patch->sources,
3925 patch->num_sinks,
3926 patch->sinks,
3927 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003928 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003929 char *address;
3930 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3931 //FIXME: we only support address on first sink with HAL version < 3.0
3932 address = audio_device_address_to_parameter(
3933 patch->sinks[0].ext.device.type,
3934 patch->sinks[0].ext.device.address);
3935 } else {
3936 address = (char *)calloc(1, 1);
3937 }
3938 AudioParameter param = AudioParameter(String8(address));
3939 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003940 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003941 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003942 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003943 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003944 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003945 mPrevOutDevice = type;
François Gaffie0c280aa2018-07-25 10:02:15 +02003946 mDeviceId = sinkPortId;
Eric Laurente8726fe2015-06-26 09:39:24 -07003947 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3948 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003949 return status;
3950}
3951
Eric Laurent054d9d32015-04-24 08:48:48 -07003952status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3953{
Andy Hungf60abce2016-08-26 11:37:54 -07003954 status_t status;
3955 if (property_get_bool("af.patch_park", false /* default_value */)) {
3956 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3957 // or if HAL does not properly lock against access.
3958 AutoPark<FastMixer> park(mFastMixer);
3959 status = PlaybackThread::releaseAudioPatch_l(handle);
3960 } else {
3961 status = PlaybackThread::releaseAudioPatch_l(handle);
3962 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003963 return status;
3964}
3965
Eric Laurent1c333e22014-05-20 10:48:17 -07003966status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3967{
3968 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003969
3970 mOutDevice = AUDIO_DEVICE_NONE;
3971
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003972 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003973 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3974 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003975 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003976 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003977 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003978 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003979 }
3980 return status;
3981}
3982
Eric Laurent83b88082014-06-20 18:31:16 -07003983void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3984{
3985 Mutex::Autolock _l(mLock);
3986 mTracks.add(track);
3987}
3988
3989void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3990{
3991 Mutex::Autolock _l(mLock);
3992 destroyTrack_l(track);
3993}
3994
Mikhail Naganovdc769682018-05-04 15:34:08 -07003995void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003996{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003997 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003998 config->role = AUDIO_PORT_ROLE_SOURCE;
3999 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4000 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004001 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4002 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4003 config->flags.output = mOutput->flags;
4004 }
Eric Laurent83b88082014-06-20 18:31:16 -07004005}
4006
Eric Laurent81784c32012-11-19 14:55:58 -08004007// ----------------------------------------------------------------------------
4008
4009AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07004010 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
4011 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004012 // mAudioMixer below
4013 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004014 mFastMixerFutex(0),
4015 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004016 // mOutputSink below
4017 // mPipeSink below
4018 // mNormalSink below
4019{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004020 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08004021 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004022 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004023 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004024 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4025 mNormalFrameCount);
4026 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4027
Andy Hungfbfc3952015-01-15 13:33:51 -08004028 if (type == DUPLICATING) {
4029 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4030 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4031 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4032 return;
4033 }
Eric Laurent81784c32012-11-19 14:55:58 -08004034 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004035 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004036 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004037 const NBAIO_Format offers[1] = {Format_from_SR_C(
4038 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004039#if !LOG_NDEBUG
4040 ssize_t index =
4041#else
4042 (void)
4043#endif
4044 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004045 ALOG_ASSERT(index == 0);
4046
4047 // initialize fast mixer depending on configuration
4048 bool initFastMixer;
4049 switch (kUseFastMixer) {
4050 case FastMixer_Never:
4051 initFastMixer = false;
4052 break;
4053 case FastMixer_Always:
4054 initFastMixer = true;
4055 break;
4056 case FastMixer_Static:
4057 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004058 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4059 // where the period is less than an experimentally determined threshold that can be
4060 // scheduled reliably with CFS. However, the BT A2DP HAL is
4061 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4062 initFastMixer = mFrameCount < mNormalFrameCount
4063 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004064 break;
4065 }
Andy Hungfda69402017-02-15 14:33:12 -08004066 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4067 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4068 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004069 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004070 audio_format_t fastMixerFormat;
4071 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4072 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4073 } else {
4074 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4075 }
4076 if (mFormat != fastMixerFormat) {
4077 // change our Sink format to accept our intermediate precision
4078 mFormat = fastMixerFormat;
4079 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004080 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004081 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4082 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4083 }
Eric Laurent81784c32012-11-19 14:55:58 -08004084
4085 // create a MonoPipe to connect our submix to FastMixer
4086 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004087
Andy Hung1258c1a2014-05-23 21:22:17 -07004088 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004089 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004090 format.mFormat = fastMixerFormat;
4091 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4092
Eric Laurent81784c32012-11-19 14:55:58 -08004093 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4094 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4095 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4096 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4097 const NBAIO_Format offers[1] = {format};
4098 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004099#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004100 ssize_t index =
4101#else
4102 (void)
4103#endif
4104 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004105 ALOG_ASSERT(index == 0);
4106 monoPipe->setAvgFrames((mScreenState & 1) ?
4107 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4108 mPipeSink = monoPipe;
4109
Eric Laurent81784c32012-11-19 14:55:58 -08004110 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004111 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004112 FastMixerStateQueue *sq = mFastMixer->sq();
4113#ifdef STATE_QUEUE_DUMP
4114 sq->setObserverDump(&mStateQueueObserverDump);
4115 sq->setMutatorDump(&mStateQueueMutatorDump);
4116#endif
4117 FastMixerState *state = sq->begin();
4118 FastTrack *fastTrack = &state->mFastTracks[0];
4119 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4120 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4121 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004122 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4123 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004124 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004125 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004126 fastTrack->mGeneration++;
4127 state->mFastTracksGen++;
4128 state->mTrackMask = 1;
4129 // fast mixer will use the HAL output sink
4130 state->mOutputSink = mOutputSink.get();
4131 state->mOutputSinkGen++;
4132 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004133 // specify sink channel mask when haptic channel mask present as it can not
4134 // be calculated directly from channel count
4135 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4136 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004137 state->mCommand = FastMixerState::COLD_IDLE;
4138 // already done in constructor initialization list
4139 //mFastMixerFutex = 0;
4140 state->mColdFutexAddr = &mFastMixerFutex;
4141 state->mColdGen++;
4142 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004143 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4144 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004145 sq->end();
4146 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4147
Eric Tan0513b5d2018-09-17 10:32:48 -07004148 NBLog::thread_info_t info;
4149 info.id = mId;
4150 info.type = NBLog::FASTMIXER;
4151 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4152
Eric Laurent81784c32012-11-19 14:55:58 -08004153 // start the fast mixer
4154 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4155 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004156 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004157 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004158
4159#ifdef AUDIO_WATCHDOG
4160 // create and start the watchdog
4161 mAudioWatchdog = new AudioWatchdog();
4162 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4163 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4164 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004165 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004166#endif
Andy Hung8946a282018-04-19 20:04:56 -07004167 } else {
4168#ifdef TEE_SINK
4169 // Only use the MixerThread tee if there is no FastMixer.
4170 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4171 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4172#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004173 }
4174
4175 switch (kUseFastMixer) {
4176 case FastMixer_Never:
4177 case FastMixer_Dynamic:
4178 mNormalSink = mOutputSink;
4179 break;
4180 case FastMixer_Always:
4181 mNormalSink = mPipeSink;
4182 break;
4183 case FastMixer_Static:
4184 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4185 break;
4186 }
4187}
4188
4189AudioFlinger::MixerThread::~MixerThread()
4190{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004191 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004192 FastMixerStateQueue *sq = mFastMixer->sq();
4193 FastMixerState *state = sq->begin();
4194 if (state->mCommand == FastMixerState::COLD_IDLE) {
4195 int32_t old = android_atomic_inc(&mFastMixerFutex);
4196 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004197 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004198 }
4199 }
4200 state->mCommand = FastMixerState::EXIT;
4201 sq->end();
4202 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4203 mFastMixer->join();
4204 // Though the fast mixer thread has exited, it's state queue is still valid.
4205 // We'll use that extract the final state which contains one remaining fast track
4206 // corresponding to our sub-mix.
4207 state = sq->begin();
4208 ALOG_ASSERT(state->mTrackMask == 1);
4209 FastTrack *fastTrack = &state->mFastTracks[0];
4210 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4211 delete fastTrack->mBufferProvider;
4212 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004213 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004214#ifdef AUDIO_WATCHDOG
4215 if (mAudioWatchdog != 0) {
4216 mAudioWatchdog->requestExit();
4217 mAudioWatchdog->requestExitAndWait();
4218 mAudioWatchdog.clear();
4219 }
4220#endif
4221 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004222 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004223 delete mAudioMixer;
4224}
4225
4226
4227uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4228{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004229 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004230 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4231 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4232 }
4233 return latency;
4234}
4235
Eric Laurentbfb1b832013-01-07 09:53:42 -08004236ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004237{
4238 // FIXME we should only do one push per cycle; confirm this is true
4239 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004240 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004241 FastMixerStateQueue *sq = mFastMixer->sq();
4242 FastMixerState *state = sq->begin();
4243 if (state->mCommand != FastMixerState::MIX_WRITE &&
4244 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4245 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004246
4247 // FIXME workaround for first HAL write being CPU bound on some devices
4248 ATRACE_BEGIN("write");
4249 mOutput->write((char *)mSinkBuffer, 0);
4250 ATRACE_END();
4251
Eric Laurent81784c32012-11-19 14:55:58 -08004252 int32_t old = android_atomic_inc(&mFastMixerFutex);
4253 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004254 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004255 }
4256#ifdef AUDIO_WATCHDOG
4257 if (mAudioWatchdog != 0) {
4258 mAudioWatchdog->resume();
4259 }
4260#endif
4261 }
4262 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004263#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004264 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004265 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004266#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004267 sq->end();
4268 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4269 if (kUseFastMixer == FastMixer_Dynamic) {
4270 mNormalSink = mPipeSink;
4271 }
4272 } else {
4273 sq->end(false /*didModify*/);
4274 }
4275 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004276 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004277}
4278
4279void AudioFlinger::MixerThread::threadLoop_standby()
4280{
4281 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004282 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004283 FastMixerStateQueue *sq = mFastMixer->sq();
4284 FastMixerState *state = sq->begin();
4285 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004286 // Report any frames trapped in the Monopipe
4287 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4288 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4289 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4290 "monoPipeWritten:%lld monoPipeLeft:%lld",
4291 (long long)mFramesWritten, (long long)mSuspendedFrames,
4292 (long long)mPipeSink->framesWritten(), pipeFrames);
4293 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4294
Eric Laurent81784c32012-11-19 14:55:58 -08004295 state->mCommand = FastMixerState::COLD_IDLE;
4296 state->mColdFutexAddr = &mFastMixerFutex;
4297 state->mColdGen++;
4298 mFastMixerFutex = 0;
4299 sq->end();
4300 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4301 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4302 if (kUseFastMixer == FastMixer_Dynamic) {
4303 mNormalSink = mOutputSink;
4304 }
4305#ifdef AUDIO_WATCHDOG
4306 if (mAudioWatchdog != 0) {
4307 mAudioWatchdog->pause();
4308 }
4309#endif
4310 } else {
4311 sq->end(false /*didModify*/);
4312 }
4313 }
4314 PlaybackThread::threadLoop_standby();
4315}
4316
Eric Laurentbfb1b832013-01-07 09:53:42 -08004317bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4318{
4319 return false;
4320}
4321
4322bool AudioFlinger::PlaybackThread::shouldStandby_l()
4323{
4324 return !mStandby;
4325}
4326
4327bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4328{
4329 Mutex::Autolock _l(mLock);
4330 return waitingAsyncCallback_l();
4331}
4332
Eric Laurent81784c32012-11-19 14:55:58 -08004333// shared by MIXER and DIRECT, overridden by DUPLICATING
4334void AudioFlinger::PlaybackThread::threadLoop_standby()
4335{
4336 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004337 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004338 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004339 // discard any pending drain or write ack by incrementing sequence
4340 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4341 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004342 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004343 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4344 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004345 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004346 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004347}
4348
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004349void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4350{
4351 ALOGV("signal playback thread");
4352 broadcast_l();
4353}
4354
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004355void AudioFlinger::PlaybackThread::onAsyncError()
4356{
4357 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4358 invalidateTracks((audio_stream_type_t)i);
4359 }
4360}
4361
Eric Laurent81784c32012-11-19 14:55:58 -08004362void AudioFlinger::MixerThread::threadLoop_mix()
4363{
Eric Laurent81784c32012-11-19 14:55:58 -08004364 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004365 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004366 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004367 // increase sleep time progressively when application underrun condition clears.
4368 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4369 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4370 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004371 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004372 sleepTimeShift--;
4373 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004374 mSleepTimeUs = 0;
4375 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004376 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004377
Eric Laurent81784c32012-11-19 14:55:58 -08004378}
4379
4380void AudioFlinger::MixerThread::threadLoop_sleepTime()
4381{
4382 // If no tracks are ready, sleep once for the duration of an output
4383 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004384 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004385 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004386 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4387 // Using the Monopipe availableToWrite, we estimate the
4388 // sleep time to retry for more data (before we underrun).
4389 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4390 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4391 const size_t pipeFrames = monoPipe->maxFrames();
4392 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4393 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4394 const size_t framesDelay = std::min(
4395 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4396 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4397 pipeFrames, framesLeft, framesDelay);
4398 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4399 } else {
4400 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4401 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4402 mSleepTimeUs = kMinThreadSleepTimeUs;
4403 }
4404 // reduce sleep time in case of consecutive application underruns to avoid
4405 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4406 // duration we would end up writing less data than needed by the audio HAL if
4407 // the condition persists.
4408 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4409 sleepTimeShift++;
4410 }
Eric Laurent81784c32012-11-19 14:55:58 -08004411 }
4412 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004413 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004414 }
4415 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004416 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4417 // before effects processing or output.
4418 if (mMixerBufferValid) {
4419 memset(mMixerBuffer, 0, mMixerBufferSize);
4420 } else {
4421 memset(mSinkBuffer, 0, mSinkBufferSize);
4422 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004423 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004424 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4425 "anticipated start");
4426 }
4427 // TODO add standby time extension fct of effect tail
4428}
4429
4430// prepareTracks_l() must be called with ThreadBase::mLock held
4431AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4432 Vector< sp<Track> > *tracksToRemove)
4433{
Andy Hungc0691382018-09-12 18:01:57 -07004434 // clean up deleted track ids in AudioMixer before allocating new tracks
4435 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4436 // for each trackId, destroy it in the AudioMixer
4437 if (mAudioMixer->exists(trackId)) {
4438 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004439 }
4440 });
Andy Hungc0691382018-09-12 18:01:57 -07004441 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004442
4443 mixer_state mixerStatus = MIXER_IDLE;
4444 // find out which tracks need to be processed
4445 size_t count = mActiveTracks.size();
4446 size_t mixedTracks = 0;
4447 size_t tracksWithEffect = 0;
4448 // counts only _active_ fast tracks
4449 size_t fastTracks = 0;
4450 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4451
4452 float masterVolume = mMasterVolume;
4453 bool masterMute = mMasterMute;
4454
4455 if (masterMute) {
4456 masterVolume = 0;
4457 }
4458 // Delegate master volume control to effect in output mix effect chain if needed
4459 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4460 if (chain != 0) {
4461 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4462 chain->setVolume_l(&v, &v);
4463 masterVolume = (float)((v + (1 << 23)) >> 24);
4464 chain.clear();
4465 }
4466
4467 // prepare a new state to push
4468 FastMixerStateQueue *sq = NULL;
4469 FastMixerState *state = NULL;
4470 bool didModify = false;
4471 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004472 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004473 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004474 sq = mFastMixer->sq();
4475 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004476 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004477 }
4478
Andy Hung69aed5f2014-02-25 17:24:40 -08004479 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004480 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004481
Andy Hungbd3b2b02018-05-21 10:53:11 -07004482 // DeferredOperations handles statistics after setting mixerStatus.
4483 class DeferredOperations {
4484 public:
4485 DeferredOperations(mixer_state *mixerStatus)
4486 : mMixerStatus(mixerStatus) { }
4487
4488 // when leaving scope, tally frames properly.
4489 ~DeferredOperations() {
4490 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4491 // because that is when the underrun occurs.
4492 // We do not distinguish between FastTracks and NormalTracks here.
4493 if (*mMixerStatus == MIXER_TRACKS_READY) {
4494 for (const auto &underrun : mUnderrunFrames) {
4495 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4496 underrun.second);
4497 }
4498 }
4499 }
4500
4501 // tallyUnderrunFrames() is called to update the track counters
4502 // with the number of underrun frames for a particular mixer period.
4503 // We defer tallying until we know the final mixer status.
4504 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4505 mUnderrunFrames.emplace_back(track, underrunFrames);
4506 }
4507
4508 private:
4509 const mixer_state * const mMixerStatus;
4510 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4511 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4512
jiabin245cdd92018-12-07 17:55:15 -08004513 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004514 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004515 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004516
4517 // this const just means the local variable doesn't change
4518 Track* const track = t.get();
4519
4520 // process fast tracks
4521 if (track->isFastTrack()) {
jiabin245cdd92018-12-07 17:55:15 -08004522 if (track->getHapticPlaybackEnabled()) {
4523 noFastHapticTrack = false;
4524 }
Eric Laurent81784c32012-11-19 14:55:58 -08004525
4526 // It's theoretically possible (though unlikely) for a fast track to be created
4527 // and then removed within the same normal mix cycle. This is not a problem, as
4528 // the track never becomes active so it's fast mixer slot is never touched.
4529 // The converse, of removing an (active) track and then creating a new track
4530 // at the identical fast mixer slot within the same normal mix cycle,
4531 // is impossible because the slot isn't marked available until the end of each cycle.
4532 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004533 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004534 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4535 FastTrack *fastTrack = &state->mFastTracks[j];
4536
4537 // Determine whether the track is currently in underrun condition,
4538 // and whether it had a recent underrun.
4539 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4540 FastTrackUnderruns underruns = ftDump->mUnderruns;
4541 uint32_t recentFull = (underruns.mBitFields.mFull -
4542 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4543 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4544 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4545 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4546 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4547 uint32_t recentUnderruns = recentPartial + recentEmpty;
4548 track->mObservedUnderruns = underruns;
4549 // don't count underruns that occur while stopping or pausing
4550 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004551 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004552 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4553 recentUnderruns > 0) {
4554 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004555 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004556 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004557 // Immediately account for FastTrack underruns.
4558 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004559
4560 // This is similar to the state machine for normal tracks,
4561 // with a few modifications for fast tracks.
4562 bool isActive = true;
4563 switch (track->mState) {
4564 case TrackBase::STOPPING_1:
4565 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004566 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004567 track->mState = TrackBase::STOPPING_2;
4568 }
4569 break;
4570 case TrackBase::PAUSING:
4571 // ramp down is not yet implemented
4572 track->setPaused();
4573 break;
4574 case TrackBase::RESUMING:
4575 // ramp up is not yet implemented
4576 track->mState = TrackBase::ACTIVE;
4577 break;
4578 case TrackBase::ACTIVE:
4579 if (recentFull > 0 || recentPartial > 0) {
4580 // track has provided at least some frames recently: reset retry count
4581 track->mRetryCount = kMaxTrackRetries;
4582 }
4583 if (recentUnderruns == 0) {
4584 // no recent underruns: stay active
4585 break;
4586 }
4587 // there has recently been an underrun of some kind
4588 if (track->sharedBuffer() == 0) {
4589 // were any of the recent underruns "empty" (no frames available)?
4590 if (recentEmpty == 0) {
4591 // no, then ignore the partial underruns as they are allowed indefinitely
4592 break;
4593 }
4594 // there has recently been an "empty" underrun: decrement the retry counter
4595 if (--(track->mRetryCount) > 0) {
4596 break;
4597 }
4598 // indicate to client process that the track was disabled because of underrun;
4599 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004600 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004601 // remove from active list, but state remains ACTIVE [confusing but true]
4602 isActive = false;
4603 break;
4604 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004605 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004606 case TrackBase::STOPPING_2:
4607 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004608 case TrackBase::STOPPED:
4609 case TrackBase::FLUSHED: // flush() while active
4610 // Check for presentation complete if track is inactive
4611 // We have consumed all the buffers of this track.
4612 // This would be incomplete if we auto-paused on underrun
4613 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004614 uint32_t latency = 0;
4615 status_t result = mOutput->stream->getLatency(&latency);
4616 ALOGE_IF(result != OK,
4617 "Error when retrieving output stream latency: %d", result);
4618 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004619 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004620 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4621 // track stays in active list until presentation is complete
4622 break;
4623 }
4624 }
4625 if (track->isStopping_2()) {
4626 track->mState = TrackBase::STOPPED;
4627 }
4628 if (track->isStopped()) {
4629 // Can't reset directly, as fast mixer is still polling this track
4630 // track->reset();
4631 // So instead mark this track as needing to be reset after push with ack
4632 resetMask |= 1 << i;
4633 }
4634 isActive = false;
4635 break;
4636 case TrackBase::IDLE:
4637 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004638 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004639 }
4640
4641 if (isActive) {
4642 // was it previously inactive?
4643 if (!(state->mTrackMask & (1 << j))) {
4644 ExtendedAudioBufferProvider *eabp = track;
4645 VolumeProvider *vp = track;
4646 fastTrack->mBufferProvider = eabp;
4647 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004648 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004649 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08004650 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08004651 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08004652 fastTrack->mGeneration++;
4653 state->mTrackMask |= 1 << j;
4654 didModify = true;
4655 // no acknowledgement required for newly active tracks
4656 }
Kevin Rocard12381092018-04-11 09:19:59 -07004657 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004658 // cache the combined master volume and stream type volume for fast mixer; this
4659 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004660 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004661 proxy->framesReleased()).first;
4662 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004663 * mStreamTypes[track->streamType()].volume
4664 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004665 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004666 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4667 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4668 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4669 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004670 ++fastTracks;
4671 } else {
4672 // was it previously active?
4673 if (state->mTrackMask & (1 << j)) {
4674 fastTrack->mBufferProvider = NULL;
4675 fastTrack->mGeneration++;
4676 state->mTrackMask &= ~(1 << j);
4677 didModify = true;
4678 // If any fast tracks were removed, we must wait for acknowledgement
4679 // because we're about to decrement the last sp<> on those tracks.
4680 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4681 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004682 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4683 // AudioTrack may start (which may not be with a start() but with a write()
4684 // after underrun) and immediately paused or released. In that case the
4685 // FastTrack state hasn't had time to update.
4686 // TODO Remove the ALOGW when this theory is confirmed.
4687 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004688 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4689 j, track->mState, state->mTrackMask, recentUnderruns,
4690 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004691 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004692 }
4693 tracksToRemove->add(track);
4694 // Avoids a misleading display in dumpsys
4695 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4696 }
jiabin245cdd92018-12-07 17:55:15 -08004697 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
4698 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
4699 didModify = true;
4700 }
Eric Laurent81784c32012-11-19 14:55:58 -08004701 continue;
4702 }
4703
4704 { // local variable scope to avoid goto warning
4705
4706 audio_track_cblk_t* cblk = track->cblk();
4707
4708 // The first time a track is added we wait
4709 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004710 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004711
4712 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004713 // use the trackId as the AudioMixer name.
4714 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004715 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004716 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004717 track->mChannelMask,
4718 track->mFormat,
4719 track->mSessionId);
4720 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004721 ALOGW("%s(): AudioMixer cannot create track(%d)"
4722 " mask %#x, format %#x, sessionId %d",
4723 __func__, trackId,
4724 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004725 tracksToRemove->add(track);
4726 track->invalidate(); // consider it dead.
4727 continue;
4728 }
4729 }
4730
Eric Laurent81784c32012-11-19 14:55:58 -08004731 // make sure that we have enough frames to mix one full buffer.
4732 // enforce this condition only once to enable draining the buffer in case the client
4733 // app does not call stop() and relies on underrun to stop:
4734 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4735 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004736 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004737 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004738 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004739
4740 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004741 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004742 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4743 // add frames already consumed but not yet released by the resampler
4744 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004745 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004746
Eric Laurent81784c32012-11-19 14:55:58 -08004747 uint32_t minFrames = 1;
4748 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4749 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004750 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004751 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004752
4753 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004754 if (ATRACE_ENABLED()) {
4755 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004756 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004757 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004758 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004759 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004760 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004761 !track->isPaused() && !track->isTerminated())
4762 {
Andy Hungc0691382018-09-12 18:01:57 -07004763 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004764
4765 mixedTracks++;
4766
Andy Hung69aed5f2014-02-25 17:24:40 -08004767 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4768 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004769 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004770 if (track->mainBuffer() != mSinkBuffer &&
4771 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004772 if (mEffectBufferEnabled) {
4773 mEffectBufferValid = true; // Later can set directly.
4774 }
Eric Laurent81784c32012-11-19 14:55:58 -08004775 chain = getEffectChain_l(track->sessionId());
4776 // Delegate volume control to effect in track effect chain if needed
4777 if (chain != 0) {
4778 tracksWithEffect++;
4779 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004780 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004781 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004782 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004783 }
4784 }
4785
4786
4787 int param = AudioMixer::VOLUME;
4788 if (track->mFillingUpStatus == Track::FS_FILLED) {
4789 // no ramp for the first volume setting
4790 track->mFillingUpStatus = Track::FS_ACTIVE;
4791 if (track->mState == TrackBase::RESUMING) {
4792 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08004793 // If a new track is paused immediately after start, do not ramp on resume.
4794 if (cblk->mServer != 0) {
4795 param = AudioMixer::RAMP_VOLUME;
4796 }
Eric Laurent81784c32012-11-19 14:55:58 -08004797 }
Andy Hungc0691382018-09-12 18:01:57 -07004798 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004799 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004800 // FIXME should not make a decision based on mServer
4801 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004802 // If the track is stopped before the first frame was mixed,
4803 // do not apply ramp
4804 param = AudioMixer::RAMP_VOLUME;
4805 }
4806
4807 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004808 uint32_t vl, vr; // in U8.24 integer format
4809 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004810 // read original volumes with volume control
4811 float typeVolume = mStreamTypes[track->streamType()].volume;
4812 float v = masterVolume * typeVolume;
4813
Glenn Kastene4756fe2012-11-29 13:38:14 -08004814 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004815 vl = vr = 0;
4816 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004817 if (track->isPausing()) {
4818 track->setPaused();
4819 }
4820 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004821 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004822 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004823 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4824 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004825 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004826 if (vlf > GAIN_FLOAT_UNITY) {
4827 ALOGV("Track left volume out of range: %.3g", vlf);
4828 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004829 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004830 if (vrf > GAIN_FLOAT_UNITY) {
4831 ALOGV("Track right volume out of range: %.3g", vrf);
4832 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004833 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004834 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004835 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004836 // now apply the master volume and stream type volume and shaper volume
4837 vlf *= v * vh;
4838 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004839 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004840 // then derive vl and vr as U8.24 versions for the effect chain
4841 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4842 vl = (uint32_t) (scaleto8_24 * vlf);
4843 vr = (uint32_t) (scaleto8_24 * vrf);
4844 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004845 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004846 // send level comes from shared memory and so may be corrupt
4847 if (sendLevel > MAX_GAIN_INT) {
4848 ALOGV("Track send level out of range: %04X", sendLevel);
4849 sendLevel = MAX_GAIN_INT;
4850 }
Andy Hung6be49402014-05-30 10:42:03 -07004851 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4852 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004853 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004854
Kevin Rocard12381092018-04-11 09:19:59 -07004855 track->setFinalVolume((vrf + vlf) / 2.f);
4856
Eric Laurent81784c32012-11-19 14:55:58 -08004857 // Delegate volume control to effect in track effect chain if needed
4858 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4859 // Do not ramp volume if volume is controlled by effect
4860 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004861 // Update remaining floating point volume levels
4862 vlf = (float)vl / (1 << 24);
4863 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004864 track->mHasVolumeController = true;
4865 } else {
4866 // force no volume ramp when volume controller was just disabled or removed
4867 // from effect chain to avoid volume spike
4868 if (track->mHasVolumeController) {
4869 param = AudioMixer::VOLUME;
4870 }
4871 track->mHasVolumeController = false;
4872 }
4873
Eric Laurent7c29ec92017-09-20 17:54:22 -07004874 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4875 // still applied by the mixer.
4876 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4877 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4878 if (v != mLeftVolFloat) {
4879 status_t result = mOutput->stream->setVolume(v, v);
4880 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4881 if (result == OK) {
4882 mLeftVolFloat = v;
4883 }
4884 }
4885 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4886 // remove stream volume contribution from software volume.
4887 if (v != 0.0f && mLeftVolFloat == v) {
4888 vlf = min(1.0f, vlf / v);
4889 vrf = min(1.0f, vrf / v);
4890 vaf = min(1.0f, vaf / v);
4891 }
4892 }
Eric Laurent81784c32012-11-19 14:55:58 -08004893 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07004894 mAudioMixer->setBufferProvider(trackId, track);
4895 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004896
Andy Hungc0691382018-09-12 18:01:57 -07004897 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
4898 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
4899 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004900 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004901 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004902 AudioMixer::TRACK,
4903 AudioMixer::FORMAT, (void *)track->format());
4904 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004905 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004906 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004907 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004908 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004909 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07004910 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08004911 AudioMixer::MIXER_CHANNEL_MASK,
4912 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08004913 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004914 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004915 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004916 if (reqSampleRate == 0) {
4917 reqSampleRate = mSampleRate;
4918 } else if (reqSampleRate > maxSampleRate) {
4919 reqSampleRate = maxSampleRate;
4920 }
Eric Laurent81784c32012-11-19 14:55:58 -08004921 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004922 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004923 AudioMixer::RESAMPLE,
4924 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004925 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004926
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004927 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004928 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004929 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07004930 AudioMixer::TIMESTRETCH,
4931 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004932 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004933
Andy Hung69aed5f2014-02-25 17:24:40 -08004934 /*
4935 * Select the appropriate output buffer for the track.
4936 *
Andy Hung98ef9782014-03-04 14:46:50 -08004937 * Tracks with effects go into their own effects chain buffer
4938 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004939 *
4940 * Other tracks can use mMixerBuffer for higher precision
4941 * channel accumulation. If this buffer is enabled
4942 * (mMixerBufferEnabled true), then selected tracks will accumulate
4943 * into it.
4944 *
4945 */
4946 if (mMixerBufferEnabled
4947 && (track->mainBuffer() == mSinkBuffer
4948 || track->mainBuffer() == mMixerBuffer)) {
4949 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004950 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004951 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004952 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004953 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004954 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004955 AudioMixer::TRACK,
4956 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4957 // TODO: override track->mainBuffer()?
4958 mMixerBufferValid = true;
4959 } else {
4960 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004961 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004962 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004963 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004964 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004965 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004966 AudioMixer::TRACK,
4967 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4968 }
Eric Laurent81784c32012-11-19 14:55:58 -08004969 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004970 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004971 AudioMixer::TRACK,
4972 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08004973 mAudioMixer->setParameter(
4974 trackId,
4975 AudioMixer::TRACK,
4976 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08004977 mAudioMixer->setParameter(
4978 trackId,
4979 AudioMixer::TRACK,
4980 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08004981
4982 // reset retry count
4983 track->mRetryCount = kMaxTrackRetries;
4984
4985 // If one track is ready, set the mixer ready if:
4986 // - the mixer was not ready during previous round OR
4987 // - no other track is not ready
4988 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4989 mixerStatus != MIXER_TRACKS_ENABLED) {
4990 mixerStatus = MIXER_TRACKS_READY;
4991 }
4992 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004993 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004994 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07004995 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
4996 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004997 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004998 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004999 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005000
Eric Laurent81784c32012-11-19 14:55:58 -08005001 // clear effect chain input buffer if an active track underruns to avoid sending
5002 // previous audio buffer again to effects
5003 chain = getEffectChain_l(track->sessionId());
5004 if (chain != 0) {
5005 chain->clearInputBuffer();
5006 }
5007
Andy Hungc0691382018-09-12 18:01:57 -07005008 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005009 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5010 track->isStopped() || track->isPaused()) {
5011 // We have consumed all the buffers of this track.
5012 // Remove it from the list of active tracks.
5013 // TODO: use actual buffer filling status instead of latency when available from
5014 // audio HAL
5015 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005016 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005017 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5018 if (track->isStopped()) {
5019 track->reset();
5020 }
5021 tracksToRemove->add(track);
5022 }
5023 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005024 // No buffers for this track. Give it a few chances to
5025 // fill a buffer, then remove it from active list.
5026 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005027 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5028 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005029 tracksToRemove->add(track);
5030 // indicate to client process that the track was disabled because of underrun;
5031 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005032 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005033 // If one track is not ready, mark the mixer also not ready if:
5034 // - the mixer was ready during previous round OR
5035 // - no other track is ready
5036 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5037 mixerStatus != MIXER_TRACKS_READY) {
5038 mixerStatus = MIXER_TRACKS_ENABLED;
5039 }
5040 }
Andy Hungc0691382018-09-12 18:01:57 -07005041 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005042 }
5043
5044 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005045
5046 }
5047
jiabin245cdd92018-12-07 17:55:15 -08005048 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5049 // When there is no fast track playing haptic and FastMixer exists,
5050 // enabling the first FastTrack, which provides mixed data from normal
5051 // tracks, to play haptic data.
5052 FastTrack *fastTrack = &state->mFastTracks[0];
5053 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5054 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5055 didModify = true;
5056 }
5057 }
5058
Eric Laurent81784c32012-11-19 14:55:58 -08005059 // Push the new FastMixer state if necessary
5060 bool pauseAudioWatchdog = false;
5061 if (didModify) {
5062 state->mFastTracksGen++;
5063 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5064 if (kUseFastMixer == FastMixer_Dynamic &&
5065 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5066 state->mCommand = FastMixerState::COLD_IDLE;
5067 state->mColdFutexAddr = &mFastMixerFutex;
5068 state->mColdGen++;
5069 mFastMixerFutex = 0;
5070 if (kUseFastMixer == FastMixer_Dynamic) {
5071 mNormalSink = mOutputSink;
5072 }
5073 // If we go into cold idle, need to wait for acknowledgement
5074 // so that fast mixer stops doing I/O.
5075 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5076 pauseAudioWatchdog = true;
5077 }
Eric Laurent81784c32012-11-19 14:55:58 -08005078 }
5079 if (sq != NULL) {
5080 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005081 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5082 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5083 // when bringing the output sink into standby.)
5084 //
5085 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5086 //
5087 // This occurs with BT suspend when we idle the FastMixer with
5088 // active tracks, which may be added or removed.
5089 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005090 }
5091#ifdef AUDIO_WATCHDOG
5092 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5093 mAudioWatchdog->pause();
5094 }
5095#endif
5096
5097 // Now perform the deferred reset on fast tracks that have stopped
5098 while (resetMask != 0) {
5099 size_t i = __builtin_ctz(resetMask);
5100 ALOG_ASSERT(i < count);
5101 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005102 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005103 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5104 track->reset();
5105 }
5106
Andy Hung80d03d22018-04-10 10:32:11 -07005107 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5108 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5109 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5110 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5111 // See also the implementation of destroyTrack_l().
5112 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005113 const int trackId = track->id();
5114 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5115 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005116 }
5117 }
5118
Eric Laurent81784c32012-11-19 14:55:58 -08005119 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005120 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005121
Eric Laurent97d547d2014-09-02 14:45:53 -07005122 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5123 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005124 }
5125
5126 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005127 // as long as there are effects we should clear the effects buffer, to avoid
5128 // passing a non-clean buffer to the effect chain
5129 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005130 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005131 // sink or mix buffer must be cleared if all tracks are connected to an
5132 // effect chain as in this case the mixer will not write to the sink or mix buffer
5133 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005134 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5135 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005136 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005137 if (mMixerBufferValid) {
5138 memset(mMixerBuffer, 0, mMixerBufferSize);
5139 // TODO: In testing, mSinkBuffer below need not be cleared because
5140 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5141 // after mixing.
5142 //
5143 // To enforce this guarantee:
5144 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5145 // (mixedTracks == 0 && fastTracks > 0))
5146 // must imply MIXER_TRACKS_READY.
5147 // Later, we may clear buffers regardless, and skip much of this logic.
5148 }
Andy Hung98ef9782014-03-04 14:46:50 -08005149 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005150 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005151 }
5152
5153 // if any fast tracks, then status is ready
5154 mMixerStatusIgnoringFastTracks = mixerStatus;
5155 if (fastTracks > 0) {
5156 mixerStatus = MIXER_TRACKS_READY;
5157 }
5158 return mixerStatus;
5159}
5160
Eric Laurentad7dd962016-09-22 12:38:37 -07005161// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005162uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005163{
5164 uint32_t trackCount = 0;
5165 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005166 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005167 trackCount++;
5168 }
5169 }
5170 return trackCount;
5171}
5172
Andy Hung1bc088a2018-02-09 15:57:31 -08005173// isTrackAllowed_l() must be called with ThreadBase::mLock held
5174bool AudioFlinger::MixerThread::isTrackAllowed_l(
5175 audio_channel_mask_t channelMask, audio_format_t format,
5176 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005177{
Andy Hung1bc088a2018-02-09 15:57:31 -08005178 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5179 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005180 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005181 // Check validity as we don't call AudioMixer::create() here.
5182 if (!AudioMixer::isValidFormat(format)) {
5183 ALOGW("%s: invalid format: %#x", __func__, format);
5184 return false;
5185 }
5186 if (!AudioMixer::isValidChannelMask(channelMask)) {
5187 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5188 return false;
5189 }
5190 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005191}
5192
Eric Laurent10351942014-05-08 18:49:52 -07005193// checkForNewParameter_l() must be called with ThreadBase::mLock held
5194bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5195 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005196{
Eric Laurent81784c32012-11-19 14:55:58 -08005197 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005198 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005199
Eric Laurent10351942014-05-08 18:49:52 -07005200 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005201
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005202 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005203
Eric Laurent10351942014-05-08 18:49:52 -07005204 AudioParameter param = AudioParameter(keyValuePair);
5205 int value;
5206 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5207 reconfig = true;
5208 }
5209 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005210 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005211 status = BAD_VALUE;
5212 } else {
5213 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005214 reconfig = true;
5215 }
Eric Laurent10351942014-05-08 18:49:52 -07005216 }
5217 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005218 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005219 status = BAD_VALUE;
5220 } else {
5221 // no need to save value, since it's constant
5222 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005223 }
Eric Laurent10351942014-05-08 18:49:52 -07005224 }
5225 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5226 // do not accept frame count changes if tracks are open as the track buffer
5227 // size depends on frame count and correct behavior would not be guaranteed
5228 // if frame count is changed after track creation
5229 if (!mTracks.isEmpty()) {
5230 status = INVALID_OPERATION;
5231 } else {
5232 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005233 }
Eric Laurent10351942014-05-08 18:49:52 -07005234 }
5235 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005236#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005237 // when changing the audio output device, call addBatteryData to notify
5238 // the change
5239 if (mOutDevice != value) {
5240 uint32_t params = 0;
5241 // check whether speaker is on
5242 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5243 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005244 }
Eric Laurent10351942014-05-08 18:49:52 -07005245
5246 audio_devices_t deviceWithoutSpeaker
5247 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5248 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005249 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005250 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5251 }
5252
5253 if (params != 0) {
5254 addBatteryData(params);
5255 }
5256 }
Eric Laurent81784c32012-11-19 14:55:58 -08005257#endif
5258
Eric Laurent10351942014-05-08 18:49:52 -07005259 // forward device change to effects that have requested to be
5260 // aware of attached audio device.
5261 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005262 a2dpDeviceChanged =
5263 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005264 mOutDevice = value;
5265 for (size_t i = 0; i < mEffectChains.size(); i++) {
5266 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005267 }
5268 }
Eric Laurent10351942014-05-08 18:49:52 -07005269 }
Eric Laurent81784c32012-11-19 14:55:58 -08005270
Eric Laurent10351942014-05-08 18:49:52 -07005271 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005272 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005273 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005274 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005275 mStandby = true;
5276 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005277 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005278 }
Eric Laurent10351942014-05-08 18:49:52 -07005279 if (status == NO_ERROR && reconfig) {
5280 readOutputParameters_l();
5281 delete mAudioMixer;
5282 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005283 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005284 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005285 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005286 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005287 track->mChannelMask,
5288 track->mFormat,
5289 track->mSessionId);
5290 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005291 "%s(): AudioMixer cannot create track(%d)"
5292 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005293 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005294 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005295 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005296 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005297 }
Eric Laurent81784c32012-11-19 14:55:58 -08005298 }
5299
Eric Laurent42537be2016-01-08 17:16:42 -08005300 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005301}
5302
5303
5304void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5305{
Eric Laurent81784c32012-11-19 14:55:58 -08005306 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005307 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005308 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005309 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005310 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5311 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5312 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005313 if (hasFastMixer()) {
5314 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5315
5316 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5317 // while we are dumping it. It may be inconsistent, but it won't mutate!
5318 // This is a large object so we place it on the heap.
5319 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005320 const std::unique_ptr<FastMixerDumpState> copy =
5321 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005322 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005323
5324#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005325 // Similar for state queue
5326 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5327 observerCopy.dump(fd);
5328 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5329 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005330#endif
5331
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005332#ifdef AUDIO_WATCHDOG
5333 if (mAudioWatchdog != 0) {
5334 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5335 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5336 wdCopy.dump(fd);
5337 }
5338#endif
5339
5340 } else {
5341 dprintf(fd, " No FastMixer\n");
5342 }
Eric Laurent81784c32012-11-19 14:55:58 -08005343}
5344
5345uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5346{
5347 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5348}
5349
5350uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5351{
5352 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5353}
5354
5355void AudioFlinger::MixerThread::cacheParameters_l()
5356{
5357 PlaybackThread::cacheParameters_l();
5358
5359 // FIXME: Relaxed timing because of a certain device that can't meet latency
5360 // Should be reduced to 2x after the vendor fixes the driver issue
5361 // increase threshold again due to low power audio mode. The way this warning
5362 // threshold is calculated and its usefulness should be reconsidered anyway.
5363 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5364}
5365
5366// ----------------------------------------------------------------------------
5367
5368AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Andy Hung48f59ed2019-01-28 15:06:59 -08005369 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005370 ThreadBase::type_t type, bool systemReady)
5371 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005372{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005373 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005374}
5375
Eric Laurent81784c32012-11-19 14:55:58 -08005376AudioFlinger::DirectOutputThread::~DirectOutputThread()
5377{
5378}
5379
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005380void AudioFlinger::DirectOutputThread::dumpInternals(int fd, const Vector<String16>& args)
5381{
5382 PlaybackThread::dumpInternals(fd, args);
5383 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5384 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5385}
5386
5387void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5388{
5389 Mutex::Autolock _l(mLock);
5390 if (mMasterBalance != balance) {
5391 mMasterBalance.store(balance);
5392 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5393 broadcast_l();
5394 }
5395}
5396
Eric Laurent5850c4c2016-11-10 13:04:31 -08005397void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005398{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005399 float left, right;
5400
5401 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5402 left = right = 0;
5403 } else {
5404 float typeVolume = mStreamTypes[track->streamType()].volume;
5405 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005406 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005407
Andy Hung10cbff12017-02-21 17:30:14 -08005408 // Get volumeshaper scaling
5409 std::pair<float /* volume */, bool /* active */>
5410 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005411 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005412 v *= vh.first;
5413 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005414
Glenn Kastenc56f3422014-03-21 17:53:17 -07005415 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5416 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5417 if (left > GAIN_FLOAT_UNITY) {
5418 left = GAIN_FLOAT_UNITY;
5419 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005420 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005421 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5422 if (right > GAIN_FLOAT_UNITY) {
5423 right = GAIN_FLOAT_UNITY;
5424 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005425 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005426 }
5427
5428 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005429 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005430 if (left != mLeftVolFloat || right != mRightVolFloat) {
5431 mLeftVolFloat = left;
5432 mRightVolFloat = right;
5433
Eric Laurentbfb1b832013-01-07 09:53:42 -08005434 // Delegate volume control to effect in track effect chain if needed
5435 // only one effect chain can be present on DirectOutputThread, so if
5436 // there is one, the track is connected to it
5437 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005438 // if effect chain exists, volume is handled by it.
5439 // Convert volumes from float to 8.24
5440 uint32_t vl = (uint32_t)(left * (1 << 24));
5441 uint32_t vr = (uint32_t)(right * (1 << 24));
5442 // Direct/Offload effect chains set output volume in setVolume_l().
5443 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5444 } else {
5445 // otherwise we directly set the volume.
5446 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005447 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005448 }
5449 }
5450}
5451
Phil Burk43b4dcc2015-06-09 16:53:44 -07005452void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5453{
5454 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005455 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005456
Eric Laurent0f0631e2015-07-06 18:01:25 -07005457 if (previousTrack != 0 && latestTrack != 0) {
5458 if (mType == DIRECT) {
5459 if (previousTrack.get() != latestTrack.get()) {
5460 mFlushPending = true;
5461 }
5462 } else /* mType == OFFLOAD */ {
5463 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5464 mFlushPending = true;
5465 }
5466 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005467 } else if (previousTrack == 0) {
5468 // there could be an old track added back during track transition for direct
5469 // output, so always issues flush to flush data of the previous track if it
5470 // was already destroyed with HAL paused, then flush can resume the playback
5471 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005472 }
5473 PlaybackThread::onAddNewTrack_l();
5474}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005475
Eric Laurent81784c32012-11-19 14:55:58 -08005476AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5477 Vector< sp<Track> > *tracksToRemove
5478)
5479{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005480 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005481 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005482 bool doHwPause = false;
5483 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005484
5485 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005486 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005487 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005488 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005489 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005490 continue;
5491 }
5492
Eric Laurent5850c4c2016-11-10 13:04:31 -08005493 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005494#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005495 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005496#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005497 // Only consider last track started for volume and mixer state control.
5498 // In theory an older track could underrun and restart after the new one starts
5499 // but as we only care about the transition phase between two tracks on a
5500 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005501 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005502 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005503
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005504 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005505 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005506 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005507 doHwPause = true;
5508 mHwPaused = true;
5509 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005510 } else if (track->isFlushPending()) {
5511 track->flushAck();
5512 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005513 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005514 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005515 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005516 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005517 if (last) {
5518 mLeftVolFloat = mRightVolFloat = -1.0;
5519 if (mHwPaused) {
5520 doHwResume = true;
5521 mHwPaused = false;
5522 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005523 }
5524 }
5525
Eric Laurent81784c32012-11-19 14:55:58 -08005526 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005527 // for all its buffers to be filled before processing it.
5528 // Allow draining the buffer in case the client
5529 // app does not call stop() and relies on underrun to stop:
5530 // hence the test on (track->mRetryCount > 1).
5531 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005532 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005533 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005534 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005535 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005536 minFrames = mNormalFrameCount;
5537 } else {
5538 minFrames = 1;
5539 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005540
Eric Laurentab5cdba2014-06-09 17:22:27 -07005541 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5542 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005543 {
Andy Hungc0691382018-09-12 18:01:57 -07005544 ALOGVV("track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005545
5546 if (track->mFillingUpStatus == Track::FS_FILLED) {
5547 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005548 if (last) {
5549 // make sure processVolume_l() will apply new volume even if 0
5550 mLeftVolFloat = mRightVolFloat = -1.0;
5551 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005552 if (!mHwSupportsPause) {
5553 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005554 }
5555 }
5556
5557 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005558 processVolume_l(track, last);
5559 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005560 sp<Track> previousTrack = mPreviousTrack.promote();
5561 if (previousTrack != 0) {
5562 if (track != previousTrack.get()) {
5563 // Flush any data still being written from last track
5564 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005565 // Invalidate previous track to force a seek when resuming.
5566 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005567 }
5568 }
5569 mPreviousTrack = track;
5570
Eric Laurentd595b7c2013-04-03 17:27:56 -07005571 // reset retry count
5572 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005573 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005574 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005575 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005576 doHwResume = true;
5577 mHwPaused = false;
5578 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005579 }
Eric Laurent81784c32012-11-19 14:55:58 -08005580 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005581 // clear effect chain input buffer if the last active track started underruns
5582 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005583 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005584 mEffectChains[0]->clearInputBuffer();
5585 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005586 if (track->isStopping_1()) {
5587 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005588 if (last && mHwPaused) {
5589 doHwResume = true;
5590 mHwPaused = false;
5591 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005592 }
5593 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5594 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005595 // We have consumed all the buffers of this track.
5596 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005597 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005598 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005599 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5600 } else {
5601 audioHALFrames = 0;
5602 }
5603
Andy Hung818e7a32016-02-16 18:08:07 -08005604 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005605 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005606 track->presentationComplete(framesWritten, audioHALFrames) ||
5607 track->isPaused()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005608 if (track->isStopping_2()) {
5609 track->mState = TrackBase::STOPPED;
5610 }
Eric Laurent81784c32012-11-19 14:55:58 -08005611 if (track->isStopped()) {
5612 track->reset();
5613 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005614 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005615 }
5616 } else {
5617 // No buffers for this track. Give it a few chances to
5618 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005619 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005620 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005621 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", track->id());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005622 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005623 // indicate to client process that the track was disabled because of underrun;
5624 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005625 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005626 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005627 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5628 "minFrames = %u, mFormat = %#x",
5629 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005630 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005631 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005632 doHwPause = true;
5633 mHwPaused = true;
5634 }
Eric Laurent81784c32012-11-19 14:55:58 -08005635 }
5636 }
5637 }
5638 }
5639
Eric Laurentd1f69b02014-12-15 14:33:13 -08005640 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005641 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005642 for (size_t i = 0; i < mTracks.size(); i++) {
5643 if (mTracks[i]->isFlushPending()) {
5644 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005645 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005646 }
5647 }
5648 }
5649
5650 // make sure the pause/flush/resume sequence is executed in the right order.
5651 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5652 // before flush and then resume HW. This can happen in case of pause/flush/resume
5653 // if resume is received before pause is executed.
5654 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005655 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005656 status_t result = mOutput->stream->pause();
5657 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005658 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005659 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005660 flushHw_l();
5661 }
5662 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005663 status_t result = mOutput->stream->resume();
5664 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005665 }
Eric Laurent81784c32012-11-19 14:55:58 -08005666 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005667 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005668
5669 return mixerStatus;
5670}
5671
5672void AudioFlinger::DirectOutputThread::threadLoop_mix()
5673{
Eric Laurent81784c32012-11-19 14:55:58 -08005674 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005675 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005676 // output audio to hardware
5677 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005678 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005679 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005680 status_t status = mActiveTrack->getNextBuffer(&buffer);
5681 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005682 // no need to pad with 0 for compressed audio
5683 if (audio_has_proportional_frames(mFormat)) {
5684 memset(curBuf, 0, frameCount * mFrameSize);
5685 }
Eric Laurent81784c32012-11-19 14:55:58 -08005686 break;
5687 }
5688 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5689 frameCount -= buffer.frameCount;
5690 curBuf += buffer.frameCount * mFrameSize;
5691 mActiveTrack->releaseBuffer(&buffer);
5692 }
Andy Hung2098f272014-02-27 14:00:06 -08005693 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005694 mSleepTimeUs = 0;
5695 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005696 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005697}
5698
5699void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5700{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005701 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005702 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005703 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005704 return;
5705 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005706 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005707 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005708 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005709 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005710 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005711 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005712 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005713 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005714 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005715 }
5716}
5717
Eric Laurentd1f69b02014-12-15 14:33:13 -08005718void AudioFlinger::DirectOutputThread::threadLoop_exit()
5719{
5720 {
5721 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005722 for (size_t i = 0; i < mTracks.size(); i++) {
5723 if (mTracks[i]->isFlushPending()) {
5724 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005725 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005726 }
5727 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005728 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005729 flushHw_l();
5730 }
5731 }
5732 PlaybackThread::threadLoop_exit();
5733}
5734
5735// must be called with thread mutex locked
5736bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5737{
5738 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005739 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005740
vivek mehta9cd7ad12016-03-17 00:18:29 -07005741 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5742 return !mStandby;
5743 }
5744
Eric Laurentd1f69b02014-12-15 14:33:13 -08005745 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5746 // after a timeout and we will enter standby then.
5747 if (mTracks.size() > 0) {
5748 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005749 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5750 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005751 }
5752
Eric Laurent5cff4032015-05-26 13:49:58 -07005753 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005754}
5755
Eric Laurent10351942014-05-08 18:49:52 -07005756// checkForNewParameter_l() must be called with ThreadBase::mLock held
5757bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5758 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005759{
5760 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005761 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005762
Eric Laurent10351942014-05-08 18:49:52 -07005763 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005764
Eric Laurent10351942014-05-08 18:49:52 -07005765 AudioParameter param = AudioParameter(keyValuePair);
5766 int value;
5767 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5768 // forward device change to effects that have requested to be
5769 // aware of attached audio device.
5770 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005771 a2dpDeviceChanged =
5772 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005773 mOutDevice = value;
5774 for (size_t i = 0; i < mEffectChains.size(); i++) {
5775 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005776 }
5777 }
Eric Laurent81784c32012-11-19 14:55:58 -08005778 }
Eric Laurent10351942014-05-08 18:49:52 -07005779 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5780 // do not accept frame count changes if tracks are open as the track buffer
5781 // size depends on frame count and correct behavior would not be garantied
5782 // if frame count is changed after track creation
5783 if (!mTracks.isEmpty()) {
5784 status = INVALID_OPERATION;
5785 } else {
5786 reconfig = true;
5787 }
5788 }
5789 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005790 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005791 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005792 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005793 mStandby = true;
5794 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005795 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005796 }
5797 if (status == NO_ERROR && reconfig) {
5798 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005799 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005800 }
5801 }
5802
Eric Laurent42537be2016-01-08 17:16:42 -08005803 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005804}
5805
5806uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5807{
5808 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005809 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005810 time = PlaybackThread::activeSleepTimeUs();
5811 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005812 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005813 }
5814 return time;
5815}
5816
5817uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5818{
5819 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005820 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005821 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5822 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005823 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005824 }
5825 return time;
5826}
5827
5828uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5829{
5830 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005831 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005832 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5833 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005834 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005835 }
5836 return time;
5837}
5838
5839void AudioFlinger::DirectOutputThread::cacheParameters_l()
5840{
5841 PlaybackThread::cacheParameters_l();
5842
5843 // use shorter standby delay as on normal output to release
5844 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005845 // no delay on outputs with HW A/V sync
5846 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005847 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005848 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005849 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005850 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005851 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005852 }
Eric Laurent81784c32012-11-19 14:55:58 -08005853}
5854
Eric Laurente659ef42014-09-29 13:06:46 -07005855void AudioFlinger::DirectOutputThread::flushHw_l()
5856{
Phil Burk062e67a2015-02-11 13:40:50 -08005857 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005858 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005859 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005860 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005861}
5862
Andy Hung10cbff12017-02-21 17:30:14 -08005863int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5864 // If a VolumeShaper is active, we must wake up periodically to update volume.
5865 const int64_t NS_PER_MS = 1000000;
5866 return mVolumeShaperActive ?
5867 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5868}
5869
Eric Laurent81784c32012-11-19 14:55:58 -08005870// ----------------------------------------------------------------------------
5871
Eric Laurentbfb1b832013-01-07 09:53:42 -08005872AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005873 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005874 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005875 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005876 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005877 mDrainSequence(0),
5878 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005879{
5880}
5881
5882AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5883{
5884}
5885
5886void AudioFlinger::AsyncCallbackThread::onFirstRef()
5887{
5888 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5889}
5890
5891bool AudioFlinger::AsyncCallbackThread::threadLoop()
5892{
5893 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005894 uint32_t writeAckSequence;
5895 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005896 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005897
5898 {
5899 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005900 while (!((mWriteAckSequence & 1) ||
5901 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005902 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005903 exitPending())) {
5904 mWaitWorkCV.wait(mLock);
5905 }
5906
Eric Laurentbfb1b832013-01-07 09:53:42 -08005907 if (exitPending()) {
5908 break;
5909 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005910 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5911 mWriteAckSequence, mDrainSequence);
5912 writeAckSequence = mWriteAckSequence;
5913 mWriteAckSequence &= ~1;
5914 drainSequence = mDrainSequence;
5915 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005916 asyncError = mAsyncError;
5917 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005918 }
5919 {
Eric Laurent4de95592013-09-26 15:28:21 -07005920 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5921 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005922 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005923 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005924 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005925 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005926 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005927 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005928 if (asyncError) {
5929 playbackThread->onAsyncError();
5930 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005931 }
5932 }
5933 }
5934 return false;
5935}
5936
5937void AudioFlinger::AsyncCallbackThread::exit()
5938{
5939 ALOGV("AsyncCallbackThread::exit");
5940 Mutex::Autolock _l(mLock);
5941 requestExit();
5942 mWaitWorkCV.broadcast();
5943}
5944
Eric Laurent3b4529e2013-09-05 18:09:19 -07005945void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005946{
5947 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005948 // bit 0 is cleared
5949 mWriteAckSequence = sequence << 1;
5950}
5951
5952void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5953{
5954 Mutex::Autolock _l(mLock);
5955 // ignore unexpected callbacks
5956 if (mWriteAckSequence & 2) {
5957 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005958 mWaitWorkCV.signal();
5959 }
5960}
5961
Eric Laurent3b4529e2013-09-05 18:09:19 -07005962void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005963{
5964 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005965 // bit 0 is cleared
5966 mDrainSequence = sequence << 1;
5967}
5968
5969void AudioFlinger::AsyncCallbackThread::resetDraining()
5970{
5971 Mutex::Autolock _l(mLock);
5972 // ignore unexpected callbacks
5973 if (mDrainSequence & 2) {
5974 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005975 mWaitWorkCV.signal();
5976 }
5977}
5978
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005979void AudioFlinger::AsyncCallbackThread::setAsyncError()
5980{
5981 Mutex::Autolock _l(mLock);
5982 mAsyncError = true;
5983 mWaitWorkCV.signal();
5984}
5985
Eric Laurentbfb1b832013-01-07 09:53:42 -08005986
5987// ----------------------------------------------------------------------------
5988AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005989 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5990 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005991 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5992 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005993{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005994 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005995 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005996 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005997}
5998
Eric Laurentbfb1b832013-01-07 09:53:42 -08005999void AudioFlinger::OffloadThread::threadLoop_exit()
6000{
6001 if (mFlushPending || mHwPaused) {
6002 // If a flush is pending or track was paused, just discard buffered data
6003 flushHw_l();
6004 } else {
6005 mMixerStatus = MIXER_DRAIN_ALL;
6006 threadLoop_drain();
6007 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006008 if (mUseAsyncWrite) {
6009 ALOG_ASSERT(mCallbackThread != 0);
6010 mCallbackThread->exit();
6011 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006012 PlaybackThread::threadLoop_exit();
6013}
6014
6015AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6016 Vector< sp<Track> > *tracksToRemove
6017)
6018{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006019 size_t count = mActiveTracks.size();
6020
6021 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006022 bool doHwPause = false;
6023 bool doHwResume = false;
6024
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006025 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006026
Eric Laurentbfb1b832013-01-07 09:53:42 -08006027 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006028 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006029 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006030#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006031 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006032#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006033 // Only consider last track started for volume and mixer state control.
6034 // In theory an older track could underrun and restart after the new one starts
6035 // but as we only care about the transition phase between two tracks on a
6036 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006037 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006038 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006039
Haynes Mathew George7844f672014-01-15 12:32:55 -08006040 if (track->isInvalid()) {
6041 ALOGW("An invalidated track shouldn't be in active list");
6042 tracksToRemove->add(track);
6043 continue;
6044 }
6045
6046 if (track->mState == TrackBase::IDLE) {
6047 ALOGW("An idle track shouldn't be in active list");
6048 continue;
6049 }
6050
Eric Laurentbfb1b832013-01-07 09:53:42 -08006051 if (track->isPausing()) {
6052 track->setPaused();
6053 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006054 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006055 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006056 mHwPaused = true;
6057 }
6058 // If we were part way through writing the mixbuffer to
6059 // the HAL we must save this until we resume
6060 // BUG - this will be wrong if a different track is made active,
6061 // in that case we want to discard the pending data in the
6062 // mixbuffer and tell the client to present it again when the
6063 // track is resumed
6064 mPausedWriteLength = mCurrentWriteLength;
6065 mPausedBytesRemaining = mBytesRemaining;
6066 mBytesRemaining = 0; // stop writing
6067 }
6068 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006069 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006070 if (track->isStopping_1()) {
6071 track->mRetryCount = kMaxTrackStopRetriesOffload;
6072 } else {
6073 track->mRetryCount = kMaxTrackRetriesOffload;
6074 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006075 track->flushAck();
6076 if (last) {
6077 mFlushPending = true;
6078 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006079 } else if (track->isResumePending()){
6080 track->resumeAck();
6081 if (last) {
6082 if (mPausedBytesRemaining) {
6083 // Need to continue write that was interrupted
6084 mCurrentWriteLength = mPausedWriteLength;
6085 mBytesRemaining = mPausedBytesRemaining;
6086 mPausedBytesRemaining = 0;
6087 }
6088 if (mHwPaused) {
6089 doHwResume = true;
6090 mHwPaused = false;
6091 // threadLoop_mix() will handle the case that we need to
6092 // resume an interrupted write
6093 }
6094 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006095 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006096
Eric Laurent3df841a2016-07-15 15:15:40 -07006097 mLeftVolFloat = mRightVolFloat = -1.0;
6098
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006099 // Do not handle new data in this iteration even if track->framesReady()
6100 mixerStatus = MIXER_TRACKS_ENABLED;
6101 }
6102 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006103 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006104 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006105 if (track->mFillingUpStatus == Track::FS_FILLED) {
6106 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006107 if (last) {
6108 // make sure processVolume_l() will apply new volume even if 0
6109 mLeftVolFloat = mRightVolFloat = -1.0;
6110 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006111 }
6112
6113 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006114 sp<Track> previousTrack = mPreviousTrack.promote();
6115 if (previousTrack != 0) {
6116 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006117 // Flush any data still being written from last track
6118 mBytesRemaining = 0;
6119 if (mPausedBytesRemaining) {
6120 // Last track was paused so we also need to flush saved
6121 // mixbuffer state and invalidate track so that it will
6122 // re-submit that unwritten data when it is next resumed
6123 mPausedBytesRemaining = 0;
6124 // Invalidate is a bit drastic - would be more efficient
6125 // to have a flag to tell client that some of the
6126 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006127 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006128 }
6129 // flush data already sent to the DSP if changing audio session as audio
6130 // comes from a different source. Also invalidate previous track to force a
6131 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006132 if (previousTrack->sessionId() != track->sessionId()) {
6133 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006134 }
6135 }
6136 }
6137 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006138 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006139 if (track->isStopping_1()) {
6140 track->mRetryCount = kMaxTrackStopRetriesOffload;
6141 } else {
6142 track->mRetryCount = kMaxTrackRetriesOffload;
6143 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006144 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006145 mixerStatus = MIXER_TRACKS_READY;
6146 }
6147 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006148 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006149 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006150 if (--(track->mRetryCount) <= 0) {
6151 // Hardware buffer can hold a large amount of audio so we must
6152 // wait for all current track's data to drain before we say
6153 // that the track is stopped.
6154 if (mBytesRemaining == 0) {
6155 // Only start draining when all data in mixbuffer
6156 // has been written
6157 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6158 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6159 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6160 if (last && !mStandby) {
6161 // do not modify drain sequence if we are already draining. This happens
6162 // when resuming from pause after drain.
6163 if ((mDrainSequence & 1) == 0) {
6164 mSleepTimeUs = 0;
6165 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6166 mixerStatus = MIXER_DRAIN_TRACK;
6167 mDrainSequence += 2;
6168 }
6169 if (mHwPaused) {
6170 // It is possible to move from PAUSED to STOPPING_1 without
6171 // a resume so we must ensure hardware is running
6172 doHwResume = true;
6173 mHwPaused = false;
6174 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006175 }
6176 }
Eric Laurente93cc032016-05-05 10:15:10 -07006177 } else if (last) {
6178 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6179 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006180 }
6181 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006182 // Drain has completed or we are in standby, signal presentation complete
6183 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006184 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006185 uint32_t latency = 0;
6186 status_t result = mOutput->stream->getLatency(&latency);
6187 ALOGE_IF(result != OK,
6188 "Error when retrieving output stream latency: %d", result);
6189 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006190 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006191 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006192 track->presentationComplete(framesWritten, audioHALFrames);
6193 track->reset();
6194 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006195 // DIRECT and OFFLOADED stop resets frame counts.
6196 if (!mUseAsyncWrite) {
6197 // If we don't get explicit drain notification we must
6198 // register discontinuity regardless of whether this is
6199 // the previous (!last) or the upcoming (last) track
6200 // to avoid skipping the discontinuity.
6201 mTimestampVerifier.discontinuity();
6202 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006203 }
6204 } else {
6205 // No buffers for this track. Give it a few chances to
6206 // fill a buffer, then remove it from active list.
6207 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006208 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006209 uint64_t position = 0;
6210 struct timespec unused;
6211 // The running check restarts the retry counter at least once.
6212 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6213 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6214 running = true;
6215 mOffloadUnderrunPosition = position;
6216 }
6217 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006218 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6219 (long long)position, (long long)mOffloadUnderrunPosition);
6220 }
6221 if (running) { // still running, give us more time.
6222 track->mRetryCount = kMaxTrackRetriesOffload;
6223 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006224 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6225 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006226 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006227 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006228 // it will then automatically call start() when data is available
6229 track->disable();
6230 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006231 } else if (last){
6232 mixerStatus = MIXER_TRACKS_ENABLED;
6233 }
6234 }
6235 }
6236 // compute volume for this track
6237 processVolume_l(track, last);
6238 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006239
Eric Laurentea0fade2013-10-04 16:23:48 -07006240 // make sure the pause/flush/resume sequence is executed in the right order.
6241 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6242 // before flush and then resume HW. This can happen in case of pause/flush/resume
6243 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006244 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006245 status_t result = mOutput->stream->pause();
6246 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006247 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006248 if (mFlushPending) {
6249 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006250 }
Eric Laurentfd477972013-10-25 18:10:40 -07006251 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006252 status_t result = mOutput->stream->resume();
6253 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006254 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006255
Eric Laurentbfb1b832013-01-07 09:53:42 -08006256 // remove all the tracks that need to be...
6257 removeTracks_l(*tracksToRemove);
6258
6259 return mixerStatus;
6260}
6261
Eric Laurentbfb1b832013-01-07 09:53:42 -08006262// must be called with thread mutex locked
6263bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6264{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006265 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6266 mWriteAckSequence, mDrainSequence);
6267 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006268 return true;
6269 }
6270 return false;
6271}
6272
Eric Laurentbfb1b832013-01-07 09:53:42 -08006273bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6274{
6275 Mutex::Autolock _l(mLock);
6276 return waitingAsyncCallback_l();
6277}
6278
6279void AudioFlinger::OffloadThread::flushHw_l()
6280{
Eric Laurente659ef42014-09-29 13:06:46 -07006281 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006282 // Flush anything still waiting in the mixbuffer
6283 mCurrentWriteLength = 0;
6284 mBytesRemaining = 0;
6285 mPausedWriteLength = 0;
6286 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006287 // reset bytes written count to reflect that DSP buffers are empty after flush.
6288 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006289 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006290
Eric Laurentbfb1b832013-01-07 09:53:42 -08006291 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006292 // discard any pending drain or write ack by incrementing sequence
6293 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6294 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006295 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006296 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6297 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006298 }
6299}
6300
Haynes Mathew George05317d22016-05-03 16:34:26 -07006301void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6302{
6303 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006304 if (PlaybackThread::invalidateTracks_l(streamType)) {
6305 mFlushPending = true;
6306 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006307}
6308
Eric Laurentbfb1b832013-01-07 09:53:42 -08006309// ----------------------------------------------------------------------------
6310
Eric Laurent81784c32012-11-19 14:55:58 -08006311AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006312 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006313 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006314 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006315 mWaitTimeMs(UINT_MAX)
6316{
6317 addOutputTrack(mainThread);
6318}
6319
6320AudioFlinger::DuplicatingThread::~DuplicatingThread()
6321{
6322 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6323 mOutputTracks[i]->destroy();
6324 }
6325}
6326
6327void AudioFlinger::DuplicatingThread::threadLoop_mix()
6328{
6329 // mix buffers...
6330 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006331 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006332 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006333 if (mMixerBufferValid) {
6334 memset(mMixerBuffer, 0, mMixerBufferSize);
6335 } else {
6336 memset(mSinkBuffer, 0, mSinkBufferSize);
6337 }
Eric Laurent81784c32012-11-19 14:55:58 -08006338 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006339 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006340 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006341 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006342 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006343}
6344
6345void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6346{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006347 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006348 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006349 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006350 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006351 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006352 }
6353 } else if (mBytesWritten != 0) {
6354 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6355 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006356 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006357 } else {
6358 // flush remaining overflow buffers in output tracks
6359 writeFrames = 0;
6360 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006361 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006362 }
6363}
6364
Eric Laurentbfb1b832013-01-07 09:53:42 -08006365ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006366{
6367 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006368 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6369
6370 // Consider the first OutputTrack for timestamp and frame counting.
6371
6372 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6373 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6374 // we always claim success.
6375 if (i == 0) {
6376 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6377 ALOGD_IF(correction != 0 && writeFrames != 0,
6378 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6379 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6380 mFramesWritten -= correction;
6381 }
6382
6383 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006384 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006385 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006386 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006387}
6388
6389void AudioFlinger::DuplicatingThread::threadLoop_standby()
6390{
6391 // DuplicatingThread implements standby by stopping all tracks
6392 for (size_t i = 0; i < outputTracks.size(); i++) {
6393 outputTracks[i]->stop();
6394 }
6395}
6396
Andy Hung1bc088a2018-02-09 15:57:31 -08006397void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6398{
6399 MixerThread::dumpInternals(fd, args);
6400
6401 std::stringstream ss;
6402 const size_t numTracks = mOutputTracks.size();
6403 ss << " " << numTracks << " OutputTracks";
6404 if (numTracks > 0) {
6405 ss << ":";
6406 for (const auto &track : mOutputTracks) {
6407 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006408 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006409 if (thread.get() != nullptr) {
6410 ss << thread.get() << ", " << thread->id();
6411 } else {
6412 ss << "null";
6413 }
6414 ss << ")";
6415 }
6416 }
6417 ss << "\n";
6418 std::string result = ss.str();
6419 write(fd, result.c_str(), result.size());
6420}
6421
Eric Laurent81784c32012-11-19 14:55:58 -08006422void AudioFlinger::DuplicatingThread::saveOutputTracks()
6423{
6424 outputTracks = mOutputTracks;
6425}
6426
6427void AudioFlinger::DuplicatingThread::clearOutputTracks()
6428{
6429 outputTracks.clear();
6430}
6431
6432void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6433{
6434 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006435 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6436 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6437 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6438 const size_t frameCount =
6439 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6440 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6441 // from different OutputTracks and their associated MixerThreads (e.g. one may
6442 // nearly empty and the other may be dropping data).
6443
6444 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006445 this,
6446 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006447 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006448 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006449 frameCount,
6450 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006451 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6452 if (status != NO_ERROR) {
6453 ALOGE("addOutputTrack() initCheck failed %d", status);
6454 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006455 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006456 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6457 mOutputTracks.add(outputTrack);
6458 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6459 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006460}
6461
6462void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6463{
6464 Mutex::Autolock _l(mLock);
6465 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6466 if (mOutputTracks[i]->thread() == thread) {
6467 mOutputTracks[i]->destroy();
6468 mOutputTracks.removeAt(i);
6469 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006470 if (thread->getOutput() == mOutput) {
6471 mOutput = NULL;
6472 }
Eric Laurent81784c32012-11-19 14:55:58 -08006473 return;
6474 }
6475 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006476 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006477}
6478
6479// caller must hold mLock
6480void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6481{
6482 mWaitTimeMs = UINT_MAX;
6483 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6484 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6485 if (strong != 0) {
6486 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6487 if (waitTimeMs < mWaitTimeMs) {
6488 mWaitTimeMs = waitTimeMs;
6489 }
6490 }
6491 }
6492}
6493
6494
6495bool AudioFlinger::DuplicatingThread::outputsReady(
6496 const SortedVector< sp<OutputTrack> > &outputTracks)
6497{
6498 for (size_t i = 0; i < outputTracks.size(); i++) {
6499 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6500 if (thread == 0) {
6501 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6502 outputTracks[i].get());
6503 return false;
6504 }
6505 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6506 // see note at standby() declaration
6507 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6508 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6509 thread.get());
6510 return false;
6511 }
6512 }
6513 return true;
6514}
6515
Kevin Rocard12381092018-04-11 09:19:59 -07006516void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6517 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006518{
Kevin Rocard12381092018-04-11 09:19:59 -07006519 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6520 outputTrack->setMetadatas(metadata.tracks);
6521 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006522}
6523
Eric Laurent81784c32012-11-19 14:55:58 -08006524uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6525{
6526 return (mWaitTimeMs * 1000) / 2;
6527}
6528
6529void AudioFlinger::DuplicatingThread::cacheParameters_l()
6530{
6531 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6532 updateWaitTime_l();
6533
6534 MixerThread::cacheParameters_l();
6535}
6536
Eric Laurent6acd1d42017-01-04 14:23:29 -08006537
Eric Laurent81784c32012-11-19 14:55:58 -08006538// ----------------------------------------------------------------------------
6539// Record
6540// ----------------------------------------------------------------------------
6541
6542AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6543 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006544 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006545 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006546 audio_devices_t inDevice,
6547 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006548 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006549 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006550 mInput(input),
6551 mActiveTracks(&this->mLocalLog),
6552 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006553 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006554 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006555 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6556 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006557 // mFastCapture below
6558 , mFastCaptureFutex(0)
6559 // mInputSource
6560 // mPipeSink
6561 // mPipeSource
6562 , mPipeFramesP2(0)
6563 // mPipeMemory
6564 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006565 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006566 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006567{
Glenn Kastend7dca052015-03-05 16:05:54 -08006568 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6569 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006570
Andy Hungc8fddf32018-08-08 18:32:37 -07006571 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6572 mIsMsdDevice = strcmp(
6573 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6574 }
6575
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006576 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006577
Andy Hungc8fddf32018-08-08 18:32:37 -07006578 // TODO: We may also match on address as well as device type for
6579 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
6580 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
6581 "audio.timestamp.corrected_input_devices",
6582 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6583 : AUDIO_DEVICE_NONE));
6584
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006585 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006586 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006587 size_t numCounterOffers = 0;
6588 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006589#if !LOG_NDEBUG
6590 ssize_t index =
6591#else
6592 (void)
6593#endif
6594 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006595 ALOG_ASSERT(index == 0);
6596
6597 // initialize fast capture depending on configuration
6598 bool initFastCapture;
6599 switch (kUseFastCapture) {
6600 case FastCapture_Never:
6601 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006602 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006603 break;
6604 case FastCapture_Always:
6605 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006606 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006607 break;
6608 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006609 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006610 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6611 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6612 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006613 break;
6614 // case FastCapture_Dynamic:
6615 }
6616
6617 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006618 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006619 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006620 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6621 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006622 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006623 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006624 const sp<MemoryDealer> roHeap(readOnlyHeap());
6625 sp<IMemory> pipeMemory;
6626 if ((roHeap == 0) ||
6627 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006628 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6629 ALOGE("not enough memory for pipe buffer size=%zu; "
6630 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6631 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6632 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006633 goto failed;
6634 }
6635 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6636 memset(pipeBuffer, 0, pipeSize);
6637 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6638 const NBAIO_Format offers[1] = {format};
6639 size_t numCounterOffers = 0;
6640 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6641 ALOG_ASSERT(index == 0);
6642 mPipeSink = pipe;
6643 PipeReader *pipeReader = new PipeReader(*pipe);
6644 numCounterOffers = 0;
6645 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6646 ALOG_ASSERT(index == 0);
6647 mPipeSource = pipeReader;
6648 mPipeFramesP2 = pipeFramesP2;
6649 mPipeMemory = pipeMemory;
6650
6651 // create fast capture
6652 mFastCapture = new FastCapture();
6653 FastCaptureStateQueue *sq = mFastCapture->sq();
6654#ifdef STATE_QUEUE_DUMP
6655 // FIXME
6656#endif
6657 FastCaptureState *state = sq->begin();
6658 state->mCblk = NULL;
6659 state->mInputSource = mInputSource.get();
6660 state->mInputSourceGen++;
6661 state->mPipeSink = pipe;
6662 state->mPipeSinkGen++;
6663 state->mFrameCount = mFrameCount;
6664 state->mCommand = FastCaptureState::COLD_IDLE;
6665 // already done in constructor initialization list
6666 //mFastCaptureFutex = 0;
6667 state->mColdFutexAddr = &mFastCaptureFutex;
6668 state->mColdGen++;
6669 state->mDumpState = &mFastCaptureDumpState;
6670#ifdef TEE_SINK
6671 // FIXME
6672#endif
6673 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6674 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6675 sq->end();
6676 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6677
6678 // start the fast capture
6679 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6680 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006681 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006682 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006683#ifdef AUDIO_WATCHDOG
6684 // FIXME
6685#endif
6686
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006687 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006688 }
Andy Hung8946a282018-04-19 20:04:56 -07006689#ifdef TEE_SINK
6690 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6691 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6692#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006693failed: ;
6694
6695 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006696}
6697
Eric Laurent81784c32012-11-19 14:55:58 -08006698AudioFlinger::RecordThread::~RecordThread()
6699{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006700 if (mFastCapture != 0) {
6701 FastCaptureStateQueue *sq = mFastCapture->sq();
6702 FastCaptureState *state = sq->begin();
6703 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6704 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6705 if (old == -1) {
6706 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6707 }
6708 }
6709 state->mCommand = FastCaptureState::EXIT;
6710 sq->end();
6711 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6712 mFastCapture->join();
6713 mFastCapture.clear();
6714 }
6715 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006716 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006717 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006718}
6719
6720void AudioFlinger::RecordThread::onFirstRef()
6721{
Glenn Kastend7dca052015-03-05 16:05:54 -08006722 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006723}
6724
Eric Laurent555530a2017-02-07 18:17:24 -08006725void AudioFlinger::RecordThread::preExit()
6726{
6727 ALOGV(" preExit()");
6728 Mutex::Autolock _l(mLock);
6729 for (size_t i = 0; i < mTracks.size(); i++) {
6730 sp<RecordTrack> track = mTracks[i];
6731 track->invalidate();
6732 }
6733 mActiveTracks.clear();
6734 mStartStopCond.broadcast();
6735}
6736
Eric Laurent81784c32012-11-19 14:55:58 -08006737bool AudioFlinger::RecordThread::threadLoop()
6738{
Eric Laurent81784c32012-11-19 14:55:58 -08006739 nsecs_t lastWarning = 0;
6740
6741 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006742
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006743reacquire_wakelock:
6744 sp<RecordTrack> activeTrack;
6745 {
6746 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006747 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006748 }
6749
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006750 // used to request a deferred sleep, to be executed later while mutex is unlocked
6751 uint32_t sleepUs = 0;
6752
Andy Hung446f4df2019-02-21 12:26:41 -08006753 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
6754
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006755 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08006756 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006757 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006758
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006759 // activeTracks accumulates a copy of a subset of mActiveTracks
6760 Vector< sp<RecordTrack> > activeTracks;
6761
Glenn Kasten735f45f2014-08-18 15:51:59 -07006762 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006763 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006764
Glenn Kasten735f45f2014-08-18 15:51:59 -07006765 // reference to a fast track which is about to be removed
6766 sp<RecordTrack> fastTrackToRemove;
6767
Eric Laurent81784c32012-11-19 14:55:58 -08006768 { // scope for mLock
6769 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006770
Eric Laurent021cf962014-05-13 10:18:14 -07006771 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006772
Eric Laurent000a4192014-01-29 15:17:32 -08006773 // check exitPending here because checkForNewParameters_l() and
6774 // checkForNewParameters_l() can temporarily release mLock
6775 if (exitPending()) {
6776 break;
6777 }
6778
Eric Laurent5c25d562016-07-13 17:17:45 -07006779 // sleep with mutex unlocked
6780 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006781 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006782 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6783 ATRACE_END();
6784 sleepUs = 0;
6785 continue;
6786 }
6787
Glenn Kasten2b806402013-11-20 16:37:38 -08006788 // if no active track(s), then standby and release wakelock
6789 size_t size = mActiveTracks.size();
6790 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006791 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006792 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006793 releaseWakeLock_l();
6794 ALOGV("RecordThread: loop stopping");
6795 // go to sleep
6796 mWaitWorkCV.wait(mLock);
6797 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006798 goto reacquire_wakelock;
6799 }
6800
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006801 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006802 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006803 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006804
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006805 activeTrack = mActiveTracks[i];
6806 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006807 if (activeTrack->isFastTrack()) {
6808 ALOG_ASSERT(fastTrackToRemove == 0);
6809 fastTrackToRemove = activeTrack;
6810 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006811 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006812 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006813 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006814 continue;
6815 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006816
6817 TrackBase::track_state activeTrackState = activeTrack->mState;
6818 switch (activeTrackState) {
6819
6820 case TrackBase::PAUSING:
6821 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006822 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006823 doBroadcast = true;
6824 size--;
6825 continue;
6826
6827 case TrackBase::STARTING_1:
6828 sleepUs = 10000;
6829 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006830 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006831 continue;
6832
6833 case TrackBase::STARTING_2:
6834 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006835 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006836 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006837 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006838 break;
6839
6840 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006841 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006842 break;
6843
Andy Hungce685402018-10-05 17:23:27 -07006844 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6845 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6846 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006847 default:
Andy Hungce685402018-10-05 17:23:27 -07006848 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6849 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006850 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006851
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006852 activeTracks.add(activeTrack);
6853 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006854
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006855 if (activeTrack->isFastTrack()) {
6856 ALOG_ASSERT(!mFastTrackAvail);
6857 ALOG_ASSERT(fastTrack == 0);
6858 fastTrack = activeTrack;
6859 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006860 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006861
Andy Hungdae27702016-10-31 14:01:16 -07006862 mActiveTracks.updatePowerState(this);
6863
Kevin Rocard069c2712018-03-29 19:09:14 -07006864 updateMetadata_l();
6865
Eric Laurent5c25d562016-07-13 17:17:45 -07006866 if (allStopped) {
6867 standbyIfNotAlreadyInStandby();
6868 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006869 if (doBroadcast) {
6870 mStartStopCond.broadcast();
6871 }
6872
6873 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006874 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006875 if (sleepUs == 0) {
6876 sleepUs = kRecordThreadSleepUs;
6877 }
6878 continue;
6879 }
6880 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006881
Eric Laurent81784c32012-11-19 14:55:58 -08006882 lockEffectChains_l(effectChains);
6883 }
6884
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006885 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006886
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006887 size_t size = effectChains.size();
6888 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006889 // thread mutex is not locked, but effect chain is locked
6890 effectChains[i]->process_l();
6891 }
6892
Glenn Kasten735f45f2014-08-18 15:51:59 -07006893 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006894 if (mFastCapture != 0) {
6895 FastCaptureStateQueue *sq = mFastCapture->sq();
6896 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006897 bool didModify = false;
6898 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006899 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6900 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6901 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6902 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6903 if (old == -1) {
6904 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6905 }
6906 }
6907 state->mCommand = FastCaptureState::READ_WRITE;
6908#if 0 // FIXME
6909 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006910 FastThreadDumpState::kSamplingNforLowRamDevice :
6911 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006912#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006913 didModify = true;
6914 }
6915 audio_track_cblk_t *cblkOld = state->mCblk;
6916 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6917 if (cblkNew != cblkOld) {
6918 state->mCblk = cblkNew;
6919 // block until acked if removing a fast track
6920 if (cblkOld != NULL) {
6921 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6922 }
6923 didModify = true;
6924 }
jiabin01c8f562018-07-19 17:47:28 -07006925 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
6926 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
6927 if (state->mFastPatchRecordBufferProvider != abp) {
6928 state->mFastPatchRecordBufferProvider = abp;
6929 state->mFastPatchRecordFormat = fastTrack == 0 ?
6930 AUDIO_FORMAT_INVALID : fastTrack->format();
6931 didModify = true;
6932 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07006933 sq->end(didModify);
6934 if (didModify) {
6935 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006936#if 0
6937 if (kUseFastCapture == FastCapture_Dynamic) {
6938 mNormalSource = mPipeSource;
6939 }
6940#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006941 }
6942 }
6943
Glenn Kasten735f45f2014-08-18 15:51:59 -07006944 // now run the fast track destructor with thread mutex unlocked
6945 fastTrackToRemove.clear();
6946
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006947 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6948 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6949 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6950 // If destination is non-contiguous, first read past the nominal end of buffer, then
6951 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006952
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006953 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006954 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08006955 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006956
6957 // If an NBAIO source is present, use it to read the normal capture's data
6958 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07006959 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006960
6961 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6962 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6963 // we immediately retry the read() to get data and prevent another overflow.
6964 for (int retries = 0; retries <= 2; ++retries) {
6965 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6966 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6967 framesToRead);
6968 if (framesRead != OVERRUN) break;
6969 }
6970
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006971 const ssize_t availableToRead = mPipeSource->availableToRead();
6972 if (availableToRead >= 0) {
6973 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6974 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6975 "more frames to read than fifo size, %zd > %zu",
6976 availableToRead, mPipeFramesP2);
6977 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6978 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6979 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6980 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006981 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6982 }
6983 if (framesRead < 0) {
6984 status_t status = (status_t) framesRead;
6985 switch (status) {
6986 case OVERRUN:
6987 ALOGW("overrun on read from pipe");
6988 framesRead = 0;
6989 break;
6990 case NEGOTIATE:
6991 ALOGE("re-negotiation is needed");
6992 framesRead = -1; // Will cause an attempt to recover.
6993 break;
6994 default:
6995 ALOGE("unknown error %d on read from pipe", status);
6996 break;
6997 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006998 }
6999 // otherwise use the HAL / AudioStreamIn directly
7000 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007001 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007002 size_t bytesRead;
7003 status_t result = mInput->stream->read(
7004 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007005 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007006 if (result < 0) {
7007 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007008 } else {
7009 framesRead = bytesRead / mFrameSize;
7010 }
7011 }
7012
Andy Hung446f4df2019-02-21 12:26:41 -08007013 const int64_t lastIoEndNs = systemTime(); // end IO timing
7014
Andy Hung3f0c9022016-01-15 17:49:46 -08007015 // Update server timestamp with server stats
7016 // systemTime() is optional if the hardware supports timestamps.
7017 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007018 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
Andy Hung3f0c9022016-01-15 17:49:46 -08007019
7020 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007021 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007022 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007023 if (mStandby) {
7024 mTimestampVerifier.discontinuity();
Andy Hungc8fddf32018-08-08 18:32:37 -07007025 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR
7026 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7027
7028 mTimestampVerifier.add(position, time, mSampleRate);
7029
7030 // Correct timestamps
7031 if (isTimestampCorrectionEnabled()) {
7032 ALOGV("TS_BEFORE: %d %lld %lld",
7033 id(), (long long)time, (long long)position);
7034 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7035 position = correctedTimestamp.mFrames;
7036 time = correctedTimestamp.mTimeNs;
7037 ALOGV("TS_AFTER: %d %lld %lld",
7038 id(), (long long)time, (long long)position);
7039 }
7040
Andy Hung3f0c9022016-01-15 17:49:46 -08007041 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7042 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7043 // Note: In general record buffers should tend to be empty in
7044 // a properly running pipeline.
7045 //
7046 // Also, it is not advantageous to call get_presentation_position during the read
7047 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007048 } else {
7049 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007050 }
7051 }
Andy Hunge6c37112019-02-26 17:38:10 -08007052
7053 // From the timestamp, input read latency is negative output write latency.
7054 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7055 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7056 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7057 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7058 mLatencyMs.add(latencyMs);
7059 }
7060
Andy Hung3f0c9022016-01-15 17:49:46 -08007061 // Use this to track timestamp information
7062 // ALOGD("%s", mTimestamp.toString().c_str());
7063
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007064 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007065 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007066 // Force input into standby so that it tries to recover at next read attempt
7067 inputStandBy();
7068 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007069 }
7070 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007071 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007072 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007073 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007074 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007075
Andy Hung446f4df2019-02-21 12:26:41 -08007076 if (audio_has_proportional_frames(mFormat)
7077 && loopCount == lastLoopCountRead + 1) {
7078 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7079 const double jitterMs =
7080 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7081 {framesRead, readPeriodNs},
7082 {0, 0} /* lastTimestamp */, mSampleRate);
7083 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7084
7085 Mutex::Autolock _l(mLock);
7086 mIoJitterMs.add(jitterMs);
7087 mProcessTimeMs.add(processMs);
7088 }
7089 // update timing info.
7090 mLastIoBeginNs = lastIoBeginNs;
7091 mLastIoEndNs = lastIoEndNs;
7092 lastLoopCountRead = loopCount;
7093
Andy Hung8946a282018-04-19 20:04:56 -07007094#ifdef TEE_SINK
7095 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7096#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007097 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007098 {
7099 size_t part1 = mRsmpInFramesP2 - rear;
7100 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007101 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007102 (framesRead - part1) * mFrameSize);
7103 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007104 }
7105 rear = mRsmpInRear += framesRead;
7106
7107 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007108
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007109 // loop over each active track
7110 for (size_t i = 0; i < size; i++) {
7111 activeTrack = activeTracks[i];
7112
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007113 // skip fast tracks, as those are handled directly by FastCapture
7114 if (activeTrack->isFastTrack()) {
7115 continue;
7116 }
7117
Andy Hung73c02e42015-03-29 01:13:58 -07007118 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007119 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7120
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007121 enum {
7122 OVERRUN_UNKNOWN,
7123 OVERRUN_TRUE,
7124 OVERRUN_FALSE
7125 } overrun = OVERRUN_UNKNOWN;
7126
7127 // loop over getNextBuffer to handle circular sink
7128 for (;;) {
7129
7130 activeTrack->mSink.frameCount = ~0;
7131 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7132 size_t framesOut = activeTrack->mSink.frameCount;
7133 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7134
Andy Hung73c02e42015-03-29 01:13:58 -07007135 // check available frames and handle overrun conditions
7136 // if the record track isn't draining fast enough.
7137 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007138 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007139 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7140 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007141 overrun = OVERRUN_TRUE;
7142 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007143 if (framesOut == 0 || framesIn == 0) {
7144 break;
7145 }
7146
Andy Hung6770c6f2015-04-07 13:43:36 -07007147 // Don't allow framesOut to be larger than what is possible with resampling
7148 // from framesIn.
7149 // This isn't strictly necessary but helps limit buffer resizing in
7150 // RecordBufferConverter. TODO: remove when no longer needed.
7151 framesOut = min(framesOut,
7152 destinationFramesPossible(
7153 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007154
7155 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007156 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007157 // straight from RecordThread buffer to RecordTrack buffer.
7158 AudioBufferProvider::Buffer buffer;
7159 buffer.frameCount = framesOut;
7160 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7161 if (status == OK && buffer.frameCount != 0) {
7162 ALOGV_IF(buffer.frameCount != framesOut,
7163 "%s() read less than expected (%zu vs %zu)",
7164 __func__, buffer.frameCount, framesOut);
7165 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007166 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007167 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7168 } else {
7169 framesOut = 0;
7170 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7171 __func__, status, buffer.frameCount);
7172 }
7173 } else {
7174 // process frames from the RecordThread buffer provider to the RecordTrack
7175 // buffer
7176 framesOut = activeTrack->mRecordBufferConverter->convert(
7177 activeTrack->mSink.raw,
7178 activeTrack->mResamplerBufferProvider,
7179 framesOut);
7180 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007181
7182 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7183 overrun = OVERRUN_FALSE;
7184 }
7185
7186 if (activeTrack->mFramesToDrop == 0) {
7187 if (framesOut > 0) {
7188 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007189 // Sanitize before releasing if the track has no access to the source data
7190 // An idle UID receives silence from non virtual devices until active
7191 if (activeTrack->isSilenced()) {
7192 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
7193 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007194 activeTrack->releaseBuffer(&activeTrack->mSink);
7195 }
7196 } else {
7197 // FIXME could do a partial drop of framesOut
7198 if (activeTrack->mFramesToDrop > 0) {
7199 activeTrack->mFramesToDrop -= framesOut;
7200 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007201 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007202 }
7203 } else {
7204 activeTrack->mFramesToDrop += framesOut;
7205 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7206 activeTrack->mSyncStartEvent->isCancelled()) {
7207 ALOGW("Synced record %s, session %d, trigger session %d",
7208 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7209 activeTrack->sessionId(),
7210 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007211 activeTrack->mSyncStartEvent->triggerSession() :
7212 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007213 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007214 }
7215 }
7216 }
7217
7218 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007219 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007220 }
7221 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007222
7223 switch (overrun) {
7224 case OVERRUN_TRUE:
7225 // client isn't retrieving buffers fast enough
7226 if (!activeTrack->setOverflow()) {
7227 nsecs_t now = systemTime();
7228 // FIXME should lastWarning per track?
7229 if ((now - lastWarning) > kWarningThrottleNs) {
7230 ALOGW("RecordThread: buffer overflow");
7231 lastWarning = now;
7232 }
7233 }
7234 break;
7235 case OVERRUN_FALSE:
7236 activeTrack->clearOverflow();
7237 break;
7238 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007239 break;
7240 }
7241
Andy Hung3f0c9022016-01-15 17:49:46 -08007242 // update frame information and push timestamp out
7243 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007244 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007245 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7246 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007247 }
7248
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007249unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007250 // enable changes in effect chain
7251 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007252 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08007253 }
7254
Glenn Kasten93e471f2013-08-19 08:40:07 -07007255 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007256
7257 {
7258 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007259 for (size_t i = 0; i < mTracks.size(); i++) {
7260 sp<RecordTrack> track = mTracks[i];
7261 track->invalidate();
7262 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007263 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007264 mStartStopCond.broadcast();
7265 }
7266
7267 releaseWakeLock();
7268
7269 ALOGV("RecordThread %p exiting", this);
7270 return false;
7271}
7272
Glenn Kasten93e471f2013-08-19 08:40:07 -07007273void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007274{
7275 if (!mStandby) {
7276 inputStandBy();
7277 mStandby = true;
7278 }
7279}
7280
7281void AudioFlinger::RecordThread::inputStandBy()
7282{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007283 // Idle the fast capture if it's currently running
7284 if (mFastCapture != 0) {
7285 FastCaptureStateQueue *sq = mFastCapture->sq();
7286 FastCaptureState *state = sq->begin();
7287 if (!(state->mCommand & FastCaptureState::IDLE)) {
7288 state->mCommand = FastCaptureState::COLD_IDLE;
7289 state->mColdFutexAddr = &mFastCaptureFutex;
7290 state->mColdGen++;
7291 mFastCaptureFutex = 0;
7292 sq->end();
7293 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7294 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7295#if 0
7296 if (kUseFastCapture == FastCapture_Dynamic) {
7297 // FIXME
7298 }
7299#endif
7300#ifdef AUDIO_WATCHDOG
7301 // FIXME
7302#endif
7303 } else {
7304 sq->end(false /*didModify*/);
7305 }
7306 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007307 status_t result = mInput->stream->standby();
7308 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007309
7310 // If going into standby, flush the pipe source.
7311 if (mPipeSource.get() != nullptr) {
7312 const ssize_t flushed = mPipeSource->flush();
7313 if (flushed > 0) {
7314 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7315 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7316 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7317 }
7318 }
Eric Laurent81784c32012-11-19 14:55:58 -08007319}
7320
Glenn Kasten05997e22014-03-13 15:08:33 -07007321// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007322sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007323 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007324 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007325 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007326 audio_format_t format,
7327 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007328 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007329 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007330 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007331 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007332 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007333 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007334 status_t *status,
7335 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007336{
Glenn Kasten74935e42013-12-19 08:56:45 -08007337 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007338 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007339 sp<RecordTrack> track;
7340 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007341 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007342 audio_input_flags_t requestedFlags = *flags;
7343 uint32_t sampleRate;
7344
7345 lStatus = initCheck();
7346 if (lStatus != NO_ERROR) {
7347 ALOGE("createRecordTrack_l() audio driver not initialized");
7348 goto Exit;
7349 }
7350
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007351 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7352 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7353 lStatus = BAD_VALUE;
7354 goto Exit;
7355 }
7356
Eric Laurentf14db3c2017-12-08 14:20:36 -08007357 if (*pSampleRate == 0) {
7358 *pSampleRate = mSampleRate;
7359 }
7360 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007361
7362 // special case for FAST flag considered OK if fast capture is present
7363 if (hasFastCapture()) {
7364 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7365 }
7366
Eric Laurentf14db3c2017-12-08 14:20:36 -08007367 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007368 if ((*flags & inputFlags) != *flags) {
7369 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7370 " input flags (%08x)",
7371 *flags, inputFlags);
7372 *flags = (audio_input_flags_t)(*flags & inputFlags);
7373 }
Eric Laurent81784c32012-11-19 14:55:58 -08007374
Glenn Kasten90e58b12013-07-31 16:16:02 -07007375 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007376 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007377 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007378 // we formerly checked for a callback handler (non-0 tid),
7379 // but that is no longer required for TRANSFER_OBTAIN mode
7380 //
Glenn Kasten74105912014-07-03 12:28:53 -07007381 // frame count is not specified, or is exactly the pipe depth
7382 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007383 // PCM data
7384 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007385 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007386 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007387 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007388 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007389 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007390 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007391 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007392 hasFastCapture() &&
7393 // there are sufficient fast track slots available
7394 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007395 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007396 // check compatibility with audio effects.
7397 Mutex::Autolock _l(mLock);
7398 // Do not accept FAST flag if the session has software effects
7399 sp<EffectChain> chain = getEffectChain_l(sessionId);
7400 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007401 audio_input_flags_t old = *flags;
7402 chain->checkInputFlagCompatibility(flags);
7403 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007404 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7405 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007406 }
7407 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007408 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007409 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7410 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007411 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007412 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7413 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007414 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007415 this, frameCount, mFrameCount, mPipeFramesP2,
7416 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007417 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007418 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007419 }
7420 }
7421
Eric Laurentf14db3c2017-12-08 14:20:36 -08007422 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7423 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7424 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7425 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7426 lStatus = BAD_TYPE;
7427 goto Exit;
7428 }
7429
Glenn Kasten74105912014-07-03 12:28:53 -07007430 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007431 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007432 // fast track: frame count is exactly the pipe depth
7433 frameCount = mPipeFramesP2;
7434 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007435 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007436 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007437 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7438 // or 20 ms if there is a fast capture
7439 // TODO This could be a roundupRatio inline, and const
7440 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7441 * sampleRate + mSampleRate - 1) / mSampleRate;
7442 // minimum number of notification periods is at least kMinNotifications,
7443 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7444 static const size_t kMinNotifications = 3;
7445 static const uint32_t kMinMs = 30;
7446 // TODO This could be a roundupRatio inline
7447 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7448 // TODO This could be a roundupRatio inline
7449 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7450 maxNotificationFrames;
7451 const size_t minFrameCount = maxNotificationFrames *
7452 max(kMinNotifications, minNotificationsByMs);
7453 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007454 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7455 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007456 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007457 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007458 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007459 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007460
7461 { // scope for mLock
7462 Mutex::Autolock _l(mLock);
7463
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007464 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007465 format, channelMask, frameCount,
7466 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007467 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007468
Glenn Kasten03003332013-08-06 15:40:54 -07007469 lStatus = track->initCheck();
7470 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007471 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007472 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007473 goto Exit;
7474 }
7475 mTracks.add(track);
7476
Eric Laurent05067782016-06-01 18:27:28 -07007477 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007478 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7479 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7480 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007481 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007482 }
Eric Laurent81784c32012-11-19 14:55:58 -08007483 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007484
Eric Laurent81784c32012-11-19 14:55:58 -08007485 lStatus = NO_ERROR;
7486
7487Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007488 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007489 return track;
7490}
7491
7492status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7493 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007494 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007495{
7496 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7497 sp<ThreadBase> strongMe = this;
7498 status_t status = NO_ERROR;
7499
7500 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007501 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007502 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007503 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007504 triggerSession,
7505 recordTrack->sessionId(),
7506 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007507 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007508 // Sync event can be cancelled by the trigger session if the track is not in a
7509 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007510 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007511 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007512 } else {
7513 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007514 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007515 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007516 }
7517 }
7518
7519 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007520 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007521 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007522 if (recordTrack->isInvalid()) {
7523 recordTrack->clearSyncStartEvent();
7524 return INVALID_OPERATION;
7525 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007526 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7527 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007528 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7529 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007530 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007531 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007532 } else {
7533 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007534 }
7535 return status;
7536 }
7537
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007538 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7539 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7540 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007541 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007542 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007543 status_t status = NO_ERROR;
7544 if (recordTrack->isExternalTrack()) {
7545 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007546 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007547 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007548 if (recordTrack->isInvalid()) {
7549 recordTrack->clearSyncStartEvent();
7550 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7551 recordTrack->mState = TrackBase::STARTING_2;
7552 // STARTING_2 forces destroy to call stopInput.
7553 }
7554 return INVALID_OPERATION;
7555 }
7556 if (recordTrack->mState != TrackBase::STARTING_1) {
7557 ALOGW("%s(%d): unsynchronized mState:%d change",
7558 __func__, recordTrack->id(), recordTrack->mState);
7559 // Someone else has changed state, let them take over,
7560 // leave mState in the new state.
7561 recordTrack->clearSyncStartEvent();
7562 return INVALID_OPERATION;
7563 }
7564 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007565 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007566 ALOGW("%s(%d): startInput failed, status %d",
7567 __func__, recordTrack->id(), status);
7568 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7569 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007570 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007571 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007572 return status;
7573 }
Eric Laurent81784c32012-11-19 14:55:58 -08007574 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007575 // Catch up with current buffer indices if thread is already running.
7576 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7577 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7578 // see previously buffered data before it called start(), but with greater risk of overrun.
7579
Andy Hung73c02e42015-03-29 01:13:58 -07007580 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007581 if (!recordTrack->isDirect()) {
7582 // clear any converter state as new data will be discontinuous
7583 recordTrack->mRecordBufferConverter->reset();
7584 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007585 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007586 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007587 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007588 return status;
7589 }
Eric Laurent81784c32012-11-19 14:55:58 -08007590}
7591
Eric Laurent81784c32012-11-19 14:55:58 -08007592void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7593{
7594 sp<SyncEvent> strongEvent = event.promote();
7595
7596 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007597 sp<RefBase> ptr = strongEvent->cookie().promote();
7598 if (ptr != 0) {
7599 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7600 recordTrack->handleSyncStartEvent(strongEvent);
7601 }
Eric Laurent81784c32012-11-19 14:55:58 -08007602 }
7603}
7604
Glenn Kastena8356f62013-07-25 14:37:52 -07007605bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007606 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007607 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007608 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007609 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007610 return false;
7611 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007612 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007613 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007614
7615 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7616 mWaitWorkCV.broadcast(); // signal thread to stop
7617 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007618 }
Andy Hungce685402018-10-05 17:23:27 -07007619
7620 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007621 ALOGV("Record stopped OK");
7622 return true;
7623 }
Andy Hungce685402018-10-05 17:23:27 -07007624
7625 // don't handle anything - we've been invalidated or restarted and in a different state
7626 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7627 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007628 return false;
7629}
7630
Glenn Kasten0f11b512014-01-31 16:18:54 -08007631bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007632{
7633 return false;
7634}
7635
Glenn Kasten0f11b512014-01-31 16:18:54 -08007636status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007637{
7638#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7639 if (!isValidSyncEvent(event)) {
7640 return BAD_VALUE;
7641 }
7642
Glenn Kastend848eb42016-03-08 13:42:11 -08007643 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007644 status_t ret = NAME_NOT_FOUND;
7645
7646 Mutex::Autolock _l(mLock);
7647
7648 for (size_t i = 0; i < mTracks.size(); i++) {
7649 sp<RecordTrack> track = mTracks[i];
7650 if (eventSession == track->sessionId()) {
7651 (void) track->setSyncEvent(event);
7652 ret = NO_ERROR;
7653 }
7654 }
7655 return ret;
7656#else
7657 return BAD_VALUE;
7658#endif
7659}
7660
jiabin653cc0a2018-01-17 17:54:10 -08007661status_t AudioFlinger::RecordThread::getActiveMicrophones(
7662 std::vector<media::MicrophoneInfo>* activeMicrophones)
7663{
7664 ALOGV("RecordThread::getActiveMicrophones");
7665 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007666 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7667 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007668}
7669
Paul McLean03a6e6a2018-12-04 10:54:13 -07007670status_t AudioFlinger::RecordThread::setMicrophoneDirection(audio_microphone_direction_t direction)
7671{
7672 ALOGV("RecordThread::setMicrophoneDirection");
7673 AutoMutex _l(mLock);
7674 return mInput->stream->setMicrophoneDirection(direction);
7675}
7676
7677status_t AudioFlinger::RecordThread::setMicrophoneFieldDimension(float zoom)
7678{
7679 ALOGV("RecordThread::setMicrophoneFieldDimension");
7680 AutoMutex _l(mLock);
7681 return mInput->stream->setMicrophoneFieldDimension(zoom);
7682}
7683
Kevin Rocard069c2712018-03-29 19:09:14 -07007684void AudioFlinger::RecordThread::updateMetadata_l()
7685{
7686 if (mInput == nullptr || mInput->stream == nullptr ||
7687 !mActiveTracks.readAndClearHasChanged()) {
7688 return;
7689 }
7690 StreamInHalInterface::SinkMetadata metadata;
7691 for (const sp<RecordTrack> &track : mActiveTracks) {
7692 // No track is invalid as this is called after prepareTrack_l in the same critical section
7693 metadata.tracks.push_back({
7694 .source = track->attributes().source,
7695 .gain = 1, // capture tracks do not have volumes
7696 });
7697 }
7698 mInput->stream->updateSinkMetadata(metadata);
7699}
7700
Eric Laurent81784c32012-11-19 14:55:58 -08007701// destroyTrack_l() must be called with ThreadBase::mLock held
7702void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7703{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007704 track->terminate();
7705 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007706 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007707 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007708 removeTrack_l(track);
7709 }
7710}
7711
7712void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7713{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007714 String8 result;
7715 track->appendDump(result, false /* active */);
7716 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7717
Eric Laurent81784c32012-11-19 14:55:58 -08007718 mTracks.remove(track);
7719 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007720 if (track->isFastTrack()) {
7721 ALOG_ASSERT(!mFastTrackAvail);
7722 mFastTrackAvail = true;
7723 }
Eric Laurent81784c32012-11-19 14:55:58 -08007724}
7725
7726void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7727{
7728 dumpInternals(fd, args);
7729 dumpTracks(fd, args);
7730 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007731 dprintf(fd, " Local log:\n");
7732 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007733}
7734
7735void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7736{
Glenn Kasten44182c22015-03-05 17:12:23 -08007737 dumpBase(fd, args);
7738
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007739 AudioStreamIn *input = mInput;
7740 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7741 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08007742 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007743 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007744 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007745 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007746 }
Andy Hungbfa64962017-06-12 14:43:19 -07007747
7748 if (input != nullptr) {
7749 dprintf(fd, " Hal stream dump:\n");
7750 (void)input->stream->dump(fd);
7751 }
7752
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007753 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007754 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007755
Glenn Kasten2f90c512015-12-02 11:40:09 -08007756 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7757 // while we are dumping it. It may be inconsistent, but it won't mutate!
7758 // This is a large object so we place it on the heap.
7759 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007760 const std::unique_ptr<FastCaptureDumpState> copy =
7761 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007762 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007763}
7764
Glenn Kasten0f11b512014-01-31 16:18:54 -08007765void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007766{
Eric Laurent81784c32012-11-19 14:55:58 -08007767 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007768 size_t numtracks = mTracks.size();
7769 size_t numactive = mActiveTracks.size();
7770 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007771 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007772 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007773 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007774 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007775 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007776 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007777 for (size_t i = 0; i < numtracks ; ++i) {
7778 sp<RecordTrack> track = mTracks[i];
7779 if (track != 0) {
7780 bool active = mActiveTracks.indexOf(track) >= 0;
7781 if (active) {
7782 numactiveseen++;
7783 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007784 result.append(prefix);
7785 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007786 }
Eric Laurent81784c32012-11-19 14:55:58 -08007787 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007788 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007789 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007790 }
7791
Marco Nelissenb2208842014-02-07 14:00:50 -08007792 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007793 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007794 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007795 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007796 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007797 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007798 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007799 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007800 result.append(prefix);
7801 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007802 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007803 }
Eric Laurent81784c32012-11-19 14:55:58 -08007804
7805 }
7806 write(fd, result.string(), result.size());
7807}
7808
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007809void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7810{
7811 Mutex::Autolock _l(mLock);
7812 for (size_t i = 0; i < mTracks.size() ; i++) {
7813 sp<RecordTrack> track = mTracks[i];
7814 if (track != 0 && track->uid() == uid) {
7815 track->setSilenced(silenced);
7816 }
7817 }
7818}
Andy Hung73c02e42015-03-29 01:13:58 -07007819
7820void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7821{
7822 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7823 RecordThread *recordThread = (RecordThread *) threadBase.get();
7824 mRsmpInFront = recordThread->mRsmpInRear;
7825 mRsmpInUnrel = 0;
7826}
7827
7828void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7829 size_t *framesAvailable, bool *hasOverrun)
7830{
7831 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7832 RecordThread *recordThread = (RecordThread *) threadBase.get();
7833 const int32_t rear = recordThread->mRsmpInRear;
7834 const int32_t front = mRsmpInFront;
7835 const ssize_t filled = rear - front;
7836
7837 size_t framesIn;
7838 bool overrun = false;
7839 if (filled < 0) {
7840 // should not happen, but treat like a massive overrun and re-sync
7841 framesIn = 0;
7842 mRsmpInFront = rear;
7843 overrun = true;
7844 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7845 framesIn = (size_t) filled;
7846 } else {
7847 // client is not keeping up with server, but give it latest data
7848 framesIn = recordThread->mRsmpInFrames;
7849 mRsmpInFront = /* front = */ rear - framesIn;
7850 overrun = true;
7851 }
7852 if (framesAvailable != NULL) {
7853 *framesAvailable = framesIn;
7854 }
7855 if (hasOverrun != NULL) {
7856 *hasOverrun = overrun;
7857 }
7858}
7859
Eric Laurent81784c32012-11-19 14:55:58 -08007860// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007861status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007862 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007863{
Andy Hung73c02e42015-03-29 01:13:58 -07007864 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007865 if (threadBase == 0) {
7866 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007867 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007868 return NOT_ENOUGH_DATA;
7869 }
7870 RecordThread *recordThread = (RecordThread *) threadBase.get();
7871 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007872 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007873 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007874 // FIXME should not be P2 (don't want to increase latency)
7875 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007876 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007877 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007878 front &= recordThread->mRsmpInFramesP2 - 1;
7879 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007880 if (part1 > (size_t) filled) {
7881 part1 = filled;
7882 }
7883 size_t ask = buffer->frameCount;
7884 ALOG_ASSERT(ask > 0);
7885 if (part1 > ask) {
7886 part1 = ask;
7887 }
7888 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007889 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007890 buffer->raw = NULL;
7891 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007892 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007893 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007894 }
7895
Andy Hung57446612015-04-19 23:56:46 -07007896 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007897 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007898 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007899 return NO_ERROR;
7900}
7901
7902// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007903void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7904 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007905{
Glenn Kasten85948432013-08-19 12:09:05 -07007906 size_t stepCount = buffer->frameCount;
7907 if (stepCount == 0) {
7908 return;
7909 }
Andy Hung73c02e42015-03-29 01:13:58 -07007910 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7911 mRsmpInUnrel -= stepCount;
7912 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007913 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007914 buffer->frameCount = 0;
7915}
7916
Eric Laurentd8365c52017-07-16 15:27:05 -07007917void AudioFlinger::RecordThread::checkBtNrec()
7918{
7919 Mutex::Autolock _l(mLock);
7920 checkBtNrec_l();
7921}
7922
7923void AudioFlinger::RecordThread::checkBtNrec_l()
7924{
7925 // disable AEC and NS if the device is a BT SCO headset supporting those
7926 // pre processings
7927 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7928 mAudioFlinger->btNrecIsOff();
7929 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7930 for (size_t i = 0; i < mEffectChains.size(); i++) {
7931 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7932 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7933 }
7934 }
7935}
7936
Andy Hung97a893e2015-03-29 01:03:07 -07007937
Eric Laurent10351942014-05-08 18:49:52 -07007938bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7939 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007940{
7941 bool reconfig = false;
7942
Eric Laurent10351942014-05-08 18:49:52 -07007943 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007944
Eric Laurent10351942014-05-08 18:49:52 -07007945 audio_format_t reqFormat = mFormat;
7946 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007947 // 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 -07007948 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7949
7950 AudioParameter param = AudioParameter(keyValuePair);
7951 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007952
7953 // scope for AutoPark extends to end of method
7954 AutoPark<FastCapture> park(mFastCapture);
7955
Eric Laurent10351942014-05-08 18:49:52 -07007956 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7957 // channel count change can be requested. Do we mandate the first client defines the
7958 // HAL sampling rate and channel count or do we allow changes on the fly?
7959 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7960 samplingRate = value;
7961 reconfig = true;
7962 }
7963 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007964 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007965 status = BAD_VALUE;
7966 } else {
7967 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007968 reconfig = true;
7969 }
Eric Laurent10351942014-05-08 18:49:52 -07007970 }
7971 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7972 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007973 if (!audio_is_input_channel(mask) ||
7974 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007975 status = BAD_VALUE;
7976 } else {
7977 channelMask = mask;
7978 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007979 }
Eric Laurent10351942014-05-08 18:49:52 -07007980 }
7981 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7982 // do not accept frame count changes if tracks are open as the track buffer
7983 // size depends on frame count and correct behavior would not be guaranteed
7984 // if frame count is changed after track creation
7985 if (mActiveTracks.size() > 0) {
7986 status = INVALID_OPERATION;
7987 } else {
7988 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007989 }
Eric Laurent10351942014-05-08 18:49:52 -07007990 }
7991 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7992 // forward device change to effects that have requested to be
7993 // aware of attached audio device.
7994 for (size_t i = 0; i < mEffectChains.size(); i++) {
7995 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007996 }
Eric Laurent81784c32012-11-19 14:55:58 -08007997
Eric Laurent10351942014-05-08 18:49:52 -07007998 // store input device and output device but do not forward output device to audio HAL.
7999 // Note that status is ignored by the caller for output device
8000 // (see AudioFlinger::setParameters()
8001 if (audio_is_output_devices(value)) {
8002 mOutDevice = value;
8003 status = BAD_VALUE;
8004 } else {
8005 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07008006 if (value != AUDIO_DEVICE_NONE) {
8007 mPrevInDevice = value;
8008 }
Eric Laurentd8365c52017-07-16 15:27:05 -07008009 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008010 }
Eric Laurent10351942014-05-08 18:49:52 -07008011 }
8012 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8013 mAudioSource != (audio_source_t)value) {
8014 // forward device change to effects that have requested to be
8015 // aware of attached audio device.
8016 for (size_t i = 0; i < mEffectChains.size(); i++) {
8017 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08008018 }
Eric Laurent10351942014-05-08 18:49:52 -07008019 mAudioSource = (audio_source_t)value;
8020 }
Glenn Kastene198c362013-08-13 09:13:36 -07008021
Eric Laurent10351942014-05-08 18:49:52 -07008022 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008023 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008024 if (status == INVALID_OPERATION) {
8025 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008026 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008027 }
8028 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008029 if (status == BAD_VALUE) {
8030 uint32_t sRate;
8031 audio_channel_mask_t channelMask;
8032 audio_format_t format;
8033 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8034 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8035 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8036 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8037 status = NO_ERROR;
8038 }
Eric Laurent81784c32012-11-19 14:55:58 -08008039 }
Eric Laurent10351942014-05-08 18:49:52 -07008040 if (status == NO_ERROR) {
8041 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008042 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008043 }
8044 }
Eric Laurent81784c32012-11-19 14:55:58 -08008045 }
Eric Laurent10351942014-05-08 18:49:52 -07008046
Eric Laurent81784c32012-11-19 14:55:58 -08008047 return reconfig;
8048}
8049
8050String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8051{
Eric Laurent81784c32012-11-19 14:55:58 -08008052 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008053 if (initCheck() == NO_ERROR) {
8054 String8 out_s8;
8055 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8056 return out_s8;
8057 }
Eric Laurent81784c32012-11-19 14:55:58 -08008058 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008059 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008060}
8061
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008062void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008063 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8064
8065 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008066
8067 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008068 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008069 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008070 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008071 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008072 desc->mChannelMask = mChannelMask;
8073 desc->mSamplingRate = mSampleRate;
8074 desc->mFormat = mFormat;
8075 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008076 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008077 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008078 break;
8079
Eric Laurent73e26b62015-04-27 16:55:58 -07008080 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008081 default:
8082 break;
8083 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008084 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008085}
8086
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008087void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008088{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008089 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8090 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008091 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008092 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8093 if (audio_is_linear_pcm(mFormat)) {
8094 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8095 mChannelCount, FCC_8);
8096 } else {
8097 // Can have more that FCC_8 channels in encoded streams.
8098 ALOGI("HAL format %#x is not linear pcm", mFormat);
8099 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008100 result = mInput->stream->getFrameSize(&mFrameSize);
8101 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8102 result = mInput->stream->getBufferSize(&mBufferSize);
8103 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008104 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008105 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
8106 "mBufferSize=%lld, mFrameCount=%lld",
8107 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
8108 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008109 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008110 // 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 -07008111 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008112 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008113 // A larger value should allow more old data to be read after a track calls start(),
8114 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008115 //
8116 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008117 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008118 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008119 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008120 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008121
8122 // TODO optimize audio capture buffer sizes ...
8123 // Here we calculate the size of the sliding buffer used as a source
8124 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8125 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8126 // be better to have it derived from the pipe depth in the long term.
8127 // The current value is higher than necessary. However it should not add to latency.
8128
Glenn Kasten85948432013-08-19 12:09:05 -07008129 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008130 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8131 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008132 // if posix_memalign fails, will segv here.
8133 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008134
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008135 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8136 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08008137}
8138
Glenn Kasten5f972c02014-01-13 09:59:31 -08008139uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008140{
8141 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008142 uint32_t result;
8143 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8144 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008145 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008146 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008147}
8148
Eric Laurent4c415062016-06-17 16:14:16 -07008149// hasAudioSession_l() must be called with ThreadBase::mLock held
8150uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08008151{
Eric Laurent81784c32012-11-19 14:55:58 -08008152 uint32_t result = 0;
8153 if (getEffectChain_l(sessionId) != 0) {
8154 result = EFFECT_SESSION;
8155 }
8156
8157 for (size_t i = 0; i < mTracks.size(); ++i) {
8158 if (sessionId == mTracks[i]->sessionId()) {
8159 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07008160 if (mTracks[i]->isFastTrack()) {
8161 result |= FAST_SESSION;
8162 }
Eric Laurent81784c32012-11-19 14:55:58 -08008163 break;
8164 }
8165 }
8166
8167 return result;
8168}
8169
Glenn Kastend848eb42016-03-08 13:42:11 -08008170KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008171{
Glenn Kastend848eb42016-03-08 13:42:11 -08008172 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008173 Mutex::Autolock _l(mLock);
8174 for (size_t j = 0; j < mTracks.size(); ++j) {
8175 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008176 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008177 if (ids.indexOfKey(sessionId) < 0) {
8178 ids.add(sessionId, true);
8179 }
8180 }
8181 return ids;
8182}
8183
8184AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8185{
8186 Mutex::Autolock _l(mLock);
8187 AudioStreamIn *input = mInput;
8188 mInput = NULL;
8189 return input;
8190}
8191
8192// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008193sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008194{
8195 if (mInput == NULL) {
8196 return NULL;
8197 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008198 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008199}
8200
8201status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8202{
8203 // only one chain per input thread
Eric Tan39ec8d62018-07-24 09:49:29 -07008204 if (!mEffectChains.isEmpty()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07008205 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08008206 return INVALID_OPERATION;
8207 }
8208 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008209 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008210 chain->setInBuffer(NULL);
8211 chain->setOutBuffer(NULL);
8212
8213 checkSuspendOnAddEffectChain_l(chain);
8214
Eric Laurent1b928682014-10-02 19:41:47 -07008215 // make sure enabled pre processing effects state is communicated to the HAL as we
8216 // just moved them to a new input stream.
8217 chain->syncHalEffectsState();
8218
Eric Laurent81784c32012-11-19 14:55:58 -08008219 mEffectChains.add(chain);
8220
8221 return NO_ERROR;
8222}
8223
8224size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8225{
8226 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
8227 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008228 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08008229 chain.get(), mEffectChains.size(), this);
8230 if (mEffectChains.size() == 1) {
8231 mEffectChains.removeAt(0);
8232 }
8233 return 0;
8234}
8235
Eric Laurent1c333e22014-05-20 10:48:17 -07008236status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8237 audio_patch_handle_t *handle)
8238{
8239 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008240
8241 // store new device and send to effects
8242 mInDevice = patch->sources[0].ext.device.type;
François Gaffie0c280aa2018-07-25 10:02:15 +02008243 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent296fb132015-05-01 11:38:42 -07008244 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07008245 for (size_t i = 0; i < mEffectChains.size(); i++) {
8246 mEffectChains[i]->setDevice_l(mInDevice);
8247 }
8248
Eric Laurentd8365c52017-07-16 15:27:05 -07008249 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008250
8251 // store new source and send to effects
8252 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8253 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008254 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008255 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008256 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008257 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008258
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008259 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008260 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8261 status = hwDevice->createAudioPatch(patch->num_sources,
8262 patch->sources,
8263 patch->num_sinks,
8264 patch->sinks,
8265 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008266 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008267 char *address;
8268 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8269 address = audio_device_address_to_parameter(
8270 patch->sources[0].ext.device.type,
8271 patch->sources[0].ext.device.address);
8272 } else {
8273 address = (char *)calloc(1, 1);
8274 }
8275 AudioParameter param = AudioParameter(String8(address));
8276 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008277 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008278 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008279 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008280 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008281 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008282 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008283 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008284
François Gaffie0c280aa2018-07-25 10:02:15 +02008285 if ((mInDevice != mPrevInDevice) || (mDeviceId != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008286 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8287 mPrevInDevice = mInDevice;
François Gaffie0c280aa2018-07-25 10:02:15 +02008288 mDeviceId = deviceId;
Eric Laurente8726fe2015-06-26 09:39:24 -07008289 }
Eric Laurent296fb132015-05-01 11:38:42 -07008290
Eric Laurent1c333e22014-05-20 10:48:17 -07008291 return status;
8292}
8293
8294status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8295{
8296 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008297
8298 mInDevice = AUDIO_DEVICE_NONE;
8299
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008300 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008301 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8302 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008303 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008304 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008305 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008306 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008307 }
8308 return status;
8309}
8310
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008311void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008312{
8313 Mutex::Autolock _l(mLock);
8314 mTracks.add(record);
8315}
8316
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008317void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008318{
8319 Mutex::Autolock _l(mLock);
8320 destroyTrack_l(record);
8321}
8322
Mikhail Naganovdc769682018-05-04 15:34:08 -07008323void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008324{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008325 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008326 config->role = AUDIO_PORT_ROLE_SINK;
8327 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8328 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008329 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8330 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8331 config->flags.input = mInput->flags;
8332 }
Eric Laurent83b88082014-06-20 18:31:16 -07008333}
Eric Laurent1c333e22014-05-20 10:48:17 -07008334
Eric Laurent6acd1d42017-01-04 14:23:29 -08008335// ----------------------------------------------------------------------------
8336// Mmap
8337// ----------------------------------------------------------------------------
8338
8339AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8340 : mThread(thread)
8341{
Phil Burk9fabbf82017-08-03 12:02:00 -07008342 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008343}
8344
8345AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8346{
Phil Burk9fabbf82017-08-03 12:02:00 -07008347 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008348}
8349
8350status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8351 struct audio_mmap_buffer_info *info)
8352{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008353 return mThread->createMmapBuffer(minSizeFrames, info);
8354}
8355
8356status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8357{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008358 return mThread->getMmapPosition(position);
8359}
8360
Eric Laurenta54f1282017-07-01 19:39:32 -07008361status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008362 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008363
8364{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008365 return mThread->start(client, handle);
8366}
8367
8368status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8369{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008370 return mThread->stop(handle);
8371}
8372
Eric Laurent18b57012017-02-13 16:23:52 -08008373status_t AudioFlinger::MmapThreadHandle::standby()
8374{
Eric Laurent18b57012017-02-13 16:23:52 -08008375 return mThread->standby();
8376}
8377
Eric Laurent6acd1d42017-01-04 14:23:29 -08008378
8379AudioFlinger::MmapThread::MmapThread(
8380 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8381 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8382 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8383 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008384 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008385 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008386 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008387 mActiveTracks(&this->mLocalLog),
8388 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8389 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008390{
Eric Laurent18b57012017-02-13 16:23:52 -08008391 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008392 readHalParameters_l();
8393}
8394
8395AudioFlinger::MmapThread::~MmapThread()
8396{
Eric Laurent18b57012017-02-13 16:23:52 -08008397 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008398}
8399
8400void AudioFlinger::MmapThread::onFirstRef()
8401{
8402 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8403}
8404
8405void AudioFlinger::MmapThread::disconnect()
8406{
Eric Laurent331679c2018-04-16 17:03:16 -07008407 ActiveTracks<MmapTrack> activeTracks;
8408 {
8409 Mutex::Autolock _l(mLock);
8410 for (const sp<MmapTrack> &t : mActiveTracks) {
8411 activeTracks.add(t);
8412 }
8413 }
8414 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008415 stop(t->portId());
8416 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008417 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008418 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008419 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008420 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008421 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008422 }
8423}
8424
8425
8426void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8427 audio_stream_type_t streamType __unused,
8428 audio_session_t sessionId,
8429 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008430 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008431 audio_port_handle_t portId)
8432{
8433 mAttr = *attr;
8434 mSessionId = sessionId;
8435 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008436 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008437 mPortId = portId;
8438}
8439
8440status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8441 struct audio_mmap_buffer_info *info)
8442{
8443 if (mHalStream == 0) {
8444 return NO_INIT;
8445 }
Eric Laurent18b57012017-02-13 16:23:52 -08008446 mStandby = true;
8447 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008448 return mHalStream->createMmapBuffer(minSizeFrames, info);
8449}
8450
8451status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8452{
8453 if (mHalStream == 0) {
8454 return NO_INIT;
8455 }
8456 return mHalStream->getMmapPosition(position);
8457}
8458
Eric Laurent331679c2018-04-16 17:03:16 -07008459status_t AudioFlinger::MmapThread::exitStandby()
8460{
8461 status_t ret = mHalStream->start();
8462 if (ret != NO_ERROR) {
8463 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8464 return ret;
8465 }
8466 mStandby = false;
8467 return NO_ERROR;
8468}
8469
Eric Laurenta54f1282017-07-01 19:39:32 -07008470status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008471 audio_port_handle_t *handle)
8472{
Eric Laurenta54f1282017-07-01 19:39:32 -07008473 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8474 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008475 if (mHalStream == 0) {
8476 return NO_INIT;
8477 }
8478
8479 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008480
Eric Laurenta54f1282017-07-01 19:39:32 -07008481 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008482 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008483 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008484 }
8485
8486 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8487
8488 audio_io_handle_t io = mId;
8489 if (isOutput()) {
8490 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8491 config.sample_rate = mSampleRate;
8492 config.channel_mask = mChannelMask;
8493 config.format = mFormat;
8494 audio_stream_type_t stream = streamType();
8495 audio_output_flags_t flags =
8496 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008497 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008498 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008499 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8500 mSessionId,
8501 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008502 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008503 client.clientUid,
8504 &config,
8505 flags,
8506 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008507 &portId,
8508 &secondaryOutputs);
8509 ALOGD_IF(!secondaryOutputs.empty(),
8510 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008511 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008512 audio_config_base_t config;
8513 config.sample_rate = mSampleRate;
8514 config.channel_mask = mChannelMask;
8515 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008516 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008517 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8518 mSessionId,
8519 client.clientPid,
8520 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008521 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008522 &config,
8523 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8524 &deviceId,
8525 &portId);
8526 }
8527 // APM should not chose a different input or output stream for the same set of attributes
8528 // and audo configuration
8529 if (ret != NO_ERROR || io != mId) {
8530 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8531 __FUNCTION__, ret, io, mId);
8532 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008533 }
8534
8535 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008536 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008537 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008538 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008539 }
8540
Eric Laurent331679c2018-04-16 17:03:16 -07008541 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008542 // abort if start is rejected by audio policy manager
8543 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008544 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008545 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008546 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008547 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008548 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008549 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008550 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008551 }
Eric Laurent331679c2018-04-16 17:03:16 -07008552 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008553 } else {
8554 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008555 }
8556 return PERMISSION_DENIED;
8557 }
8558
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008559 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8560 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008561 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008562
Eric Laurent4eb58f12018-12-07 16:41:02 -08008563 if (isOutput()) {
8564 // force volume update when a new track is added
8565 mHalVolFloat = -1.0f;
8566 } else if (!track->isSilenced_l()) {
8567 for (const sp<MmapTrack> &t : mActiveTracks) {
8568 if (t->isSilenced_l() && t->uid() != client.clientUid)
8569 t->invalidate();
8570 }
8571 }
8572
8573
Eric Laurent6acd1d42017-01-04 14:23:29 -08008574 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008575 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008576 if (chain != 0) {
8577 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8578 chain->incTrackCnt();
8579 chain->incActiveTrackCnt();
8580 }
8581
8582 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008583 broadcast_l();
8584
Eric Laurenta54f1282017-07-01 19:39:32 -07008585 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008586
8587 return NO_ERROR;
8588}
8589
8590status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8591{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008592 ALOGV("%s handle %d", __FUNCTION__, handle);
8593
8594 if (mHalStream == 0) {
8595 return NO_INIT;
8596 }
8597
Eric Laurenta54f1282017-07-01 19:39:32 -07008598 if (handle == mPortId) {
8599 mHalStream->stop();
8600 return NO_ERROR;
8601 }
8602
Eric Laurent331679c2018-04-16 17:03:16 -07008603 Mutex::Autolock _l(mLock);
8604
Eric Laurent6acd1d42017-01-04 14:23:29 -08008605 sp<MmapTrack> track;
8606 for (const sp<MmapTrack> &t : mActiveTracks) {
8607 if (handle == t->portId()) {
8608 track = t;
8609 break;
8610 }
8611 }
8612 if (track == 0) {
8613 return BAD_VALUE;
8614 }
8615
8616 mActiveTracks.remove(track);
8617
Eric Laurent331679c2018-04-16 17:03:16 -07008618 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008619 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008620 AudioSystem::stopOutput(track->portId());
8621 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008622 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008623 AudioSystem::stopInput(track->portId());
8624 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008625 }
Eric Laurent331679c2018-04-16 17:03:16 -07008626 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008627
8628 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8629 if (chain != 0) {
8630 chain->decActiveTrackCnt();
8631 chain->decTrackCnt();
8632 }
8633
8634 broadcast_l();
8635
Eric Laurent6acd1d42017-01-04 14:23:29 -08008636 return NO_ERROR;
8637}
8638
Eric Laurent18b57012017-02-13 16:23:52 -08008639status_t AudioFlinger::MmapThread::standby()
8640{
8641 ALOGV("%s", __FUNCTION__);
8642
8643 if (mHalStream == 0) {
8644 return NO_INIT;
8645 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008646 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008647 return INVALID_OPERATION;
8648 }
8649 mHalStream->standby();
8650 mStandby = true;
8651 releaseWakeLock();
8652 return NO_ERROR;
8653}
8654
Eric Laurent6acd1d42017-01-04 14:23:29 -08008655
8656void AudioFlinger::MmapThread::readHalParameters_l()
8657{
8658 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8659 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8660 mFormat = mHALFormat;
8661 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8662 result = mHalStream->getFrameSize(&mFrameSize);
8663 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8664 result = mHalStream->getBufferSize(&mBufferSize);
8665 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8666 mFrameCount = mBufferSize / mFrameSize;
8667}
8668
8669bool AudioFlinger::MmapThread::threadLoop()
8670{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008671 checkSilentMode_l();
8672
8673 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8674
8675 while (!exitPending())
8676 {
8677 Mutex::Autolock _l(mLock);
8678 Vector< sp<EffectChain> > effectChains;
8679
8680 if (mSignalPending) {
8681 // A signal was raised while we were unlocked
8682 mSignalPending = false;
8683 } else {
8684 if (mConfigEvents.isEmpty()) {
8685 // we're about to wait, flush the binder command buffer
8686 IPCThreadState::self()->flushCommands();
8687
8688 if (exitPending()) {
8689 break;
8690 }
8691
Eric Laurent6acd1d42017-01-04 14:23:29 -08008692 // wait until we have something to do...
8693 ALOGV("%s going to sleep", myName.string());
8694 mWaitWorkCV.wait(mLock);
8695 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008696
8697 checkSilentMode_l();
8698
8699 continue;
8700 }
8701 }
8702
8703 processConfigEvents_l();
8704
8705 processVolume_l();
8706
8707 checkInvalidTracks_l();
8708
8709 mActiveTracks.updatePowerState(this);
8710
Kevin Rocard069c2712018-03-29 19:09:14 -07008711 updateMetadata_l();
8712
Eric Laurent6acd1d42017-01-04 14:23:29 -08008713 lockEffectChains_l(effectChains);
8714 for (size_t i = 0; i < effectChains.size(); i ++) {
8715 effectChains[i]->process_l();
8716 }
8717 // enable changes in effect chain
8718 unlockEffectChains(effectChains);
8719 // Effect chains will be actually deleted here if they were removed from
8720 // mEffectChains list during mixing or effects processing
8721 }
8722
8723 threadLoop_exit();
8724
8725 if (!mStandby) {
8726 threadLoop_standby();
8727 mStandby = true;
8728 }
8729
Eric Laurent6acd1d42017-01-04 14:23:29 -08008730 ALOGV("Thread %p type %d exiting", this, mType);
8731 return false;
8732}
8733
8734// checkForNewParameter_l() must be called with ThreadBase::mLock held
8735bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8736 status_t& status)
8737{
8738 AudioParameter param = AudioParameter(keyValuePair);
8739 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008740 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008741 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008742 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008743 // forward device change to effects that have requested to be
8744 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008745 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008746 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008747 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008748 }
8749 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008750 if (audio_is_output_devices(device)) {
8751 mOutDevice = device;
8752 if (!isOutput()) {
8753 sendToHal = false;
8754 }
8755 } else {
8756 mInDevice = device;
8757 if (device != AUDIO_DEVICE_NONE) {
8758 mPrevInDevice = value;
8759 }
8760 // TODO: implement and call checkBtNrec_l();
8761 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008762 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008763 if (sendToHal) {
8764 status = mHalStream->setParameters(keyValuePair);
8765 } else {
8766 status = NO_ERROR;
8767 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008768
8769 return false;
8770}
8771
8772String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8773{
8774 Mutex::Autolock _l(mLock);
8775 String8 out_s8;
8776 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8777 return out_s8;
8778 }
8779 return String8();
8780}
8781
8782void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8783 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8784
8785 desc->mIoHandle = mId;
8786
8787 switch (event) {
8788 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008789 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008790 case AUDIO_INPUT_CONFIG_CHANGED:
8791 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008792 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008793 case AUDIO_OUTPUT_CONFIG_CHANGED:
8794 desc->mPatch = mPatch;
8795 desc->mChannelMask = mChannelMask;
8796 desc->mSamplingRate = mSampleRate;
8797 desc->mFormat = mFormat;
8798 desc->mFrameCount = mFrameCount;
8799 desc->mFrameCountHAL = mFrameCount;
8800 desc->mLatency = 0;
8801 break;
8802
8803 case AUDIO_INPUT_CLOSED:
8804 case AUDIO_OUTPUT_CLOSED:
8805 default:
8806 break;
8807 }
8808 mAudioFlinger->ioConfigChanged(event, desc, pid);
8809}
8810
8811status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8812 audio_patch_handle_t *handle)
8813{
8814 status_t status = NO_ERROR;
8815
8816 // store new device and send to effects
8817 audio_devices_t type = AUDIO_DEVICE_NONE;
8818 audio_port_handle_t deviceId;
8819 if (isOutput()) {
8820 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8821 type |= patch->sinks[i].ext.device.type;
8822 }
8823 deviceId = patch->sinks[0].id;
8824 } else {
8825 type = patch->sources[0].ext.device.type;
8826 deviceId = patch->sources[0].id;
8827 }
8828
8829 for (size_t i = 0; i < mEffectChains.size(); i++) {
8830 mEffectChains[i]->setDevice_l(type);
8831 }
8832
8833 if (isOutput()) {
8834 mOutDevice = type;
8835 } else {
8836 mInDevice = type;
8837 // store new source and send to effects
8838 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8839 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8840 for (size_t i = 0; i < mEffectChains.size(); i++) {
8841 mEffectChains[i]->setAudioSource_l(mAudioSource);
8842 }
8843 }
8844 }
8845
8846 if (mAudioHwDev->supportsAudioPatches()) {
8847 status = mHalDevice->createAudioPatch(patch->num_sources,
8848 patch->sources,
8849 patch->num_sinks,
8850 patch->sinks,
8851 handle);
8852 } else {
8853 char *address;
8854 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8855 //FIXME: we only support address on first sink with HAL version < 3.0
8856 address = audio_device_address_to_parameter(
8857 patch->sinks[0].ext.device.type,
8858 patch->sinks[0].ext.device.address);
8859 } else {
8860 address = (char *)calloc(1, 1);
8861 }
8862 AudioParameter param = AudioParameter(String8(address));
8863 free(address);
8864 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8865 if (!isOutput()) {
8866 param.addInt(String8(AudioParameter::keyInputSource),
8867 (int)patch->sinks[0].ext.mix.usecase.source);
8868 }
8869 status = mHalStream->setParameters(param.toString());
8870 *handle = AUDIO_PATCH_HANDLE_NONE;
8871 }
8872
François Gaffie0c280aa2018-07-25 10:02:15 +02008873 if (isOutput() && (mPrevOutDevice != mOutDevice || mDeviceId != deviceId)) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008874 mPrevOutDevice = type;
8875 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008876 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008877 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008878 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008879 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008880 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008881 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008882 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008883 }
François Gaffie0c280aa2018-07-25 10:02:15 +02008884 if (!isOutput() && (mPrevInDevice != mInDevice || mDeviceId != deviceId)) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008885 mPrevInDevice = type;
8886 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008887 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008888 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008889 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008890 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008891 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008892 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008893 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008894 }
8895 return status;
8896}
8897
8898status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8899{
8900 status_t status = NO_ERROR;
8901
8902 mInDevice = AUDIO_DEVICE_NONE;
8903
8904 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8905 supportsAudioPatches : false;
8906
8907 if (supportsAudioPatches) {
8908 status = mHalDevice->releaseAudioPatch(handle);
8909 } else {
8910 AudioParameter param;
8911 param.addInt(String8(AudioParameter::keyRouting), 0);
8912 status = mHalStream->setParameters(param.toString());
8913 }
8914 return status;
8915}
8916
Mikhail Naganovdc769682018-05-04 15:34:08 -07008917void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008918{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008919 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008920 if (isOutput()) {
8921 config->role = AUDIO_PORT_ROLE_SOURCE;
8922 config->ext.mix.hw_module = mAudioHwDev->handle();
8923 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8924 } else {
8925 config->role = AUDIO_PORT_ROLE_SINK;
8926 config->ext.mix.hw_module = mAudioHwDev->handle();
8927 config->ext.mix.usecase.source = mAudioSource;
8928 }
8929}
8930
8931status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8932{
8933 audio_session_t session = chain->sessionId();
8934
8935 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8936 // Attach all tracks with same session ID to this chain.
8937 // indicate all active tracks in the chain
8938 for (const sp<MmapTrack> &track : mActiveTracks) {
8939 if (session == track->sessionId()) {
8940 chain->incTrackCnt();
8941 chain->incActiveTrackCnt();
8942 }
8943 }
8944
8945 chain->setThread(this);
8946 chain->setInBuffer(nullptr);
8947 chain->setOutBuffer(nullptr);
8948 chain->syncHalEffectsState();
8949
8950 mEffectChains.add(chain);
8951 checkSuspendOnAddEffectChain_l(chain);
8952 return NO_ERROR;
8953}
8954
8955size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8956{
8957 audio_session_t session = chain->sessionId();
8958
8959 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8960
8961 for (size_t i = 0; i < mEffectChains.size(); i++) {
8962 if (chain == mEffectChains[i]) {
8963 mEffectChains.removeAt(i);
8964 // detach all active tracks from the chain
8965 // detach all tracks with same session ID from this chain
8966 for (const sp<MmapTrack> &track : mActiveTracks) {
8967 if (session == track->sessionId()) {
8968 chain->decActiveTrackCnt();
8969 chain->decTrackCnt();
8970 }
8971 }
8972 break;
8973 }
8974 }
8975 return mEffectChains.size();
8976}
8977
8978// hasAudioSession_l() must be called with ThreadBase::mLock held
8979uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8980{
8981 uint32_t result = 0;
8982 if (getEffectChain_l(sessionId) != 0) {
8983 result = EFFECT_SESSION;
8984 }
8985
8986 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8987 sp<MmapTrack> track = mActiveTracks[i];
8988 if (sessionId == track->sessionId()) {
8989 result |= TRACK_SESSION;
8990 if (track->isFastTrack()) {
8991 result |= FAST_SESSION;
8992 }
8993 break;
8994 }
8995 }
8996
8997 return result;
8998}
8999
9000void AudioFlinger::MmapThread::threadLoop_standby()
9001{
9002 mHalStream->standby();
9003}
9004
9005void AudioFlinger::MmapThread::threadLoop_exit()
9006{
Phil Burk7dce7282017-09-27 13:51:41 -07009007 // Do not call callback->onTearDown() because it is redundant for thread exit
9008 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009009}
9010
9011status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9012{
9013 return BAD_VALUE;
9014}
9015
9016bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9017{
9018 return false;
9019}
9020
9021status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9022 const effect_descriptor_t *desc, audio_session_t sessionId)
9023{
9024 // No global effect sessions on mmap threads
9025 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
9026 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
9027 desc->name, mThreadName);
9028 return BAD_VALUE;
9029 }
9030
9031 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9032 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9033 desc->name);
9034 return BAD_VALUE;
9035 }
9036 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009037 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9038 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009039 return BAD_VALUE;
9040 }
9041
9042 // Only allow effects without processing load or latency
9043 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9044 return BAD_VALUE;
9045 }
9046
9047 return NO_ERROR;
9048
9049}
9050
9051void AudioFlinger::MmapThread::checkInvalidTracks_l()
9052{
9053 for (const sp<MmapTrack> &track : mActiveTracks) {
9054 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009055 sp<MmapStreamCallback> callback = mCallback.promote();
9056 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009057 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009058 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009059 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009060 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9061 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9062 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009063 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009064 }
9065 }
9066}
9067
9068void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
9069{
9070 dumpInternals(fd, args);
9071 dumpTracks(fd, args);
9072 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009073 dprintf(fd, " Local log:\n");
9074 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009075}
9076
9077void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
9078{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009079 dumpBase(fd, args);
9080
9081 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9082 mAttr.content_type, mAttr.usage, mAttr.source);
9083 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009084 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009085 dprintf(fd, " No active clients\n");
9086 }
9087}
9088
9089void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
9090{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009091 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009092 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009093 dprintf(fd, " %zu Tracks\n", numtracks);
9094 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009095 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009096 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009097 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009098 for (size_t i = 0; i < numtracks ; ++i) {
9099 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009100 result.append(prefix);
9101 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009102 }
9103 } else {
9104 dprintf(fd, "\n");
9105 }
9106 write(fd, result.string(), result.size());
9107}
9108
9109AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9110 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9111 AudioHwDevice *hwDev, AudioStreamOut *output,
9112 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9113 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
9114 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009115 mStreamVolume(1.0),
9116 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009117 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009118{
9119 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9120 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9121 mMasterVolume = audioFlinger->masterVolume_l();
9122 mMasterMute = audioFlinger->masterMute_l();
9123 if (mAudioHwDev) {
9124 if (mAudioHwDev->canSetMasterVolume()) {
9125 mMasterVolume = 1.0;
9126 }
9127
9128 if (mAudioHwDev->canSetMasterMute()) {
9129 mMasterMute = false;
9130 }
9131 }
9132}
9133
9134void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9135 audio_stream_type_t streamType,
9136 audio_session_t sessionId,
9137 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009138 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009139 audio_port_handle_t portId)
9140{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009141 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009142 mStreamType = streamType;
9143}
9144
9145AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9146{
9147 Mutex::Autolock _l(mLock);
9148 AudioStreamOut *output = mOutput;
9149 mOutput = NULL;
9150 return output;
9151}
9152
9153void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9154{
9155 Mutex::Autolock _l(mLock);
9156 // Don't apply master volume in SW if our HAL can do it for us.
9157 if (mAudioHwDev &&
9158 mAudioHwDev->canSetMasterVolume()) {
9159 mMasterVolume = 1.0;
9160 } else {
9161 mMasterVolume = value;
9162 }
9163}
9164
9165void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9166{
9167 Mutex::Autolock _l(mLock);
9168 // Don't apply master mute in SW if our HAL can do it for us.
9169 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9170 mMasterMute = false;
9171 } else {
9172 mMasterMute = muted;
9173 }
9174}
9175
9176void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9177{
9178 Mutex::Autolock _l(mLock);
9179 if (stream == mStreamType) {
9180 mStreamVolume = value;
9181 broadcast_l();
9182 }
9183}
9184
9185float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9186{
9187 Mutex::Autolock _l(mLock);
9188 if (stream == mStreamType) {
9189 return mStreamVolume;
9190 }
9191 return 0.0f;
9192}
9193
9194void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9195{
9196 Mutex::Autolock _l(mLock);
9197 if (stream == mStreamType) {
9198 mStreamMute= muted;
9199 broadcast_l();
9200 }
9201}
9202
9203void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9204{
9205 Mutex::Autolock _l(mLock);
9206 if (streamType == mStreamType) {
9207 for (const sp<MmapTrack> &track : mActiveTracks) {
9208 track->invalidate();
9209 }
9210 broadcast_l();
9211 }
9212}
9213
9214void AudioFlinger::MmapPlaybackThread::processVolume_l()
9215{
9216 float volume;
9217
9218 if (mMasterMute || mStreamMute) {
9219 volume = 0;
9220 } else {
9221 volume = mMasterVolume * mStreamVolume;
9222 }
9223
9224 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009225
9226 // Convert volumes from float to 8.24
9227 uint32_t vol = (uint32_t)(volume * (1 << 24));
9228
9229 // Delegate volume control to effect in track effect chain if needed
9230 // only one effect chain can be present on DirectOutputThread, so if
9231 // there is one, the track is connected to it
9232 if (!mEffectChains.isEmpty()) {
9233 mEffectChains[0]->setVolume_l(&vol, &vol);
9234 volume = (float)vol / (1 << 24);
9235 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009236 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009237 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9238 mHalVolFloat = volume; // HW volume control worked, so update value.
9239 mNoCallbackWarningCount = 0;
9240 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009241 sp<MmapStreamCallback> callback = mCallback.promote();
9242 if (callback != 0) {
9243 int channelCount;
9244 if (isOutput()) {
9245 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9246 } else {
9247 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9248 }
9249 Vector<float> values;
9250 for (int i = 0; i < channelCount; i++) {
9251 values.add(volume);
9252 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009253 mHalVolFloat = volume; // SW volume control worked, so update value.
9254 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009255 mLock.unlock();
9256 callback->onVolumeChanged(mChannelMask, values);
9257 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009258 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009259 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9260 ALOGW("Could not set MMAP stream volume: no volume callback!");
9261 mNoCallbackWarningCount++;
9262 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009263 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009264 }
9265 }
9266}
9267
Kevin Rocard069c2712018-03-29 19:09:14 -07009268void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9269{
9270 if (mOutput == nullptr || mOutput->stream == nullptr ||
9271 !mActiveTracks.readAndClearHasChanged()) {
9272 return;
9273 }
9274 StreamOutHalInterface::SourceMetadata metadata;
9275 for (const sp<MmapTrack> &track : mActiveTracks) {
9276 // No track is invalid as this is called after prepareTrack_l in the same critical section
9277 metadata.tracks.push_back({
9278 .usage = track->attributes().usage,
9279 .content_type = track->attributes().content_type,
9280 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9281 });
9282 }
9283 mOutput->stream->updateSourceMetadata(metadata);
9284}
9285
Eric Laurent6acd1d42017-01-04 14:23:29 -08009286void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9287{
9288 if (!mMasterMute) {
9289 char value[PROPERTY_VALUE_MAX];
9290 if (property_get("ro.audio.silent", value, "0") > 0) {
9291 char *endptr;
9292 unsigned long ul = strtoul(value, &endptr, 0);
9293 if (*endptr == '\0' && ul != 0) {
9294 ALOGD("Silence is golden");
9295 // The setprop command will not allow a property to be changed after
9296 // the first time it is set, so we don't have to worry about un-muting.
9297 setMasterMute_l(true);
9298 }
9299 }
9300 }
9301}
9302
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009303void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9304{
9305 MmapThread::toAudioPortConfig(config);
9306 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9307 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9308 config->flags.output = mOutput->flags;
9309 }
9310}
9311
Eric Laurent6acd1d42017-01-04 14:23:29 -08009312void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9313{
9314 MmapThread::dumpInternals(fd, args);
9315
Glenn Kastend3bb6452016-12-05 18:14:37 -08009316 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9317 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009318 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9319}
9320
9321AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9322 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9323 AudioHwDevice *hwDev, AudioStreamIn *input,
9324 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9325 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9326 mInput(input)
9327{
9328 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9329 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9330}
9331
Eric Laurent331679c2018-04-16 17:03:16 -07009332status_t AudioFlinger::MmapCaptureThread::exitStandby()
9333{
Phil Burkf054fc32018-12-06 09:45:59 -08009334 {
9335 // mInput might have been cleared by clearInput()
9336 Mutex::Autolock _l(mLock);
9337 if (mInput != nullptr && mInput->stream != nullptr) {
9338 mInput->stream->setGain(1.0f);
9339 }
9340 }
Eric Laurent331679c2018-04-16 17:03:16 -07009341 return MmapThread::exitStandby();
9342}
9343
Eric Laurent6acd1d42017-01-04 14:23:29 -08009344AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9345{
9346 Mutex::Autolock _l(mLock);
9347 AudioStreamIn *input = mInput;
9348 mInput = NULL;
9349 return input;
9350}
Kevin Rocard069c2712018-03-29 19:09:14 -07009351
Eric Laurent331679c2018-04-16 17:03:16 -07009352
9353void AudioFlinger::MmapCaptureThread::processVolume_l()
9354{
9355 bool changed = false;
9356 bool silenced = false;
9357
9358 sp<MmapStreamCallback> callback = mCallback.promote();
9359 if (callback == 0) {
9360 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9361 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9362 mNoCallbackWarningCount++;
9363 }
9364 }
9365
9366 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9367 // track is silenced and unmute otherwise
9368 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9369 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9370 changed = true;
9371 silenced = mActiveTracks[i]->isSilenced_l();
9372 }
9373 }
9374
9375 if (changed) {
9376 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9377 }
9378}
9379
Kevin Rocard069c2712018-03-29 19:09:14 -07009380void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9381{
9382 if (mInput == nullptr || mInput->stream == nullptr ||
9383 !mActiveTracks.readAndClearHasChanged()) {
9384 return;
9385 }
9386 StreamInHalInterface::SinkMetadata metadata;
9387 for (const sp<MmapTrack> &track : mActiveTracks) {
9388 // No track is invalid as this is called after prepareTrack_l in the same critical section
9389 metadata.tracks.push_back({
9390 .source = track->attributes().source,
9391 .gain = 1, // capture tracks do not have volumes
9392 });
9393 }
9394 mInput->stream->updateSinkMetadata(metadata);
9395}
9396
Eric Laurent331679c2018-04-16 17:03:16 -07009397void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9398{
9399 Mutex::Autolock _l(mLock);
9400 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9401 if (mActiveTracks[i]->uid() == uid) {
9402 mActiveTracks[i]->setSilenced_l(silenced);
9403 broadcast_l();
9404 }
9405 }
9406}
9407
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009408void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9409{
9410 MmapThread::toAudioPortConfig(config);
9411 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9412 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9413 config->flags.input = mInput->flags;
9414 }
9415}
9416
Glenn Kasten63238ef2015-03-02 15:50:29 -08009417} // namespace android