blob: 6fea8befbfccd1b51a805562f995c3d25853bd75 [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>
Hongwei Wang95e37682019-04-12 11:13:36 -070047#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070048#include <system/audio_effects/effect_ns.h>
49#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051
52// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070053#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080054#include <media/nbaio/AudioStreamOutSink.h>
55#include <media/nbaio/MonoPipe.h>
56#include <media/nbaio/MonoPipeReader.h>
57#include <media/nbaio/Pipe.h>
58#include <media/nbaio/PipeReader.h>
59#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080060#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080061
62#include <powermanager/PowerManager.h>
63
Kevin Rocard7588ff42018-01-08 11:11:30 -080064#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070065#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080066
Eric Laurent81784c32012-11-19 14:55:58 -080067#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080068#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070069#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070070#include <mediautils/SchedulingPolicyService.h>
71#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080072
Eric Laurent81784c32012-11-19 14:55:58 -080073#ifdef ADD_BATTERY_DATA
74#include <media/IMediaPlayerService.h>
75#include <media/IMediaDeathNotifier.h>
76#endif
77
Eric Laurent81784c32012-11-19 14:55:58 -080078#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070079#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080080#include <cpustats/ThreadCpuUsage.h>
81#endif
82
Glenn Kastenc05b8d72016-03-24 09:48:17 -070083#include "AutoPark.h"
84
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080085#include <pthread.h>
86#include "TypedLogger.h"
87
Eric Laurent81784c32012-11-19 14:55:58 -080088// ----------------------------------------------------------------------------
89
90// Note: the following macro is used for extremely verbose logging message. In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well. Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on. Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
102
Andy Hung6770c6f2015-04-07 13:43:36 -0700103// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700104#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700105template <typename T>
106static inline T min(const T& a, const T& b)
107{
108 return a < b ? a : b;
109}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700110
Eric Laurent81784c32012-11-19 14:55:58 -0800111namespace android {
112
113// retry counts for buffer fill timeout
114// 50 * ~20msecs = 1 second
115static const int8_t kMaxTrackRetries = 50;
116static const int8_t kMaxTrackStartupRetries = 50;
117// allow less retry attempts on direct output thread.
118// direct outputs can be a scarce resource in audio hardware and should
119// be released as quickly as possible.
120static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700121
Eric Laurent51716182016-02-29 18:00:56 -0800122
Eric Laurent81784c32012-11-19 14:55:58 -0800123
124// don't warn about blocked writes or record buffer overflows more often than this
125static const nsecs_t kWarningThrottleNs = seconds(5);
126
127// RecordThread loop sleep time upon application overrun or audio HAL read error
128static const int kRecordThreadSleepUs = 5000;
129
Eric Laurent10351942014-05-08 18:49:52 -0700130// maximum time to wait in sendConfigEvent_l() for a status to be received
131static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800132
133// minimum sleep time for the mixer thread loop when tracks are active but in underrun
134static const uint32_t kMinThreadSleepTimeUs = 5000;
135// maximum divider applied to the active sleep time in the mixer thread loop
136static const uint32_t kMaxThreadSleepTimeShift = 2;
137
Andy Hung09a50072014-02-27 14:30:47 -0800138// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700139// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800140static const uint32_t kMinNormalSinkBufferSizeMs = 20;
141// maximum normal sink buffer size
142static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800143
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700144// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
145// FIXME This should be based on experimentally observed scheduling jitter
146static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
147
Eric Laurent972a1732013-09-04 09:42:59 -0700148// Offloaded output thread standby delay: allows track transition without going to standby
149static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
150
Eric Laurent51716182016-02-29 18:00:56 -0800151// Direct output thread minimum sleep time in idle or active(underrun) state
152static const nsecs_t kDirectMinSleepTimeUs = 10000;
153
Glenn Kasten1b291842016-07-18 14:55:21 -0700154// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
155// balance between power consumption and latency, and allows threads to be scheduled reliably
156// by the CFS scheduler.
157// FIXME Express other hardcoded references to 20ms with references to this constant and move
158// it appropriately.
159#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800160
Eric Laurent81784c32012-11-19 14:55:58 -0800161// Whether to use fast mixer
162static const enum {
163 FastMixer_Never, // never initialize or use: for debugging only
164 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
165 // normal mixer multiplier is 1
166 FastMixer_Static, // initialize if needed, then use all the time if initialized,
167 // multiplier is calculated based on min & max normal mixer buffer size
168 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
169 // multiplier is calculated based on min & max normal mixer buffer size
170 // FIXME for FastMixer_Dynamic:
171 // Supporting this option will require fixing HALs that can't handle large writes.
172 // For example, one HAL implementation returns an error from a large write,
173 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
174 // We could either fix the HAL implementations, or provide a wrapper that breaks
175 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
176} kUseFastMixer = FastMixer_Static;
177
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700178// Whether to use fast capture
179static const enum {
180 FastCapture_Never, // never initialize or use: for debugging only
181 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
182 FastCapture_Static, // initialize if needed, then use all the time if initialized
183} kUseFastCapture = FastCapture_Static;
184
Eric Laurent81784c32012-11-19 14:55:58 -0800185// Priorities for requestPriority
186static const int kPriorityAudioApp = 2;
187static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700188static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800189
Glenn Kastenea38ee72016-04-18 11:08:01 -0700190// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
191// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
192// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700193
194// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800195static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800196
Glenn Kasten03490092014-05-27 12:30:54 -0700197// The minimum and maximum allowed values
198static const int kFastTrackMultiplierMin = 1;
199static const int kFastTrackMultiplierMax = 2;
200
201// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
202static int sFastTrackMultiplier = kFastTrackMultiplier;
203
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700204// See Thread::readOnlyHeap().
205// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
206// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
207// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700208static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700209
Eric Laurent81784c32012-11-19 14:55:58 -0800210// ----------------------------------------------------------------------------
211
Glenn Kasten03490092014-05-27 12:30:54 -0700212static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
213
214static void sFastTrackMultiplierInit()
215{
216 char value[PROPERTY_VALUE_MAX];
217 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
218 char *endptr;
219 unsigned long ul = strtoul(value, &endptr, 0);
220 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
221 sFastTrackMultiplier = (int) ul;
222 }
223 }
224}
225
226// ----------------------------------------------------------------------------
227
Eric Laurent81784c32012-11-19 14:55:58 -0800228#ifdef ADD_BATTERY_DATA
229// To collect the amplifier usage
230static void addBatteryData(uint32_t params) {
231 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
232 if (service == NULL) {
233 // it already logged
234 return;
235 }
236
237 service->addBatteryData(params);
238}
239#endif
240
Andy Hung3f0c9022016-01-15 17:49:46 -0800241// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
242struct {
243 // call when you acquire a partial wakelock
244 void acquire(const sp<IBinder> &wakeLockToken) {
245 pthread_mutex_lock(&mLock);
246 if (wakeLockToken.get() == nullptr) {
247 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
248 } else {
249 if (mCount == 0) {
250 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
251 }
252 ++mCount;
253 }
254 pthread_mutex_unlock(&mLock);
255 }
256
257 // call when you release a partial wakelock.
258 void release(const sp<IBinder> &wakeLockToken) {
259 if (wakeLockToken.get() == nullptr) {
260 return;
261 }
262 pthread_mutex_lock(&mLock);
263 if (--mCount < 0) {
264 ALOGE("negative wakelock count");
265 mCount = 0;
266 }
267 pthread_mutex_unlock(&mLock);
268 }
269
270 // retrieves the boottime timebase offset from monotonic.
271 int64_t getBoottimeOffset() {
272 pthread_mutex_lock(&mLock);
273 int64_t boottimeOffset = mBoottimeOffset;
274 pthread_mutex_unlock(&mLock);
275 return boottimeOffset;
276 }
277
278 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
279 // and the selected timebase.
280 // Currently only TIMEBASE_BOOTTIME is allowed.
281 //
282 // This only needs to be called upon acquiring the first partial wakelock
283 // after all other partial wakelocks are released.
284 //
285 // We do an empirical measurement of the offset rather than parsing
286 // /proc/timer_list since the latter is not a formal kernel ABI.
287 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
288 int clockbase;
289 switch (timebase) {
290 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
291 clockbase = SYSTEM_TIME_BOOTTIME;
292 break;
293 default:
294 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
295 break;
296 }
297 // try three times to get the clock offset, choose the one
298 // with the minimum gap in measurements.
299 const int tries = 3;
300 nsecs_t bestGap, measured;
301 for (int i = 0; i < tries; ++i) {
302 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
303 const nsecs_t tbase = systemTime(clockbase);
304 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
305 const nsecs_t gap = tmono2 - tmono;
306 if (i == 0 || gap < bestGap) {
307 bestGap = gap;
308 measured = tbase - ((tmono + tmono2) >> 1);
309 }
310 }
311
312 // to avoid micro-adjusting, we don't change the timebase
313 // unless it is significantly different.
314 //
315 // Assumption: It probably takes more than toleranceNs to
316 // suspend and resume the device.
317 static int64_t toleranceNs = 10000; // 10 us
318 if (llabs(*offset - measured) > toleranceNs) {
319 ALOGV("Adjusting timebase offset old: %lld new: %lld",
320 (long long)*offset, (long long)measured);
321 *offset = measured;
322 }
323 }
324
325 pthread_mutex_t mLock;
326 int32_t mCount;
327 int64_t mBoottimeOffset;
328} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800329
330// ----------------------------------------------------------------------------
331// CPU Stats
332// ----------------------------------------------------------------------------
333
334class CpuStats {
335public:
336 CpuStats();
337 void sample(const String8 &title);
338#ifdef DEBUG_CPU_USAGE
339private:
340 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700341 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800342
Andy Hung16698b82018-08-01 10:48:38 -0700343 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800344
345 int mCpuNum; // thread's current CPU number
346 int mCpukHz; // frequency of thread's current CPU in kHz
347#endif
348};
349
350CpuStats::CpuStats()
351#ifdef DEBUG_CPU_USAGE
352 : mCpuNum(-1), mCpukHz(-1)
353#endif
354{
355}
356
Glenn Kasten0f11b512014-01-31 16:18:54 -0800357void CpuStats::sample(const String8 &title
358#ifndef DEBUG_CPU_USAGE
359 __unused
360#endif
361 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800362#ifdef DEBUG_CPU_USAGE
363 // get current thread's delta CPU time in wall clock ns
364 double wcNs;
365 bool valid = mCpuUsage.sampleAndEnable(wcNs);
366
367 // record sample for wall clock statistics
368 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700369 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800370 }
371
372 // get the current CPU number
373 int cpuNum = sched_getcpu();
374
375 // get the current CPU frequency in kHz
376 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
377
378 // check if either CPU number or frequency changed
379 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
380 mCpuNum = cpuNum;
381 mCpukHz = cpukHz;
382 // ignore sample for purposes of cycles
383 valid = false;
384 }
385
386 // if no change in CPU number or frequency, then record sample for cycle statistics
387 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700388 const double cycles = wcNs * cpukHz * 0.000001;
389 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800390 }
391
Eric Tan5b13ff82018-07-27 11:20:17 -0700392 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800393 // mCpuUsage.elapsed() is expensive, so don't call it every loop
394 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700395 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800396 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700397 const double perLoop = elapsed / (double) n;
398 const double perLoop100 = perLoop * 0.01;
399 const double perLoop1k = perLoop * 0.001;
400 const double mean = mWcStats.getMean();
401 const double stddev = mWcStats.getStdDev();
402 const double minimum = mWcStats.getMin();
403 const double maximum = mWcStats.getMax();
404 const double meanCycles = mHzStats.getMean();
405 const double stddevCycles = mHzStats.getStdDev();
406 const double minCycles = mHzStats.getMin();
407 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800408 mCpuUsage.resetElapsed();
409 mWcStats.reset();
410 mHzStats.reset();
411 ALOGD("CPU usage for %s over past %.1f secs\n"
412 " (%u mixer loops at %.1f mean ms per loop):\n"
413 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
414 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
415 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
416 title.string(),
417 elapsed * .000000001, n, perLoop * .000001,
418 mean * .001,
419 stddev * .001,
420 minimum * .001,
421 maximum * .001,
422 mean / perLoop100,
423 stddev / perLoop100,
424 minimum / perLoop100,
425 maximum / perLoop100,
426 meanCycles / perLoop1k,
427 stddevCycles / perLoop1k,
428 minCycles / perLoop1k,
429 maxCycles / perLoop1k);
430
431 }
432 }
433#endif
434};
435
436// ----------------------------------------------------------------------------
437// ThreadBase
438// ----------------------------------------------------------------------------
439
Glenn Kasten97b7b752014-09-28 13:04:24 -0700440// static
441const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
442{
443 switch (type) {
444 case MIXER:
445 return "MIXER";
446 case DIRECT:
447 return "DIRECT";
448 case DUPLICATING:
449 return "DUPLICATING";
450 case RECORD:
451 return "RECORD";
452 case OFFLOAD:
453 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800454 case MMAP:
455 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700456 default:
457 return "unknown";
458 }
459}
460
Eric Laurent81784c32012-11-19 14:55:58 -0800461AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700462 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800463 : Thread(false /*canCallJava*/),
464 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700465 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700466 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800467 // are set by PlaybackThread::readOutputParameters_l() or
468 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700469 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800470 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700471 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
472 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800473 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700474 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800475 mSystemReady(systemReady),
476 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800477{
Eric Laurent296fb132015-05-01 11:38:42 -0700478 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800479}
480
481AudioFlinger::ThreadBase::~ThreadBase()
482{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700483 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700484 mConfigEvents.clear();
485
Eric Laurent81784c32012-11-19 14:55:58 -0800486 // do not lock the mutex in destructor
487 releaseWakeLock_l();
488 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800489 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800490 binder->unlinkToDeath(mDeathRecipient);
491 }
Andy Hungd0979812019-02-21 15:51:44 -0800492
493 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800494}
495
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700496status_t AudioFlinger::ThreadBase::readyToRun()
497{
498 status_t status = initCheck();
499 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800500 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700501 } else {
502 ALOGE("No working audio driver found.");
503 }
504 return status;
505}
506
Eric Laurent81784c32012-11-19 14:55:58 -0800507void AudioFlinger::ThreadBase::exit()
508{
509 ALOGV("ThreadBase::exit");
510 // do any cleanup required for exit to succeed
511 preExit();
512 {
513 // This lock prevents the following race in thread (uniprocessor for illustration):
514 // if (!exitPending()) {
515 // // context switch from here to exit()
516 // // exit() calls requestExit(), what exitPending() observes
517 // // exit() calls signal(), which is dropped since no waiters
518 // // context switch back from exit() to here
519 // mWaitWorkCV.wait(...);
520 // // now thread is hung
521 // }
522 AutoMutex lock(mLock);
523 requestExit();
524 mWaitWorkCV.broadcast();
525 }
526 // When Thread::requestExitAndWait is made virtual and this method is renamed to
527 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
528 requestExitAndWait();
529}
530
531status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
532{
Eric Laurent81784c32012-11-19 14:55:58 -0800533 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
534 Mutex::Autolock _l(mLock);
535
Eric Laurent10351942014-05-08 18:49:52 -0700536 return sendSetParameterConfigEvent_l(keyValuePairs);
537}
538
539// sendConfigEvent_l() must be called with ThreadBase::mLock held
540// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
541status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
542{
543 status_t status = NO_ERROR;
544
Eric Laurent72e3f392015-05-20 14:43:50 -0700545 if (event->mRequiresSystemReady && !mSystemReady) {
546 event->mWaitStatus = false;
547 mPendingConfigEvents.add(event);
548 return status;
549 }
Eric Laurent10351942014-05-08 18:49:52 -0700550 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700551 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800552 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700553 mLock.unlock();
554 {
555 Mutex::Autolock _l(event->mLock);
556 while (event->mWaitStatus) {
557 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
558 event->mStatus = TIMED_OUT;
559 event->mWaitStatus = false;
560 }
561 }
562 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800563 }
Eric Laurent10351942014-05-08 18:49:52 -0700564 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800565 return status;
566}
567
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700568void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800569{
570 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700571 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800572}
573
574// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700575void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800576{
Andy Hungd0979812019-02-21 15:51:44 -0800577 // The audio statistics history is exponentially weighted to forget events
578 // about five or more seconds in the past. In order to have
579 // crisper statistics for mediametrics, we reset the statistics on
580 // an IoConfigEvent, to reflect different properties for a new device.
581 mIoJitterMs.reset();
582 mLatencyMs.reset();
583 mProcessTimeMs.reset();
584 mTimestampVerifier.discontinuity();
585
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700586 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700587 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800588}
589
Mikhail Naganov83f04272017-02-07 10:45:09 -0800590void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700591{
592 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800593 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700594}
595
Eric Laurent81784c32012-11-19 14:55:58 -0800596// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800597void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
598 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800599{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800600 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700601 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800602}
603
Eric Laurent10351942014-05-08 18:49:52 -0700604// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
605status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800606{
Andy Hung2ddee192015-12-18 17:34:44 -0800607 sp<ConfigEvent> configEvent;
608 AudioParameter param(keyValuePair);
609 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700610 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800611 setMasterMono_l(value != 0);
612 if (param.size() == 1) {
613 return NO_ERROR; // should be a solo parameter - we don't pass down
614 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700615 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800616 configEvent = new SetParameterConfigEvent(param.toString());
617 } else {
618 configEvent = new SetParameterConfigEvent(keyValuePair);
619 }
Eric Laurent10351942014-05-08 18:49:52 -0700620 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700621}
622
Eric Laurent1c333e22014-05-20 10:48:17 -0700623status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
624 const struct audio_patch *patch,
625 audio_patch_handle_t *handle)
626{
627 Mutex::Autolock _l(mLock);
628 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
629 status_t status = sendConfigEvent_l(configEvent);
630 if (status == NO_ERROR) {
631 CreateAudioPatchConfigEventData *data =
632 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
633 *handle = data->mHandle;
634 }
635 return status;
636}
637
638status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
639 const audio_patch_handle_t handle)
640{
641 Mutex::Autolock _l(mLock);
642 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
643 return sendConfigEvent_l(configEvent);
644}
645
646
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700647// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700648void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700649{
Eric Laurent10351942014-05-08 18:49:52 -0700650 bool configChanged = false;
651
Eric Laurent81784c32012-11-19 14:55:58 -0800652 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700653 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700654 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800655 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700656 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700657 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700658 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
659 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800660 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700661 true /*asynchronous*/);
662 if (err != 0) {
663 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700664 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700665 }
666 } break;
667 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700668 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700669 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700670 } break;
671 case CFG_EVENT_SET_PARAMETER: {
672 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
673 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
674 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700675 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
676 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700677 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700678 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700679 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700680 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700681 CreateAudioPatchConfigEventData *data =
682 (CreateAudioPatchConfigEventData *)event->mData.get();
683 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700684 const audio_devices_t newDevice = getDevice();
685 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
Andy Hung9b181952019-02-25 14:53:36 -0800686 (unsigned)oldDevice, toString(oldDevice).c_str(),
687 (unsigned)newDevice, toString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700688 } break;
689 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700690 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700691 ReleaseAudioPatchConfigEventData *data =
692 (ReleaseAudioPatchConfigEventData *)event->mData.get();
693 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700694 const audio_devices_t newDevice = getDevice();
695 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
Andy Hung9b181952019-02-25 14:53:36 -0800696 (unsigned)oldDevice, toString(oldDevice).c_str(),
697 (unsigned)newDevice, toString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700698 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700699 default:
Eric Laurent10351942014-05-08 18:49:52 -0700700 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700701 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800702 }
Eric Laurent10351942014-05-08 18:49:52 -0700703 {
704 Mutex::Autolock _l(event->mLock);
705 if (event->mWaitStatus) {
706 event->mWaitStatus = false;
707 event->mCond.signal();
708 }
709 }
710 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
711 }
712
713 if (configChanged) {
714 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800715 }
Eric Laurent81784c32012-11-19 14:55:58 -0800716}
717
Marco Nelissenb2208842014-02-07 14:00:50 -0800718String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
719 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700720 const audio_channel_representation_t representation =
721 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700722
723 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800724 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700725 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
726 if (output) {
727 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
728 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
729 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
730 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
731 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
732 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
733 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
734 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
735 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
736 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
737 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
738 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
739 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
740 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
741 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
742 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
743 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
744 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700745 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
746 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800747 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
748 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700749 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
750 } else {
751 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
752 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
753 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
754 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
755 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
756 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
757 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
758 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
759 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
760 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
761 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
762 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700763 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
764 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
765 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
766 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
767 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
768 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700769 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
770 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
771 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
772 }
773 const int len = s.length();
774 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700775 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700776 s.unlockBuffer(len - 2); // remove trailing ", "
777 }
778 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800779 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700780 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
781 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
782 return s;
783 default:
784 s.appendFormat("unknown mask, representation:%d bits:%#x",
785 representation, audio_channel_mask_get_bits(mask));
786 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800787 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800788}
789
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700790void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800791{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800792 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
793 this, mThreadName, getTid(), type(), threadTypeToString(type()));
794
Eric Laurent81784c32012-11-19 14:55:58 -0800795 bool locked = AudioFlinger::dumpTryLock(mLock);
796 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800797 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800798 }
799
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700800 dumpBase_l(fd, args);
801 dumpInternals_l(fd, args);
802 dumpTracks_l(fd, args);
803 dumpEffectChains_l(fd, args);
804
805 if (locked) {
806 mLock.unlock();
807 }
808
809 dprintf(fd, " Local log:\n");
810 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
811}
812
813void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
814{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700815 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700816 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700817 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700819 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700820 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700821 dprintf(fd, " Channel count: %u\n", mChannelCount);
822 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800823 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700824 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700825 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700826 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800827 size_t numConfig = mConfigEvents.size();
828 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700829 const size_t SIZE = 256;
830 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800831 for (size_t i = 0; i < numConfig; i++) {
832 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700833 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800834 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700835 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800836 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800838 }
Andy Hung293558a2017-03-21 12:19:20 -0700839 // Note: output device may be used by capture threads for effects such as AEC.
Andy Hung9b181952019-02-25 14:53:36 -0800840 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, toString(mOutDevice).c_str());
841 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, toString(mInDevice).c_str());
842 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800843
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700844 // Dump timestamp statistics for the Thread types that support it.
845 if (mType == RECORD
846 || mType == MIXER
847 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700848 || mType == DIRECT
849 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700850 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700851 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700852 }
853
Andy Hung446f4df2019-02-21 12:26:41 -0800854 if (mLastIoBeginNs > 0) { // MMAP may not set this
855 dprintf(fd, " Last %s occurred (msecs): %lld\n",
856 isOutput() ? "write" : "read",
857 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
858 }
859
860 if (mProcessTimeMs.getN() > 0) {
861 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
862 }
863
864 if (mIoJitterMs.getN() > 0) {
865 dprintf(fd, " Hal %s jitter ms stats: %s\n",
866 isOutput() ? "write" : "read",
867 mIoJitterMs.toString().c_str());
868 }
869
Andy Hunge6c37112019-02-26 17:38:10 -0800870 if (mLatencyMs.getN() > 0) {
871 dprintf(fd, " Threadloop %s latency stats: %s\n",
872 isOutput() ? "write" : "read",
873 mLatencyMs.toString().c_str());
874 }
Eric Laurent81784c32012-11-19 14:55:58 -0800875}
876
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700877void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800878{
879 const size_t SIZE = 256;
880 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800881
Marco Nelissenb2208842014-02-07 14:00:50 -0800882 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000883 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800884 write(fd, buffer, strlen(buffer));
885
Marco Nelissenb2208842014-02-07 14:00:50 -0800886 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800887 sp<EffectChain> chain = mEffectChains[i];
888 if (chain != 0) {
889 chain->dump(fd, args);
890 }
891 }
892}
893
Andy Hungdae27702016-10-31 14:01:16 -0700894void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800895{
896 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700897 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800898}
899
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100900String16 AudioFlinger::ThreadBase::getWakeLockTag()
901{
902 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800903 case MIXER:
904 return String16("AudioMix");
905 case DIRECT:
906 return String16("AudioDirectOut");
907 case DUPLICATING:
908 return String16("AudioDup");
909 case RECORD:
910 return String16("AudioIn");
911 case OFFLOAD:
912 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800913 case MMAP:
914 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800915 default:
916 ALOG_ASSERT(false);
917 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100918 }
919}
920
Andy Hungdae27702016-10-31 14:01:16 -0700921void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800922{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800923 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800924 if (mPowerManager != 0) {
925 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700926 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
927 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700928 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100929 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700930 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700931 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 if (status == NO_ERROR) {
933 mWakeLockToken = binder;
934 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800935 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800936 }
Wei Jia3f273d12015-11-24 09:06:49 -0800937
Andy Hung3f0c9022016-01-15 17:49:46 -0800938 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800939 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
940 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800941}
942
943void AudioFlinger::ThreadBase::releaseWakeLock()
944{
945 Mutex::Autolock _l(mLock);
946 releaseWakeLock_l();
947}
948
949void AudioFlinger::ThreadBase::releaseWakeLock_l()
950{
Andy Hung3f0c9022016-01-15 17:49:46 -0800951 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800952 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800953 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800954 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700955 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
956 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800957 }
958 mWakeLockToken.clear();
959 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800960}
961
962void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700963 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800964 // use checkService() to avoid blocking if power service is not up yet
965 sp<IBinder> binder =
966 defaultServiceManager()->checkService(String16("power"));
967 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800968 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800969 } else {
970 mPowerManager = interface_cast<IPowerManager>(binder);
971 binder->linkToDeath(mDeathRecipient);
972 }
973 }
974}
975
Andy Hungd01b0f12016-11-07 16:10:30 -0800976void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800977 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700978
979#if !LOG_NDEBUG
980 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800981 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700982 s << uid << " ";
983 }
984 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
985#endif
986
Andy Hung438e7572015-12-14 15:51:17 -0800987 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
988 if (mSystemReady) {
989 ALOGE("no wake lock to update, but system ready!");
990 } else {
991 ALOGW("no wake lock to update, system not ready yet");
992 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800993 return;
994 }
995 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800996 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
997 status_t status = mPowerManager->updateWakeLockUids(
998 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
999 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001000 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001001 }
1002}
1003
Eric Laurent81784c32012-11-19 14:55:58 -08001004void AudioFlinger::ThreadBase::clearPowerManager()
1005{
1006 Mutex::Autolock _l(mLock);
1007 releaseWakeLock_l();
1008 mPowerManager.clear();
1009}
1010
Glenn Kasten0f11b512014-01-31 16:18:54 -08001011void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001012{
1013 sp<ThreadBase> thread = mThread.promote();
1014 if (thread != 0) {
1015 thread->clearPowerManager();
1016 }
1017 ALOGW("power manager service died !!!");
1018}
1019
Eric Laurent81784c32012-11-19 14:55:58 -08001020void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001021 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001022{
1023 sp<EffectChain> chain = getEffectChain_l(sessionId);
1024 if (chain != 0) {
1025 if (type != NULL) {
1026 chain->setEffectSuspended_l(type, suspend);
1027 } else {
1028 chain->setEffectSuspendedAll_l(suspend);
1029 }
1030 }
1031
1032 updateSuspendedSessions_l(type, suspend, sessionId);
1033}
1034
1035void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1036{
1037 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1038 if (index < 0) {
1039 return;
1040 }
1041
1042 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1043 mSuspendedSessions.valueAt(index);
1044
1045 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001046 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001047 for (int j = 0; j < desc->mRefCount; j++) {
1048 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1049 chain->setEffectSuspendedAll_l(true);
1050 } else {
1051 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1052 desc->mType.timeLow);
1053 chain->setEffectSuspended_l(&desc->mType, true);
1054 }
1055 }
1056 }
1057}
1058
1059void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1060 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001061 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001062{
1063 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1064
1065 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1066
1067 if (suspend) {
1068 if (index >= 0) {
1069 sessionEffects = mSuspendedSessions.valueAt(index);
1070 } else {
1071 mSuspendedSessions.add(sessionId, sessionEffects);
1072 }
1073 } else {
1074 if (index < 0) {
1075 return;
1076 }
1077 sessionEffects = mSuspendedSessions.valueAt(index);
1078 }
1079
1080
1081 int key = EffectChain::kKeyForSuspendAll;
1082 if (type != NULL) {
1083 key = type->timeLow;
1084 }
1085 index = sessionEffects.indexOfKey(key);
1086
1087 sp<SuspendedSessionDesc> desc;
1088 if (suspend) {
1089 if (index >= 0) {
1090 desc = sessionEffects.valueAt(index);
1091 } else {
1092 desc = new SuspendedSessionDesc();
1093 if (type != NULL) {
1094 desc->mType = *type;
1095 }
1096 sessionEffects.add(key, desc);
1097 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1098 }
1099 desc->mRefCount++;
1100 } else {
1101 if (index < 0) {
1102 return;
1103 }
1104 desc = sessionEffects.valueAt(index);
1105 if (--desc->mRefCount == 0) {
1106 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1107 sessionEffects.removeItemsAt(index);
1108 if (sessionEffects.isEmpty()) {
1109 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1110 sessionId);
1111 mSuspendedSessions.removeItem(sessionId);
1112 }
1113 }
1114 }
1115 if (!sessionEffects.isEmpty()) {
1116 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1117 }
1118}
1119
1120void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1121 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001122 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001123{
1124 Mutex::Autolock _l(mLock);
1125 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1126}
1127
1128void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1129 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001130 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001131{
1132 if (mType != RECORD) {
1133 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1134 // another session. This gives the priority to well behaved effect control panels
1135 // and applications not using global effects.
1136 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1137 // global effects
1138 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1139 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1140 }
1141 }
1142
1143 sp<EffectChain> chain = getEffectChain_l(sessionId);
1144 if (chain != 0) {
1145 chain->checkSuspendOnEffectEnabled(effect, enabled);
1146 }
1147}
1148
Eric Laurent4c415062016-06-17 16:14:16 -07001149// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1150status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1151 const effect_descriptor_t *desc, audio_session_t sessionId)
1152{
1153 // No global effect sessions on record threads
1154 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1155 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1156 desc->name, mThreadName);
1157 return BAD_VALUE;
1158 }
1159 // only pre processing effects on record thread
1160 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1161 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1162 desc->name, mThreadName);
1163 return BAD_VALUE;
1164 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001165
1166 // always allow effects without processing load or latency
1167 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1168 return NO_ERROR;
1169 }
1170
Eric Laurent4c415062016-06-17 16:14:16 -07001171 audio_input_flags_t flags = mInput->flags;
1172 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1173 if (flags & AUDIO_INPUT_FLAG_RAW) {
1174 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1175 desc->name, mThreadName);
1176 return BAD_VALUE;
1177 }
1178 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1179 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1180 desc->name, mThreadName);
1181 return BAD_VALUE;
1182 }
1183 }
1184 return NO_ERROR;
1185}
1186
1187// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1188status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1189 const effect_descriptor_t *desc, audio_session_t sessionId)
1190{
1191 // no preprocessing on playback threads
1192 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1193 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1194 " thread %s", desc->name, mThreadName);
1195 return BAD_VALUE;
1196 }
1197
Eric Laurent3e4de772017-07-16 16:55:08 -07001198 // always allow effects without processing load or latency
1199 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1200 return NO_ERROR;
1201 }
1202
Eric Laurent4c415062016-06-17 16:14:16 -07001203 switch (mType) {
1204 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001205#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001206 // Reject any effect on mixer multichannel sinks.
1207 // TODO: fix both format and multichannel issues with effects.
1208 if (mChannelCount != FCC_2) {
1209 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1210 " thread %s", desc->name, mChannelCount, mThreadName);
1211 return BAD_VALUE;
1212 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001213#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001214 audio_output_flags_t flags = mOutput->flags;
1215 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1216 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1217 // global effects are applied only to non fast tracks if they are SW
1218 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1219 break;
1220 }
1221 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1222 // only post processing on output stage session
1223 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1224 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1225 " on output stage session", desc->name);
1226 return BAD_VALUE;
1227 }
1228 } else {
1229 // no restriction on effects applied on non fast tracks
1230 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1231 break;
1232 }
1233 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001234
Eric Laurent4c415062016-06-17 16:14:16 -07001235 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1236 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1237 desc->name);
1238 return BAD_VALUE;
1239 }
1240 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1241 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1242 " in fast mode", desc->name);
1243 return BAD_VALUE;
1244 }
1245 }
1246 } break;
1247 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001248 // nothing actionable on offload threads, if the effect:
1249 // - is offloadable: the effect can be created
1250 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1251 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001252 break;
1253 case DIRECT:
1254 // Reject any effect on Direct output threads for now, since the format of
1255 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1256 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1257 desc->name, mThreadName);
1258 return BAD_VALUE;
1259 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001260#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001261 // Reject any effect on mixer multichannel sinks.
1262 // TODO: fix both format and multichannel issues with effects.
1263 if (mChannelCount != FCC_2) {
1264 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1265 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1266 return BAD_VALUE;
1267 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001268#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001269 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1270 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1271 " thread %s", desc->name, mThreadName);
1272 return BAD_VALUE;
1273 }
1274 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1275 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1276 " DUPLICATING thread %s", desc->name, mThreadName);
1277 return BAD_VALUE;
1278 }
1279 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1280 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1281 " DUPLICATING thread %s", desc->name, mThreadName);
1282 return BAD_VALUE;
1283 }
1284 break;
1285 default:
1286 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1287 }
1288
1289 return NO_ERROR;
1290}
1291
Eric Laurent81784c32012-11-19 14:55:58 -08001292// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1293sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1294 const sp<AudioFlinger::Client>& client,
1295 const sp<IEffectClient>& effectClient,
1296 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001297 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001298 effect_descriptor_t *desc,
1299 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001300 status_t *status,
1301 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001302{
1303 sp<EffectModule> effect;
1304 sp<EffectHandle> handle;
1305 status_t lStatus;
1306 sp<EffectChain> chain;
1307 bool chainCreated = false;
1308 bool effectCreated = false;
1309 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001310 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001311
1312 lStatus = initCheck();
1313 if (lStatus != NO_ERROR) {
1314 ALOGW("createEffect_l() Audio driver not initialized.");
1315 goto Exit;
1316 }
1317
Eric Laurent81784c32012-11-19 14:55:58 -08001318 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1319
1320 { // scope for mLock
1321 Mutex::Autolock _l(mLock);
1322
Eric Laurent4c415062016-06-17 16:14:16 -07001323 lStatus = checkEffectCompatibility_l(desc, sessionId);
1324 if (lStatus != NO_ERROR) {
1325 goto Exit;
1326 }
1327
Eric Laurent81784c32012-11-19 14:55:58 -08001328 // check for existing effect chain with the requested audio session
1329 chain = getEffectChain_l(sessionId);
1330 if (chain == 0) {
1331 // create a new chain for this session
1332 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1333 chain = new EffectChain(this, sessionId);
1334 addEffectChain_l(chain);
1335 chain->setStrategy(getStrategyForSession_l(sessionId));
1336 chainCreated = true;
1337 } else {
1338 effect = chain->getEffectFromDesc_l(desc);
1339 }
1340
1341 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1342
1343 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001344 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001345 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001346 lStatus = AudioSystem::registerEffect(
1347 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001348 if (lStatus != NO_ERROR) {
1349 goto Exit;
1350 }
1351 effectRegistered = true;
1352 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001353 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001354 if (lStatus != NO_ERROR) {
1355 goto Exit;
1356 }
1357 effectCreated = true;
1358
1359 effect->setDevice(mOutDevice);
1360 effect->setDevice(mInDevice);
1361 effect->setMode(mAudioFlinger->getMode());
1362 effect->setAudioSource(mAudioSource);
1363 }
1364 // create effect handle and connect it to effect module
1365 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001366 lStatus = handle->initCheck();
1367 if (lStatus == OK) {
1368 lStatus = effect->addHandle(handle.get());
1369 }
Eric Laurent81784c32012-11-19 14:55:58 -08001370 if (enabled != NULL) {
1371 *enabled = (int)effect->isEnabled();
1372 }
1373 }
1374
1375Exit:
1376 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1377 Mutex::Autolock _l(mLock);
1378 if (effectCreated) {
1379 chain->removeEffect_l(effect);
1380 }
1381 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001382 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001383 }
1384 if (chainCreated) {
1385 removeEffectChain_l(chain);
1386 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001387 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001388 }
1389
Glenn Kasten9156ef32013-08-06 15:39:08 -07001390 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001391 return handle;
1392}
1393
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001394void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1395 bool unpinIfLast)
1396{
1397 bool remove = false;
1398 sp<EffectModule> effect;
1399 {
1400 Mutex::Autolock _l(mLock);
1401
1402 effect = handle->effect().promote();
1403 if (effect == 0) {
1404 return;
1405 }
1406 // restore suspended effects if the disconnected handle was enabled and the last one.
1407 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1408 if (remove) {
1409 removeEffect_l(effect, true);
1410 }
1411 }
1412 if (remove) {
1413 mAudioFlinger->updateOrphanEffectChains(effect);
1414 AudioSystem::unregisterEffect(effect->id());
1415 if (handle->enabled()) {
1416 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1417 }
1418 }
1419}
1420
Glenn Kastend848eb42016-03-08 13:42:11 -08001421sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1422 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001423{
1424 Mutex::Autolock _l(mLock);
1425 return getEffect_l(sessionId, effectId);
1426}
1427
Glenn Kastend848eb42016-03-08 13:42:11 -08001428sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1429 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001430{
1431 sp<EffectChain> chain = getEffectChain_l(sessionId);
1432 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1433}
1434
1435// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1436// PlaybackThread::mLock held
1437status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1438{
1439 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001440 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001441 sp<EffectChain> chain = getEffectChain_l(sessionId);
1442 bool chainCreated = false;
1443
Eric Laurent5baf2af2013-09-12 17:37:00 -07001444 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001445 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001446 this, effect->desc().name, effect->desc().flags);
1447
Eric Laurent81784c32012-11-19 14:55:58 -08001448 if (chain == 0) {
1449 // create a new chain for this session
1450 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1451 chain = new EffectChain(this, sessionId);
1452 addEffectChain_l(chain);
1453 chain->setStrategy(getStrategyForSession_l(sessionId));
1454 chainCreated = true;
1455 }
1456 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1457
1458 if (chain->getEffectFromId_l(effect->id()) != 0) {
1459 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1460 this, effect->desc().name, chain.get());
1461 return BAD_VALUE;
1462 }
1463
Eric Laurent5baf2af2013-09-12 17:37:00 -07001464 effect->setOffloaded(mType == OFFLOAD, mId);
1465
Eric Laurent81784c32012-11-19 14:55:58 -08001466 status_t status = chain->addEffect_l(effect);
1467 if (status != NO_ERROR) {
1468 if (chainCreated) {
1469 removeEffectChain_l(chain);
1470 }
1471 return status;
1472 }
1473
1474 effect->setDevice(mOutDevice);
1475 effect->setDevice(mInDevice);
1476 effect->setMode(mAudioFlinger->getMode());
1477 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001478
Eric Laurent81784c32012-11-19 14:55:58 -08001479 return NO_ERROR;
1480}
1481
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001482void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001483
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001484 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001485 effect_descriptor_t desc = effect->desc();
1486 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1487 detachAuxEffect_l(effect->id());
1488 }
1489
1490 sp<EffectChain> chain = effect->chain().promote();
1491 if (chain != 0) {
1492 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001493 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001494 removeEffectChain_l(chain);
1495 }
1496 } else {
1497 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1498 }
1499}
1500
1501void AudioFlinger::ThreadBase::lockEffectChains_l(
1502 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1503{
1504 effectChains = mEffectChains;
1505 for (size_t i = 0; i < mEffectChains.size(); i++) {
1506 mEffectChains[i]->lock();
1507 }
1508}
1509
1510void AudioFlinger::ThreadBase::unlockEffectChains(
1511 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1512{
1513 for (size_t i = 0; i < effectChains.size(); i++) {
1514 effectChains[i]->unlock();
1515 }
1516}
1517
Glenn Kastend848eb42016-03-08 13:42:11 -08001518sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001519{
1520 Mutex::Autolock _l(mLock);
1521 return getEffectChain_l(sessionId);
1522}
1523
Glenn Kastend848eb42016-03-08 13:42:11 -08001524sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1525 const
Eric Laurent81784c32012-11-19 14:55:58 -08001526{
1527 size_t size = mEffectChains.size();
1528 for (size_t i = 0; i < size; i++) {
1529 if (mEffectChains[i]->sessionId() == sessionId) {
1530 return mEffectChains[i];
1531 }
1532 }
1533 return 0;
1534}
1535
1536void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1537{
1538 Mutex::Autolock _l(mLock);
1539 size_t size = mEffectChains.size();
1540 for (size_t i = 0; i < size; i++) {
1541 mEffectChains[i]->setMode_l(mode);
1542 }
1543}
1544
Mikhail Naganovdc769682018-05-04 15:34:08 -07001545void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001546{
1547 config->type = AUDIO_PORT_TYPE_MIX;
1548 config->ext.mix.handle = mId;
1549 config->sample_rate = mSampleRate;
1550 config->format = mFormat;
1551 config->channel_mask = mChannelMask;
1552 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1553 AUDIO_PORT_CONFIG_FORMAT;
1554}
1555
Eric Laurent72e3f392015-05-20 14:43:50 -07001556void AudioFlinger::ThreadBase::systemReady()
1557{
1558 Mutex::Autolock _l(mLock);
1559 if (mSystemReady) {
1560 return;
1561 }
1562 mSystemReady = true;
1563
1564 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1565 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1566 }
1567 mPendingConfigEvents.clear();
1568}
1569
Andy Hungdae27702016-10-31 14:01:16 -07001570template <typename T>
1571ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1572 ssize_t index = mActiveTracks.indexOf(track);
1573 if (index >= 0) {
1574 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1575 return index;
1576 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001577 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001578 mActiveTracksGeneration++;
1579 mLatestActiveTrack = track;
1580 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001581 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001582 return mActiveTracks.add(track);
1583}
1584
1585template <typename T>
1586ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1587 ssize_t index = mActiveTracks.remove(track);
1588 if (index < 0) {
1589 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1590 return index;
1591 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001592 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001593 mActiveTracksGeneration++;
1594 --mBatteryCounter[track->uid()].second;
1595 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001596 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001597#ifdef TEE_SINK
1598 track->dumpTee(-1 /* fd */, "_REMOVE");
1599#endif
Andy Hungdae27702016-10-31 14:01:16 -07001600 return index;
1601}
1602
1603template <typename T>
1604void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1605 for (const sp<T> &track : mActiveTracks) {
1606 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001607 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001608 }
1609 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001610 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001611 mActiveTracks.clear();
1612 mLatestActiveTrack.clear();
1613 mBatteryCounter.clear();
1614}
1615
1616template <typename T>
1617void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1618 sp<ThreadBase> thread, bool force) {
1619 // Updates ActiveTracks client uids to the thread wakelock.
1620 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1621 thread->updateWakeLockUids_l(getWakeLockUids());
1622 mLastActiveTracksGeneration = mActiveTracksGeneration;
1623 }
1624
1625 // Updates BatteryNotifier uids
1626 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1627 const uid_t uid = it->first;
1628 ssize_t &previous = it->second.first;
1629 ssize_t &current = it->second.second;
1630 if (current > 0) {
1631 if (previous == 0) {
1632 BatteryNotifier::getInstance().noteStartAudio(uid);
1633 }
1634 previous = current;
1635 ++it;
1636 } else if (current == 0) {
1637 if (previous > 0) {
1638 BatteryNotifier::getInstance().noteStopAudio(uid);
1639 }
1640 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1641 } else /* (current < 0) */ {
1642 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1643 }
1644 }
1645}
Eric Laurent83b88082014-06-20 18:31:16 -07001646
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001647template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001648bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1649 const bool hasChanged = mHasChanged;
1650 mHasChanged = false;
1651 return hasChanged;
1652}
1653
1654template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001655void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1656 const char *funcName, const sp<T> &track) const {
1657 if (mLocalLog != nullptr) {
1658 String8 result;
1659 track->appendDump(result, false /* active */);
1660 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1661 }
1662}
1663
Eric Laurent6acd1d42017-01-04 14:23:29 -08001664void AudioFlinger::ThreadBase::broadcast_l()
1665{
1666 // Thread could be blocked waiting for async
1667 // so signal it to handle state changes immediately
1668 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1669 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1670 mSignalPending = true;
1671 mWaitWorkCV.broadcast();
1672}
1673
Andy Hungd0979812019-02-21 15:51:44 -08001674// Call only from threadLoop() or when it is idle.
1675// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1676void AudioFlinger::ThreadBase::sendStatistics(bool force)
1677{
1678 // Do not log if we have no stats.
1679 // We choose the timestamp verifier because it is the most likely item to be present.
1680 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1681 if (nstats == 0) {
1682 return;
1683 }
1684
1685 // Don't log more frequently than once per 12 hours.
1686 // We use BOOTTIME to include suspend time.
1687 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1688 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1689 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1690 return;
1691 }
1692
1693 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1694 mLastRecordedTimeNs = timeNs;
1695
1696 std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create("audiothread"));
1697
1698#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1699
1700 // thread configuration
1701 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1702 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1703 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1704 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1705 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1706 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1707 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
1708 item->setCString(MM_PREFIX "outDevice", toString(mOutDevice).c_str());
1709 item->setCString(MM_PREFIX "inDevice", toString(mInDevice).c_str());
1710
1711 // thread statistics
1712 if (mIoJitterMs.getN() > 0) {
1713 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1714 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1715 }
1716 if (mProcessTimeMs.getN() > 0) {
1717 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1718 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1719 }
1720 const auto tsjitter = mTimestampVerifier.getJitterMs();
1721 if (tsjitter.getN() > 0) {
1722 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1723 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1724 }
1725 if (mLatencyMs.getN() > 0) {
1726 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1727 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1728 }
1729
1730 item->selfrecord();
1731}
1732
Eric Laurent81784c32012-11-19 14:55:58 -08001733// ----------------------------------------------------------------------------
1734// Playback
1735// ----------------------------------------------------------------------------
1736
1737AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1738 AudioStreamOut* output,
1739 audio_io_handle_t id,
1740 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001741 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001742 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001743 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001744 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001745 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001746 mMixerBuffer(NULL),
1747 mMixerBufferSize(0),
1748 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1749 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001750 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001751 mEffectBuffer(NULL),
1752 mEffectBufferSize(0),
1753 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1754 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001755 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001756 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001757 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001758 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001759 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001760 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001761 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001762 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001763 mMixerStatus(MIXER_IDLE),
1764 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001765 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001766 mBytesRemaining(0),
1767 mCurrentWriteLength(0),
1768 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001769 mWriteAckSequence(0),
1770 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001771 mScreenState(AudioFlinger::mScreenState),
1772 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001773 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001774 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1775 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001776{
Glenn Kastend7dca052015-03-05 16:05:54 -08001777 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1778 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001779
1780 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1781 // it would be safer to explicitly pass initial masterVolume/masterMute as
1782 // parameter.
1783 //
1784 // If the HAL we are using has support for master volume or master mute,
1785 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1786 // and the mute set to false).
1787 mMasterVolume = audioFlinger->masterVolume_l();
1788 mMasterMute = audioFlinger->masterMute_l();
1789 if (mOutput && mOutput->audioHwDev) {
1790 if (mOutput->audioHwDev->canSetMasterVolume()) {
1791 mMasterVolume = 1.0;
1792 }
1793
1794 if (mOutput->audioHwDev->canSetMasterMute()) {
1795 mMasterMute = false;
1796 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001797 mIsMsdDevice = strcmp(
1798 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001799 }
1800
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001801 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001802
Andy Hungc8fddf32018-08-08 18:32:37 -07001803 // TODO: We may also match on address as well as device type for
1804 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
1805 if (type == MIXER || type == DIRECT) {
1806 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
1807 "audio.timestamp.corrected_output_devices",
1808 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1809 : AUDIO_DEVICE_NONE));
1810 }
1811
Eric Laurent223fd5c2014-11-11 13:43:36 -08001812 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001813 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001814 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001815 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001816 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1817 }
Eric Laurent98e38192018-02-15 18:31:53 -08001818 // Audio patch volume is always max
1819 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1820 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001821}
1822
1823AudioFlinger::PlaybackThread::~PlaybackThread()
1824{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001825 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001826 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001827 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001828 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001829}
1830
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001831// Thread virtuals
1832
1833void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001834{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001835 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001836}
1837
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001838// ThreadBase virtuals
1839void AudioFlinger::PlaybackThread::preExit()
1840{
1841 ALOGV(" preExit()");
1842 // FIXME this is using hard-coded strings but in the future, this functionality will be
1843 // converted to use audio HAL extensions required to support tunneling
1844 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1845 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1846}
1847
1848void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001849{
Eric Laurent81784c32012-11-19 14:55:58 -08001850 String8 result;
1851
Marco Nelissenb2208842014-02-07 14:00:50 -08001852 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001853 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1854 const stream_type_t *st = &mStreamTypes[i];
1855 if (i > 0) {
1856 result.appendFormat(", ");
1857 }
1858 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1859 if (st->mute) {
1860 result.append("M");
1861 }
1862 }
1863 result.append("\n");
1864 write(fd, result.string(), result.length());
1865 result.clear();
1866
Eric Laurent81784c32012-11-19 14:55:58 -08001867 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1868 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001869 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001870 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001871
1872 size_t numtracks = mTracks.size();
1873 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001874 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001875 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001876 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001877 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001878 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001879 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001880 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001881 for (size_t i = 0; i < numtracks; ++i) {
1882 sp<Track> track = mTracks[i];
1883 if (track != 0) {
1884 bool active = mActiveTracks.indexOf(track) >= 0;
1885 if (active) {
1886 numactiveseen++;
1887 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001888 result.append(prefix);
1889 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001890 }
1891 }
1892 } else {
1893 result.append("\n");
1894 }
1895 if (numactiveseen != numactive) {
1896 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001897 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001898 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001899 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001900 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001901 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001902 sp<Track> track = mActiveTracks[i];
1903 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001904 result.append(prefix);
1905 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001906 }
1907 }
1908 }
1909
1910 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001911}
1912
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001913void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001914{
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07001915 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08001916 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
1917 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
1918 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
1919 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001920 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001921 dprintf(fd, " Total writes: %d\n", mNumWrites);
1922 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1923 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1924 dprintf(fd, " Suspend count: %d\n", mSuspended);
1925 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1926 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1927 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1928 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001929 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001930 AudioStreamOut *output = mOutput;
1931 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001932 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08001933 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001934 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1935 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1936 if (mPipeSink.get() != nullptr) {
1937 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1938 }
1939 if (output != nullptr) {
1940 dprintf(fd, " Hal stream dump:\n");
1941 (void)output->stream->dump(fd);
1942 }
Eric Laurent81784c32012-11-19 14:55:58 -08001943}
1944
Eric Laurent81784c32012-11-19 14:55:58 -08001945// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1946sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1947 const sp<AudioFlinger::Client>& client,
1948 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001949 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001950 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001951 audio_format_t format,
1952 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001953 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001954 size_t *pNotificationFrameCount,
1955 uint32_t notificationsPerBuffer,
1956 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001957 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001958 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001959 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001960 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001961 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001962 status_t *status,
1963 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001964{
Glenn Kasten74935e42013-12-19 08:56:45 -08001965 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001966 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001967 sp<Track> track;
1968 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001969 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001970 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001971 uint32_t sampleRate;
1972
1973 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1974 lStatus = BAD_VALUE;
1975 goto Exit;
1976 }
Eric Laurent21da6472017-11-09 16:29:26 -08001977
1978 if (*pSampleRate == 0) {
1979 *pSampleRate = mSampleRate;
1980 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001981 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001982
1983 // special case for FAST flag considered OK if fast mixer is present
1984 if (hasFastMixer()) {
1985 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1986 }
1987
1988 // Check if requested flags are compatible with output stream flags
1989 if ((*flags & outputFlags) != *flags) {
1990 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1991 *flags, outputFlags);
1992 *flags = (audio_output_flags_t)(*flags & outputFlags);
1993 }
Eric Laurent81784c32012-11-19 14:55:58 -08001994
Eric Laurent81784c32012-11-19 14:55:58 -08001995 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001996 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001997 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001998 // PCM data
1999 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002000 // TODO: extract as a data library function that checks that a computationally
2001 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002002 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002003 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2004 (channelMask == AUDIO_CHANNEL_OUT_MONO
2005 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002006 // hardware sample rate
2007 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002008 // normal mixer has an associated fast mixer
2009 hasFastMixer() &&
2010 // there are sufficient fast track slots available
2011 (mFastTrackAvailMask != 0)
2012 // FIXME test that MixerThread for this fast track has a capable output HAL
2013 // FIXME add a permission test also?
2014 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002015 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2016 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002017 // read the fast track multiplier property the first time it is needed
2018 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2019 if (ok != 0) {
2020 ALOGE("%s pthread_once failed: %d", __func__, ok);
2021 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002022 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002023 }
Eric Laurent4c415062016-06-17 16:14:16 -07002024
2025 // check compatibility with audio effects.
2026 { // scope for mLock
2027 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002028 for (audio_session_t session : {
2029 AUDIO_SESSION_OUTPUT_STAGE,
2030 AUDIO_SESSION_OUTPUT_MIX,
2031 sessionId,
2032 }) {
2033 sp<EffectChain> chain = getEffectChain_l(session);
2034 if (chain.get() != nullptr) {
2035 audio_output_flags_t old = *flags;
2036 chain->checkOutputFlagCompatibility(flags);
2037 if (old != *flags) {
2038 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2039 (int)session, (int)old, (int)*flags);
2040 }
Eric Laurent4c415062016-06-17 16:14:16 -07002041 }
2042 }
2043 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002044 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002045 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2046 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002047 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002048 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2049 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002050 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002051 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002052 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002053 audio_is_linear_pcm(format),
2054 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002055 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002056 }
2057 }
Eric Laurent21da6472017-11-09 16:29:26 -08002058
2059 if (!audio_has_proportional_frames(format)) {
2060 if (sharedBuffer != 0) {
2061 // Same comment as below about ignoring frameCount parameter for set()
2062 frameCount = sharedBuffer->size();
2063 } else if (frameCount == 0) {
2064 frameCount = mNormalFrameCount;
2065 }
2066 if (notificationFrameCount != frameCount) {
2067 notificationFrameCount = frameCount;
2068 }
2069 } else if (sharedBuffer != 0) {
2070 // FIXME: Ensure client side memory buffers need
2071 // not have additional alignment beyond sample
2072 // (e.g. 16 bit stereo accessed as 32 bit frame).
2073 size_t alignment = audio_bytes_per_sample(format);
2074 if (alignment & 1) {
2075 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2076 alignment = 1;
2077 }
2078 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2079 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2080 if (channelCount > 1) {
2081 // More than 2 channels does not require stronger alignment than stereo
2082 alignment <<= 1;
2083 }
2084 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2085 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2086 sharedBuffer->pointer(), channelCount);
2087 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002088 goto Exit;
2089 }
Eric Laurent21da6472017-11-09 16:29:26 -08002090
2091 // When initializing a shared buffer AudioTrack via constructors,
2092 // there's no frameCount parameter.
2093 // But when initializing a shared buffer AudioTrack via set(),
2094 // there _is_ a frameCount parameter. We silently ignore it.
2095 frameCount = sharedBuffer->size() / frameSize;
2096 } else {
2097 size_t minFrameCount = 0;
2098 // For fast tracks we try to respect the application's request for notifications per buffer.
2099 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2100 if (notificationsPerBuffer > 0) {
2101 // Avoid possible arithmetic overflow during multiplication.
2102 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2103 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2104 notificationsPerBuffer, mFrameCount);
2105 } else {
2106 minFrameCount = mFrameCount * notificationsPerBuffer;
2107 }
2108 }
2109 } else {
2110 // For normal PCM streaming tracks, update minimum frame count.
2111 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2112 // cover audio hardware latency.
2113 // This is probably too conservative, but legacy application code may depend on it.
2114 // If you change this calculation, also review the start threshold which is related.
2115 uint32_t latencyMs = latency_l();
2116 if (latencyMs == 0) {
2117 ALOGE("Error when retrieving output stream latency");
2118 lStatus = UNKNOWN_ERROR;
2119 goto Exit;
2120 }
2121
2122 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2123 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2124
Eric Laurent81784c32012-11-19 14:55:58 -08002125 }
Eric Laurent21da6472017-11-09 16:29:26 -08002126 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002127 frameCount = minFrameCount;
2128 }
Eric Laurent81784c32012-11-19 14:55:58 -08002129 }
Eric Laurent21da6472017-11-09 16:29:26 -08002130
2131 // Make sure that application is notified with sufficient margin before underrun.
2132 // The client can divide the AudioTrack buffer into sub-buffers,
2133 // and expresses its desire to server as the notification frame count.
2134 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2135 size_t maxNotificationFrames;
2136 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2137 // notify every HAL buffer, regardless of the size of the track buffer
2138 maxNotificationFrames = mFrameCount;
2139 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002140 // Triple buffer the notification period for a triple buffered mixer period;
2141 // otherwise, double buffering for the notification period is fine.
2142 //
2143 // TODO: This should be moved to AudioTrack to modify the notification period
2144 // on AudioTrack::setBufferSizeInFrames() changes.
2145 const int nBuffering =
2146 (uint64_t{frameCount} * mSampleRate)
2147 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2148
Eric Laurent21da6472017-11-09 16:29:26 -08002149 maxNotificationFrames = frameCount / nBuffering;
2150 // If client requested a fast track but this was denied, then use the smaller maximum.
2151 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2152 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2153 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2154 maxNotificationFrames = maxNotificationFramesFastDenied;
2155 }
2156 }
2157 }
2158 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2159 if (notificationFrameCount == 0) {
2160 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2161 maxNotificationFrames, frameCount);
2162 } else {
2163 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2164 notificationFrameCount, maxNotificationFrames, frameCount);
2165 }
2166 notificationFrameCount = maxNotificationFrames;
2167 }
2168 }
2169
Glenn Kasten74935e42013-12-19 08:56:45 -08002170 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002171 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002172
Glenn Kastenc3df8382014-03-13 15:05:25 -07002173 switch (mType) {
2174
2175 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002176 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002177 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002178 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2179 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002180 sampleRate, format, channelMask, mOutput, mFormat);
2181 lStatus = BAD_VALUE;
2182 goto Exit;
2183 }
2184 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002185 break;
2186
2187 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002188 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002189 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2190 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002191 sampleRate, format, channelMask, mOutput, mFormat);
2192 lStatus = BAD_VALUE;
2193 goto Exit;
2194 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002195 break;
2196
2197 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002198 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002199 ALOGE("createTrack_l() Bad parameter: format %#x \""
2200 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002201 format, mOutput, mFormat);
2202 lStatus = BAD_VALUE;
2203 goto Exit;
2204 }
Andy Hungcd044842014-08-07 11:04:34 -07002205 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002206 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2207 lStatus = BAD_VALUE;
2208 goto Exit;
2209 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002210 break;
2211
Eric Laurent81784c32012-11-19 14:55:58 -08002212 }
2213
2214 lStatus = initCheck();
2215 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002216 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002217 goto Exit;
2218 }
2219
2220 { // scope for mLock
2221 Mutex::Autolock _l(mLock);
2222
2223 // all tracks in same audio session must share the same routing strategy otherwise
2224 // conflicts will happen when tracks are moved from one output to another by audio policy
2225 // manager
2226 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2227 for (size_t i = 0; i < mTracks.size(); ++i) {
2228 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002229 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002230 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2231 if (sessionId == t->sessionId() && strategy != actual) {
2232 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2233 strategy, actual);
2234 lStatus = BAD_VALUE;
2235 goto Exit;
2236 }
2237 }
2238 }
2239
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002240 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002241 channelMask, frameCount,
2242 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002243 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002244
Glenn Kasten03003332013-08-06 15:40:54 -07002245 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2246 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002247 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002248 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002249 goto Exit;
2250 }
2251 mTracks.add(track);
2252
2253 sp<EffectChain> chain = getEffectChain_l(sessionId);
2254 if (chain != 0) {
2255 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2256 track->setMainBuffer(chain->inBuffer());
2257 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2258 chain->incTrackCnt();
2259 }
2260
Eric Laurent05067782016-06-01 18:27:28 -07002261 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002262 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2263 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2264 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002265 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002266 }
2267 }
2268
2269 lStatus = NO_ERROR;
2270
2271Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002272 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002273 return track;
2274}
2275
Andy Hung1bc088a2018-02-09 15:57:31 -08002276template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002277ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2278{
Andy Hungc0691382018-09-12 18:01:57 -07002279 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002280 const ssize_t index = mTracks.remove(track);
2281 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002282 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002283 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002284 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002285 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002286 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002287 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002288 }
2289 return index;
2290}
2291
Eric Laurent81784c32012-11-19 14:55:58 -08002292uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2293{
2294 return latency;
2295}
2296
2297uint32_t AudioFlinger::PlaybackThread::latency() const
2298{
2299 Mutex::Autolock _l(mLock);
2300 return latency_l();
2301}
2302uint32_t AudioFlinger::PlaybackThread::latency_l() const
2303{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002304 uint32_t latency;
2305 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2306 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002307 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002308 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002309}
2310
2311void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2312{
2313 Mutex::Autolock _l(mLock);
2314 // Don't apply master volume in SW if our HAL can do it for us.
2315 if (mOutput && mOutput->audioHwDev &&
2316 mOutput->audioHwDev->canSetMasterVolume()) {
2317 mMasterVolume = 1.0;
2318 } else {
2319 mMasterVolume = value;
2320 }
2321}
2322
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002323void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2324{
2325 mMasterBalance.store(balance);
2326}
2327
Eric Laurent81784c32012-11-19 14:55:58 -08002328void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2329{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002330 if (isDuplicating()) {
2331 return;
2332 }
Eric Laurent81784c32012-11-19 14:55:58 -08002333 Mutex::Autolock _l(mLock);
2334 // Don't apply master mute in SW if our HAL can do it for us.
2335 if (mOutput && mOutput->audioHwDev &&
2336 mOutput->audioHwDev->canSetMasterMute()) {
2337 mMasterMute = false;
2338 } else {
2339 mMasterMute = muted;
2340 }
2341}
2342
2343void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2344{
2345 Mutex::Autolock _l(mLock);
2346 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002347 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002348}
2349
2350void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2351{
2352 Mutex::Autolock _l(mLock);
2353 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002354 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002355}
2356
2357float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2358{
2359 Mutex::Autolock _l(mLock);
2360 return mStreamTypes[stream].volume;
2361}
2362
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002363void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2364{
2365 mOutput->stream->setVolume(left, right);
2366}
2367
Eric Laurent81784c32012-11-19 14:55:58 -08002368// addTrack_l() must be called with ThreadBase::mLock held
2369status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2370{
2371 status_t status = ALREADY_EXISTS;
2372
Eric Laurent81784c32012-11-19 14:55:58 -08002373 if (mActiveTracks.indexOf(track) < 0) {
2374 // the track is newly added, make sure it fills up all its
2375 // buffers before playing. This is to ensure the client will
2376 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002377 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002378 TrackBase::track_state state = track->mState;
2379 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002380 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002381 mLock.lock();
2382 // abort track was stopped/paused while we released the lock
2383 if (state != track->mState) {
2384 if (status == NO_ERROR) {
2385 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002386 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002387 mLock.lock();
2388 }
2389 return INVALID_OPERATION;
2390 }
2391 // abort if start is rejected by audio policy manager
2392 if (status != NO_ERROR) {
2393 return PERMISSION_DENIED;
2394 }
2395#ifdef ADD_BATTERY_DATA
2396 // to track the speaker usage
2397 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2398#endif
2399 }
2400
Eric Laurent51716182016-02-29 18:00:56 -08002401 // set retry count for buffer fill
2402 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002403 if (track->isStopping_1()) {
2404 track->mRetryCount = kMaxTrackStopRetriesOffload;
2405 } else {
2406 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2407 }
2408 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002409 } else {
2410 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002411 track->mFillingUpStatus =
2412 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002413 }
2414
jiabin245cdd92018-12-07 17:55:15 -08002415 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2416 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002417 // Unlock due to VibratorService will lock for this call and will
2418 // call Tracks.mute/unmute which also require thread's lock.
2419 mLock.unlock();
2420 const int intensity = AudioFlinger::onExternalVibrationStart(
2421 track->getExternalVibration());
2422 mLock.lock();
jiabinbf6b0ec2019-02-12 12:30:12 -08002423 track->setHapticIntensity(static_cast<AudioMixer::haptic_intensity_t>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002424 // Haptic playback should be enabled by vibrator service.
2425 if (track->getHapticPlaybackEnabled()) {
2426 // Disable haptic playback of all active track to ensure only
2427 // one track playing haptic if current track should play haptic.
2428 for (const auto &t : mActiveTracks) {
2429 t->setHapticPlaybackEnabled(false);
2430 }
jiabin245cdd92018-12-07 17:55:15 -08002431 }
jiabin245cdd92018-12-07 17:55:15 -08002432 }
2433
Eric Laurent81784c32012-11-19 14:55:58 -08002434 track->mResetDone = false;
2435 track->mPresentationCompleteFrames = 0;
2436 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002437 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2438 if (chain != 0) {
2439 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2440 track->sessionId());
2441 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002442 }
2443
2444 status = NO_ERROR;
2445 }
2446
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002447 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002448 return status;
2449}
2450
Eric Laurentbfb1b832013-01-07 09:53:42 -08002451bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002452{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002453 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002454 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002455 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2456 track->mState = TrackBase::STOPPED;
2457 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002458 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002459 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002460 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002461 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002462
2463 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002464}
2465
2466void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2467{
2468 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002469
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002470 String8 result;
2471 track->appendDump(result, false /* active */);
2472 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002473
Eric Laurent81784c32012-11-19 14:55:58 -08002474 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002475 if (track->isFastTrack()) {
2476 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002477 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002478 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2479 mFastTrackAvailMask |= 1 << index;
2480 // redundant as track is about to be destroyed, for dumpsys only
2481 track->mFastIndex = -1;
2482 }
2483 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2484 if (chain != 0) {
2485 chain->decTrackCnt();
2486 }
2487}
2488
2489String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2490{
Eric Laurent81784c32012-11-19 14:55:58 -08002491 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002492 String8 out_s8;
2493 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2494 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002495 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002496 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002497}
2498
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002499status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2500 Mutex::Autolock _l(mLock);
2501 if (mOutput == nullptr || mOutput->stream == nullptr) {
2502 return NO_INIT;
2503 }
2504 return mOutput->stream->selectPresentation(presentationId, programId);
2505}
2506
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002507void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002508 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2509 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002510
Eric Laurent73e26b62015-04-27 16:55:58 -07002511 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002512
2513 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002514 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002515 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002516 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002517 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002518 desc->mChannelMask = mChannelMask;
2519 desc->mSamplingRate = mSampleRate;
2520 desc->mFormat = mFormat;
2521 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002522 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002523 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002524 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002525 break;
2526
Eric Laurent73e26b62015-04-27 16:55:58 -07002527 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002528 default:
2529 break;
2530 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002531 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002532}
2533
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002534void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002535{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002536 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002537}
2538
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002539void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002540{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002541 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002542}
2543
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002544void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002545{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002546 mCallbackThread->setAsyncError();
2547}
2548
Eric Laurent3b4529e2013-09-05 18:09:19 -07002549void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002550{
2551 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002552 // reject out of sequence requests
2553 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2554 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002555 mWaitWorkCV.signal();
2556 }
2557}
2558
Eric Laurent3b4529e2013-09-05 18:09:19 -07002559void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560{
2561 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002562 // reject out of sequence requests
2563 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002564 // Register discontinuity when HW drain is completed because that can cause
2565 // the timestamp frame position to reset to 0 for direct and offload threads.
2566 // (Out of sequence requests are ignored, since the discontinuity would be handled
2567 // elsewhere, e.g. in flush).
2568 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002569 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002570 mWaitWorkCV.signal();
2571 }
2572}
2573
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002574void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002575{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002576 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002577 mSampleRate = mOutput->getSampleRate();
2578 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002579 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002580 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002581 }
Andy Hung9a592762014-07-21 21:56:01 -07002582 if ((mType == MIXER || mType == DUPLICATING)
2583 && !isValidPcmSinkChannelMask(mChannelMask)) {
2584 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2585 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002586 }
Andy Hunge5412692014-05-16 11:25:07 -07002587 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002588 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002589
2590 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002591 status_t result = mOutput->stream->getFormat(&mHALFormat);
2592 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002593 // Get format from the shim, which will be different than the HAL format
2594 // if playing compressed audio over HDMI passthrough.
2595 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002596 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002597 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002598 }
Andy Hung6146c082014-03-18 11:56:15 -07002599 if ((mType == MIXER || mType == DUPLICATING)
2600 && !isValidPcmSinkFormat(mFormat)) {
2601 LOG_FATAL("HAL format %#x not supported for mixed output",
2602 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002603 }
Phil Burk062e67a2015-02-11 13:40:50 -08002604 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002605 result = mOutput->stream->getBufferSize(&mBufferSize);
2606 LOG_ALWAYS_FATAL_IF(result != OK,
2607 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002608 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002609 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002610 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002611 mFrameCount);
2612 }
2613
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002614 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2615 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002616 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002617 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002618 }
2619 }
2620
Eric Laurentd1f69b02014-12-15 14:33:13 -08002621 mHwSupportsPause = false;
2622 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002623 bool supportsPause = false, supportsResume = false;
2624 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2625 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002626 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002627 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002628 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002629 } else if (supportsResume) {
2630 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002631 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002632 }
2633 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002634 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2635 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2636 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002637
Andy Hungfbfc3952015-01-15 13:33:51 -08002638 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2639 // For best precision, we use float instead of the associated output
2640 // device format (typically PCM 16 bit).
2641
2642 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2643 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2644 mBufferSize = mFrameSize * mFrameCount;
2645
2646 // TODO: We currently use the associated output device channel mask and sample rate.
2647 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2648 // (if a valid mask) to avoid premature downmix.
2649 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2650 // instead of the output device sample rate to avoid loss of high frequency information.
2651 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2652 }
2653
Andy Hung09a50072014-02-27 14:30:47 -08002654 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002655 double multiplier = 1.0;
2656 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2657 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002658 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2659 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002660
Eric Laurent81784c32012-11-19 14:55:58 -08002661 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2662 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2663 maxNormalFrameCount = maxNormalFrameCount & ~15;
2664 if (maxNormalFrameCount < minNormalFrameCount) {
2665 maxNormalFrameCount = minNormalFrameCount;
2666 }
2667 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2668 if (multiplier <= 1.0) {
2669 multiplier = 1.0;
2670 } else if (multiplier <= 2.0) {
2671 if (2 * mFrameCount <= maxNormalFrameCount) {
2672 multiplier = 2.0;
2673 } else {
2674 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2675 }
2676 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002677 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002678 }
2679 }
2680 mNormalFrameCount = multiplier * mFrameCount;
2681 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002682 if (mType == MIXER || mType == DUPLICATING) {
2683 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2684 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002685 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002686 mNormalFrameCount);
2687
Andy Hung08fb1742015-05-31 23:22:10 -07002688 // Check if we want to throttle the processing to no more than 2x normal rate
2689 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002690 mThreadThrottleTimeMs = 0;
2691 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002692 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2693
Andy Hung010a1a12014-03-13 13:57:33 -07002694 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2695 // Originally this was int16_t[] array, need to remove legacy implications.
2696 free(mSinkBuffer);
2697 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002698 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2699 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2700 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002701 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002702
Andy Hung69aed5f2014-02-25 17:24:40 -08002703 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2704 // drives the output.
2705 free(mMixerBuffer);
2706 mMixerBuffer = NULL;
2707 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002708 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002709 mMixerBufferSize = mNormalFrameCount * mChannelCount
2710 * audio_bytes_per_sample(mMixerBufferFormat);
2711 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2712 }
Andy Hung98ef9782014-03-04 14:46:50 -08002713 free(mEffectBuffer);
2714 mEffectBuffer = NULL;
2715 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002716 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002717 mEffectBufferSize = mNormalFrameCount * mChannelCount
2718 * audio_bytes_per_sample(mEffectBufferFormat);
2719 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2720 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002721
jiabin245cdd92018-12-07 17:55:15 -08002722 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2723 mChannelMask &= ~mHapticChannelMask;
2724 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2725 mChannelCount -= mHapticChannelCount;
2726
Eric Laurent81784c32012-11-19 14:55:58 -08002727 // force reconfiguration of effect chains and engines to take new buffer size and audio
2728 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002729 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002730 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2731 // matter.
2732 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2733 Vector< sp<EffectChain> > effectChains = mEffectChains;
2734 for (size_t i = 0; i < effectChains.size(); i ++) {
2735 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2736 }
2737}
2738
Kevin Rocard069c2712018-03-29 19:09:14 -07002739void AudioFlinger::PlaybackThread::updateMetadata_l()
2740{
Kevin Rocard12381092018-04-11 09:19:59 -07002741 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2742 return; // That should not happen
2743 }
2744 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2745 for (const sp<Track> &track : mActiveTracks) {
2746 // Do not short-circuit as all hasChanged states must be reset
2747 // as all the metadata are going to be sent
2748 hasChanged |= track->readAndClearHasChanged();
2749 }
2750 if (!hasChanged) {
2751 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002752 }
2753 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002754 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002755 for (const sp<Track> &track : mActiveTracks) {
2756 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002757 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002758 }
Kevin Rocard12381092018-04-11 09:19:59 -07002759 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002760}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002761
Kevin Rocard12381092018-04-11 09:19:59 -07002762void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2763 const StreamOutHalInterface::SourceMetadata& metadata)
2764{
2765 mOutput->stream->updateSourceMetadata(metadata);
2766};
2767
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002768status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002769{
2770 if (halFrames == NULL || dspFrames == NULL) {
2771 return BAD_VALUE;
2772 }
2773 Mutex::Autolock _l(mLock);
2774 if (initCheck() != NO_ERROR) {
2775 return INVALID_OPERATION;
2776 }
Andy Hung818e7a32016-02-16 18:08:07 -08002777 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002778 *halFrames = framesWritten;
2779
2780 if (isSuspended()) {
2781 // return an estimation of rendered frames when the output is suspended
2782 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002783 *dspFrames = (uint32_t)
2784 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002785 return NO_ERROR;
2786 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002787 status_t status;
2788 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002789 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002790 *dspFrames = (size_t)frames;
2791 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002792 }
2793}
2794
Glenn Kastend848eb42016-03-08 13:42:11 -08002795uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002796{
2797 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2798 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2799 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2800 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2801 }
2802 for (size_t i = 0; i < mTracks.size(); i++) {
2803 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002804 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002805 return AudioSystem::getStrategyForStream(track->streamType());
2806 }
2807 }
2808 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2809}
2810
2811
Phil Burk062e67a2015-02-11 13:40:50 -08002812AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002813{
2814 Mutex::Autolock _l(mLock);
2815 return mOutput;
2816}
2817
Phil Burk062e67a2015-02-11 13:40:50 -08002818AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002819{
2820 Mutex::Autolock _l(mLock);
2821 AudioStreamOut *output = mOutput;
2822 mOutput = NULL;
2823 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2824 // must push a NULL and wait for ack
2825 mOutputSink.clear();
2826 mPipeSink.clear();
2827 mNormalSink.clear();
2828 return output;
2829}
2830
2831// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002832sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002833{
2834 if (mOutput == NULL) {
2835 return NULL;
2836 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002837 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002838}
2839
2840uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2841{
2842 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2843}
2844
2845status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2846{
2847 if (!isValidSyncEvent(event)) {
2848 return BAD_VALUE;
2849 }
2850
2851 Mutex::Autolock _l(mLock);
2852
2853 for (size_t i = 0; i < mTracks.size(); ++i) {
2854 sp<Track> track = mTracks[i];
2855 if (event->triggerSession() == track->sessionId()) {
2856 (void) track->setSyncEvent(event);
2857 return NO_ERROR;
2858 }
2859 }
2860
2861 return NAME_NOT_FOUND;
2862}
2863
2864bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2865{
2866 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2867}
2868
2869void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2870 const Vector< sp<Track> >& tracksToRemove)
2871{
Andy Hungfe726a62018-09-27 15:17:25 -07002872 // Miscellaneous track cleanup when removed from the active list,
2873 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002875 for (const auto& track : tracksToRemove) {
2876 if (track->isExternalTrack()) {
2877 // to track the speaker usage
2878 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002879 }
2880 }
Andy Hungfe726a62018-09-27 15:17:25 -07002881#else
2882 (void)tracksToRemove; // suppress unused warning
2883#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002884}
2885
2886void AudioFlinger::PlaybackThread::checkSilentMode_l()
2887{
2888 if (!mMasterMute) {
2889 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002890 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2891 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2892 return;
2893 }
Eric Laurent81784c32012-11-19 14:55:58 -08002894 if (property_get("ro.audio.silent", value, "0") > 0) {
2895 char *endptr;
2896 unsigned long ul = strtoul(value, &endptr, 0);
2897 if (*endptr == '\0' && ul != 0) {
2898 ALOGD("Silence is golden");
2899 // The setprop command will not allow a property to be changed after
2900 // the first time it is set, so we don't have to worry about un-muting.
2901 setMasterMute_l(true);
2902 }
2903 }
2904 }
2905}
2906
2907// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002909{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002910 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002911 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002912 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002913 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002914
2915 // If an NBAIO sink is present, use it to write the normal mixer's submix
2916 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002917
Andy Hung010a1a12014-03-13 13:57:33 -07002918 const size_t count = mBytesRemaining / mFrameSize;
2919
Simon Wilson2d590962012-11-29 15:18:50 -08002920 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002921 // update the setpoint when AudioFlinger::mScreenState changes
2922 uint32_t screenState = AudioFlinger::mScreenState;
2923 if (screenState != mScreenState) {
2924 mScreenState = screenState;
2925 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2926 if (pipe != NULL) {
2927 pipe->setAvgFrames((mScreenState & 1) ?
2928 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2929 }
2930 }
Andy Hung010a1a12014-03-13 13:57:33 -07002931 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002932 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002933 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002934 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002935#ifdef TEE_SINK
2936 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2937#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002938 } else {
2939 bytesWritten = framesWritten;
2940 }
2941 // otherwise use the HAL / AudioStreamOut directly
2942 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002943 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002944
Eric Laurentbfb1b832013-01-07 09:53:42 -08002945 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002946 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2947 mWriteAckSequence += 2;
2948 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002949 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002950 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002951 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002952 // FIXME We should have an implementation of timestamps for direct output threads.
2953 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002954 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002955
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956 if (mUseAsyncWrite &&
2957 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2958 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002959 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002961 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002962 }
Eric Laurent81784c32012-11-19 14:55:58 -08002963 }
2964
Eric Laurent81784c32012-11-19 14:55:58 -08002965 mNumWrites++;
2966 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002967 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002968 return bytesWritten;
2969}
2970
2971void AudioFlinger::PlaybackThread::threadLoop_drain()
2972{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002973 bool supportsDrain = false;
2974 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002975 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2976 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002977 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2978 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002979 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002980 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002981 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002982 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002983 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002984 }
2985}
2986
2987void AudioFlinger::PlaybackThread::threadLoop_exit()
2988{
Eric Laurent275e8e92014-11-30 15:14:47 -08002989 {
2990 Mutex::Autolock _l(mLock);
2991 for (size_t i = 0; i < mTracks.size(); i++) {
2992 sp<Track> track = mTracks[i];
2993 track->invalidate();
2994 }
Andy Hungdae27702016-10-31 14:01:16 -07002995 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2996 // After we exit there are no more track changes sent to BatteryNotifier
2997 // because that requires an active threadLoop.
2998 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2999 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003000 }
Eric Laurent81784c32012-11-19 14:55:58 -08003001}
3002
3003/*
3004The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003005 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003006 - mActiveSleepTimeUs from activeSleepTimeUs()
3007 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003008 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3009 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003010 - maxPeriod from frame count and sample rate (MIXER only)
3011
3012The parameters that affect these derived values are:
3013 - frame count
3014 - frame size
3015 - sample rate
3016 - device type: A2DP or not
3017 - device latency
3018 - format: PCM or not
3019 - active sleep time
3020 - idle sleep time
3021*/
3022
3023void AudioFlinger::PlaybackThread::cacheParameters_l()
3024{
Andy Hung25c2dac2014-02-27 14:56:00 -08003025 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003026 mActiveSleepTimeUs = activeSleepTimeUs();
3027 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003028
3029 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3030 // truncating audio when going to standby.
3031 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
3032 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
3033 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3034 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3035 }
3036 }
Eric Laurent81784c32012-11-19 14:55:58 -08003037}
3038
Eric Laurent13084622016-05-17 10:51:49 -07003039bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003040{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003041 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003042 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003043 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003044 size_t size = mTracks.size();
3045 for (size_t i = 0; i < size; i++) {
3046 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003047 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003048 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003049 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003050 }
3051 }
Eric Laurent13084622016-05-17 10:51:49 -07003052 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003053}
3054
Haynes Mathew George05317d22016-05-03 16:34:26 -07003055void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3056{
3057 Mutex::Autolock _l(mLock);
3058 invalidateTracks_l(streamType);
3059}
3060
Eric Laurent81784c32012-11-19 14:55:58 -08003061status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3062{
Glenn Kastend848eb42016-03-08 13:42:11 -08003063 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003064 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003065 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003066 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3067 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3068 &halInBuffer);
3069 if (result != OK) return result;
3070 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003071 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003072 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003073 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003074 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003075 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003076 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003077 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003078 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003079 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003080 &halInBuffer);
3081 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003082#ifdef FLOAT_EFFECT_CHAIN
3083 buffer = halInBuffer->audioBuffer()->f32;
3084#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003085 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003086#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003087 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3088 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003089 }
3090
3091 // Attach all tracks with same session ID to this chain.
3092 for (size_t i = 0; i < mTracks.size(); ++i) {
3093 sp<Track> track = mTracks[i];
3094 if (session == track->sessionId()) {
3095 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3096 buffer);
3097 track->setMainBuffer(buffer);
3098 chain->incTrackCnt();
3099 }
3100 }
3101
3102 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003103 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003104 if (session == track->sessionId()) {
3105 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3106 chain->incActiveTrackCnt();
3107 }
3108 }
3109 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003110 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003111 chain->setInBuffer(halInBuffer);
3112 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003113 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003114 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003115 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3116 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003117 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003118 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003119 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003120 // Effect chain for other sessions are inserted at beginning of effect
3121 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003122 // sessions is not important.
3123 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3124 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3125 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003126 size_t size = mEffectChains.size();
3127 size_t i = 0;
3128 for (i = 0; i < size; i++) {
3129 if (mEffectChains[i]->sessionId() < session) {
3130 break;
3131 }
3132 }
3133 mEffectChains.insertAt(chain, i);
3134 checkSuspendOnAddEffectChain_l(chain);
3135
3136 return NO_ERROR;
3137}
3138
3139size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3140{
Glenn Kastend848eb42016-03-08 13:42:11 -08003141 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003142
3143 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3144
3145 for (size_t i = 0; i < mEffectChains.size(); i++) {
3146 if (chain == mEffectChains[i]) {
3147 mEffectChains.removeAt(i);
3148 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003149 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003150 if (session == track->sessionId()) {
3151 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3152 chain.get(), session);
3153 chain->decActiveTrackCnt();
3154 }
3155 }
3156
3157 // detach all tracks with same session ID from this chain
3158 for (size_t i = 0; i < mTracks.size(); ++i) {
3159 sp<Track> track = mTracks[i];
3160 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003161 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003162 chain->decTrackCnt();
3163 }
3164 }
3165 break;
3166 }
3167 }
3168 return mEffectChains.size();
3169}
3170
3171status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003172 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003173{
3174 Mutex::Autolock _l(mLock);
3175 return attachAuxEffect_l(track, EffectId);
3176}
3177
3178status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003179 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003180{
3181 status_t status = NO_ERROR;
3182
3183 if (EffectId == 0) {
3184 track->setAuxBuffer(0, NULL);
3185 } else {
3186 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3187 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3188 if (effect != 0) {
3189 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3190 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3191 } else {
3192 status = INVALID_OPERATION;
3193 }
3194 } else {
3195 status = BAD_VALUE;
3196 }
3197 }
3198 return status;
3199}
3200
3201void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3202{
3203 for (size_t i = 0; i < mTracks.size(); ++i) {
3204 sp<Track> track = mTracks[i];
3205 if (track->auxEffectId() == effectId) {
3206 attachAuxEffect_l(track, 0);
3207 }
3208 }
3209}
3210
3211bool AudioFlinger::PlaybackThread::threadLoop()
3212{
Glenn Kasten388d5712017-04-07 14:38:41 -07003213 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003214
Eric Laurent81784c32012-11-19 14:55:58 -08003215 Vector< sp<Track> > tracksToRemove;
3216
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003217 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003218 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
3219 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003220
3221 // MIXER
3222 nsecs_t lastWarning = 0;
3223
3224 // DUPLICATING
3225 // FIXME could this be made local to while loop?
3226 writeFrames = 0;
3227
3228 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003229 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003230
3231 if (mType == MIXER) {
3232 sleepTimeShift = 0;
3233 }
3234
3235 CpuStats cpuStats;
3236 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3237
3238 acquireWakeLock();
3239
Glenn Kasteneef598c2017-04-03 14:41:13 -07003240 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3241 // thread associated with this PlaybackThread.
3242 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3243 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003244 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3245 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003246 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003247 const char *logString = NULL;
3248
rago1bb90822017-05-02 18:31:48 -07003249 // Estimated time for next buffer to be written to hal. This is used only on
3250 // suspended mode (for now) to help schedule the wait time until next iteration.
3251 nsecs_t timeLoopNextNs = 0;
3252
Eric Laurent664539d2013-09-23 18:24:31 -07003253 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003254
Andy Hungf3234512018-07-03 14:51:47 -07003255 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3256 // TODO: add confirmation checks:
3257 // 1) DIRECT threads and linear PCM format really resets to 0?
3258 // 2) Is frame count really valid if not linear pcm?
3259 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3260 if (mType == OFFLOAD || mType == DIRECT) {
3261 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3262 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003263 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003264
Andy Hung446f4df2019-02-21 12:26:41 -08003265 // loopCount is used for statistics and diagnostics.
3266 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003267 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003268 // Log merge requests are performed during AudioFlinger binder transactions, but
3269 // that does not cover audio playback. It's requested here for that reason.
3270 mAudioFlinger->requestLogMerge();
3271
Eric Laurent81784c32012-11-19 14:55:58 -08003272 cpuStats.sample(myName);
3273
3274 Vector< sp<EffectChain> > effectChains;
3275
Andy Hung2dbffc22018-08-08 18:50:41 -07003276 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3277 //
3278 // Note: we access outDevice() outside of mLock.
3279 if (isMsdDevice() && (outDevice() & AUDIO_DEVICE_OUT_BUS) != 0) {
3280 // Here, we try for the AF lock, but do not block on it as the latency
3281 // is more informational.
3282 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3283 std::vector<PatchPanel::SoftwarePatch> swPatches;
3284 double latencyMs;
3285 status_t status = INVALID_OPERATION;
3286 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3287 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3288 && swPatches.size() > 0) {
3289 status = swPatches[0].getLatencyMs_l(&latencyMs);
3290 downstreamPatchHandle = swPatches[0].getPatchHandle();
3291 }
3292 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003293 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003294 lastDownstreamPatchHandle = downstreamPatchHandle;
3295 }
3296 if (status == OK) {
3297 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003298 // latency of 5 seconds).
3299 const double minLatency = 0., maxLatency = 5000.;
3300 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003301 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003302 } else {
3303 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003304 if (latencyMs < minLatency) latencyMs = minLatency;
3305 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003306 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003307 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003308 }
3309 mAudioFlinger->mLock.unlock();
3310 }
3311 } else {
3312 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3313 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003314 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003315 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3316 }
3317 }
3318
Eric Laurent81784c32012-11-19 14:55:58 -08003319 { // scope for mLock
3320
3321 Mutex::Autolock _l(mLock);
3322
Eric Laurent021cf962014-05-13 10:18:14 -07003323 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003324
Glenn Kasteneef598c2017-04-03 14:41:13 -07003325 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003326 if (logString != NULL) {
3327 mNBLogWriter->logTimestamp();
3328 mNBLogWriter->log(logString);
3329 logString = NULL;
3330 }
3331
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003332 // Collect timestamp statistics for the Playback Thread types that support it.
3333 if (mType == MIXER
3334 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003335 || mType == DIRECT
3336 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003337 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003338 // and associate with the sink frames written out. We need
3339 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003340 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003341 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003342 if (mStandby) {
3343 mTimestampVerifier.discontinuity();
3344 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3345 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3346 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3347 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003348
3349 if (isTimestampCorrectionEnabled()) {
3350 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3351 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3352 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3353 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3354 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3355 = correctedTimestamp.mFrames;
3356 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3357 = correctedTimestamp.mTimeNs;
3358 ALOGV("TS_AFTER: %d %lld %lld", id(),
3359 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3360 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003361
3362 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003363 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003364 const int64_t newPosition =
3365 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003366 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003367 // prevent retrograde
3368 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3369 newPosition,
3370 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3371 - mSuspendedFrames));
3372 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003373 }
3374
Andy Hung818e7a32016-02-16 18:08:07 -08003375 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003376 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003377
3378 // We keep track of the last valid kernel position in case we are in underrun
3379 // and the normal mixer period is the same as the fast mixer period, or there
3380 // is some error from the HAL.
3381 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3382 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3383 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3384 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3385 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3386
3387 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3388 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3389 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3390 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003391 }
3392
3393 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3394 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003395 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003396 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003397 }
3398
Andy Hung818e7a32016-02-16 18:08:07 -08003399 // copy over kernel info
3400 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003401 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3402 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003403 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3404 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003405 } else {
3406 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003407 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003408
Andy Hungc54b1ff2016-02-23 14:07:07 -08003409 // mFramesWritten for non-offloaded tracks are contiguous
3410 // even after standby() is called. This is useful for the track frame
3411 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003412 bool serverLocationUpdate = false;
3413 if (mFramesWritten != lastFramesWritten) {
3414 serverLocationUpdate = true;
3415 lastFramesWritten = mFramesWritten;
3416 }
3417 // Only update timestamps if there is a meaningful change.
3418 // Either the kernel timestamp must be valid or we have written something.
3419 if (kernelLocationUpdate || serverLocationUpdate) {
3420 if (serverLocationUpdate) {
3421 // use the time before we called the HAL write - it is a bit more accurate
3422 // to when the server last read data than the current time here.
3423 //
Andy Hung446f4df2019-02-21 12:26:41 -08003424 // If we haven't written anything, mLastIoBeginNs will be -1
Andy Hung69488c42016-05-16 18:43:33 -07003425 // and we use systemTime().
3426 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
Andy Hung446f4df2019-02-21 12:26:41 -08003427 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
3428 ? systemTime() : mLastIoBeginNs;
Andy Hung69488c42016-05-16 18:43:33 -07003429 }
Andy Hungdae27702016-10-31 14:01:16 -07003430
3431 for (const sp<Track> &t : mActiveTracks) {
3432 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003433 t->updateTrackFrameInfo(
3434 t->mAudioTrackServerProxy->framesReleased(),
3435 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003436 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003437 mTimestamp);
3438 }
Andy Hunge10393e2015-06-12 13:59:33 -07003439 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003440 }
Andy Hunge6c37112019-02-26 17:38:10 -08003441
3442 if (audio_has_proportional_frames(mFormat)) {
3443 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
3444 if (latencyMs != 0.) { // note 0. means timestamp is empty.
3445 mLatencyMs.add(latencyMs);
3446 }
3447 }
3448
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003449 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003450#if 0
3451 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003452 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003453 timespec ts;
3454 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003455 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003456 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003457 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003458 }
3459 ++z;
3460#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003461 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003462 if (mSignalPending) {
3463 // A signal was raised while we were unlocked
3464 mSignalPending = false;
3465 } else if (waitingAsyncCallback_l()) {
3466 if (exitPending()) {
3467 break;
3468 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003469 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003470 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003471 releaseWakeLock_l();
3472 released = true;
3473 }
Andy Hung10cbff12017-02-21 17:30:14 -08003474
3475 const int64_t waitNs = computeWaitTimeNs_l();
3476 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3477 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3478 if (status == TIMED_OUT) {
3479 mSignalPending = true; // if timeout recheck everything
3480 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003481 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003482 if (released) {
3483 acquireWakeLock_l();
3484 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003485 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3486 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003487
3488 continue;
3489 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003490 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003491 isSuspended()) {
3492 // put audio hardware into standby after short delay
3493 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003494
3495 threadLoop_standby();
3496
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003497 // This is where we go into standby
3498 if (!mStandby) {
3499 LOG_AUDIO_STATE();
3500 }
Eric Laurent81784c32012-11-19 14:55:58 -08003501 mStandby = true;
Andy Hungd0979812019-02-21 15:51:44 -08003502 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003503 }
3504
Eric Tan39ec8d62018-07-24 09:49:29 -07003505 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003506 // we're about to wait, flush the binder command buffer
3507 IPCThreadState::self()->flushCommands();
3508
3509 clearOutputTracks();
3510
3511 if (exitPending()) {
3512 break;
3513 }
3514
3515 releaseWakeLock_l();
3516 // wait until we have something to do...
3517 ALOGV("%s going to sleep", myName.string());
3518 mWaitWorkCV.wait(mLock);
3519 ALOGV("%s waking up", myName.string());
3520 acquireWakeLock_l();
3521
3522 mMixerStatus = MIXER_IDLE;
3523 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3524 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003525 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003526 checkSilentMode_l();
3527
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003528 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3529 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003530 if (mType == MIXER) {
3531 sleepTimeShift = 0;
3532 }
3533
3534 continue;
3535 }
3536 }
Eric Laurent81784c32012-11-19 14:55:58 -08003537 // mMixerStatusIgnoringFastTracks is also updated internally
3538 mMixerStatus = prepareTracks_l(&tracksToRemove);
3539
Andy Hungdae27702016-10-31 14:01:16 -07003540 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003541
Kevin Rocard069c2712018-03-29 19:09:14 -07003542 updateMetadata_l();
3543
Eric Laurent81784c32012-11-19 14:55:58 -08003544 // prevent any changes in effect chain list and in each effect chain
3545 // during mixing and effect process as the audio buffers could be deleted
3546 // or modified if an effect is created or deleted
3547 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003548 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003549
Eric Laurentbfb1b832013-01-07 09:53:42 -08003550 if (mBytesRemaining == 0) {
3551 mCurrentWriteLength = 0;
3552 if (mMixerStatus == MIXER_TRACKS_READY) {
3553 // threadLoop_mix() sets mCurrentWriteLength
3554 threadLoop_mix();
3555 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3556 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003557 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003558 // must be written to HAL
3559 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003560 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003561 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003562 }
3563 }
Andy Hung98ef9782014-03-04 14:46:50 -08003564 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003565 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003566 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3567 // or mSinkBuffer (if there are no effects).
3568 //
3569 // This is done pre-effects computation; if effects change to
3570 // support higher precision, this needs to move.
3571 //
3572 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003573 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003574 if (mMixerBufferValid) {
3575 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3576 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3577
Andy Hung2ddee192015-12-18 17:34:44 -08003578 // mono blend occurs for mixer threads only (not direct or offloaded)
3579 // and is handled here if we're going directly to the sink.
3580 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003581 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3582 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003583 }
3584
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003585 if (!hasFastMixer()) {
3586 // Balance must take effect after mono conversion.
3587 // We do it here if there is no FastMixer.
3588 // mBalance detects zero balance within the class for speed (not needed here).
3589 mBalance.setBalance(mMasterBalance.load());
3590 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3591 }
3592
Andy Hung98ef9782014-03-04 14:46:50 -08003593 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003594 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3595
3596 // If we're going directly to the sink and there are haptic channels,
3597 // we should adjust channels as the sample data is partially interleaved
3598 // in this case.
3599 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3600 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3601 mChannelCount + mHapticChannelCount,
3602 audio_bytes_per_sample(format),
3603 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3604 }
Andy Hung98ef9782014-03-04 14:46:50 -08003605 }
3606
Eric Laurentbfb1b832013-01-07 09:53:42 -08003607 mBytesRemaining = mCurrentWriteLength;
3608 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003609 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3610 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3611 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3612 mBytesWritten += mBytesRemaining;
3613 mFramesWritten += framesRemaining;
3614 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003615 mBytesRemaining = 0;
3616 }
Eric Laurent81784c32012-11-19 14:55:58 -08003617
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003619 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
jiabin47affe52019-04-04 18:02:07 -07003620 audio_session_t activeHapticId = AUDIO_SESSION_NONE;
3621 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3622 for (auto track : mActiveTracks) {
3623 if (track->getHapticPlaybackEnabled()) {
3624 activeHapticId = track->sessionId();
3625 break;
3626 }
3627 }
3628 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003629 for (size_t i = 0; i < effectChains.size(); i ++) {
3630 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003631 // TODO: Write haptic data directly to sink buffer when mixing.
3632 if (activeHapticId != AUDIO_SESSION_NONE
3633 && activeHapticId == effectChains[i]->sessionId()) {
3634 // Haptic data is active in this case, copy it directly from
3635 // in buffer to out buffer.
3636 const size_t audioBufferSize = mNormalFrameCount
3637 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3638 memcpy_by_audio_format(
3639 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3640 EFFECT_BUFFER_FORMAT,
3641 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3642 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3643 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003644 }
Eric Laurent81784c32012-11-19 14:55:58 -08003645 }
3646 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003647 // Process effect chains for offloaded thread even if no audio
3648 // was read from audio track: process only updates effect state
3649 // and thus does have to be synchronized with audio writes but may have
3650 // to be called while waiting for async write callback
3651 if (mType == OFFLOAD) {
3652 for (size_t i = 0; i < effectChains.size(); i ++) {
3653 effectChains[i]->process_l();
3654 }
3655 }
Eric Laurent81784c32012-11-19 14:55:58 -08003656
Andy Hung98ef9782014-03-04 14:46:50 -08003657 // Only if the Effects buffer is enabled and there is data in the
3658 // Effects buffer (buffer valid), we need to
3659 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003660 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003661 if (mEffectBufferValid) {
3662 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003663
3664 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003665 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3666 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003667 }
3668
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003669 if (!hasFastMixer()) {
3670 // Balance must take effect after mono conversion.
3671 // We do it here if there is no FastMixer.
3672 // mBalance detects zero balance within the class for speed (not needed here).
3673 mBalance.setBalance(mMasterBalance.load());
3674 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3675 }
3676
Andy Hung98ef9782014-03-04 14:46:50 -08003677 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003678 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3679 // The sample data is partially interleaved when haptic channels exist,
3680 // we need to adjust channels here.
3681 if (mHapticChannelCount > 0) {
3682 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3683 mChannelCount + mHapticChannelCount,
3684 audio_bytes_per_sample(mFormat),
3685 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3686 }
Andy Hung98ef9782014-03-04 14:46:50 -08003687 }
3688
Eric Laurent81784c32012-11-19 14:55:58 -08003689 // enable changes in effect chain
3690 unlockEffectChains(effectChains);
3691
Eric Laurentbfb1b832013-01-07 09:53:42 -08003692 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003693 // mSleepTimeUs == 0 means we must write to audio hardware
3694 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003695 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003696 // writePeriodNs is updated >= 0 when ret > 0.
3697 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003698 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003699 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003700 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003701 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003702 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003703 if (ret < 0) {
3704 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003705 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003706 mBytesWritten += ret;
3707 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003708 const int64_t frames = ret / mFrameSize;
3709 mFramesWritten += frames;
3710
3711 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3712 // process information relating to write time.
3713 if (audio_has_proportional_frames(mFormat)) {
3714 // we are in a continuous mixing cycle
3715 if (mMixerStatus == MIXER_TRACKS_READY &&
3716 loopCount == lastLoopCountWritten + 1) {
3717
3718 const double jitterMs =
3719 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3720 {frames, writePeriodNs},
3721 {0, 0} /* lastTimestamp */, mSampleRate);
3722 const double processMs =
3723 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3724
3725 Mutex::Autolock _l(mLock);
3726 mIoJitterMs.add(jitterMs);
3727 mProcessTimeMs.add(processMs);
3728 }
3729
3730 // write blocked detection
3731 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3732 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3733 mNumDelayedWrites++;
3734 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3735 ATRACE_NAME("underrun");
3736 ALOGW("write blocked for %lld msecs, "
3737 "%d delayed writes, thread %d",
3738 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3739 mNumDelayedWrites, mId);
3740 lastWarning = lastIoEndNs;
3741 }
3742 }
3743 }
3744 // update timing info.
3745 mLastIoBeginNs = lastIoBeginNs;
3746 mLastIoEndNs = lastIoEndNs;
3747 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003748 }
3749 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3750 (mMixerStatus == MIXER_DRAIN_ALL)) {
3751 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003752 }
Andy Hung08fb1742015-05-31 23:22:10 -07003753 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003754
3755 if (mThreadThrottle
3756 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003757 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003758 // Limit MixerThread data processing to no more than twice the
3759 // expected processing rate.
3760 //
3761 // This helps prevent underruns with NuPlayer and other applications
3762 // which may set up buffers that are close to the minimum size, or use
3763 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3764 //
3765 // The throttle smooths out sudden large data drains from the device,
3766 // e.g. when it comes out of standby, which often causes problems with
3767 // (1) mixer threads without a fast mixer (which has its own warm-up)
3768 // (2) minimum buffer sized tracks (even if the track is full,
3769 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003770 //
3771 // Total time spent in last processing cycle equals time spent in
3772 // 1. threadLoop_write, as well as time spent in
3773 // 2. threadLoop_mix (significant for heavy mixing, especially
3774 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003775
Andy Hung446f4df2019-02-21 12:26:41 -08003776 // it's OK if deltaMs is an overestimate.
3777
3778 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003779
Ivan Lozanoea04d392017-11-07 14:37:07 -08003780 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003781 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3782 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003783 // notify of throttle start on verbose log
3784 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3785 "mixer(%p) throttle begin:"
3786 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003787 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003788 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003789 // Throttle must be attributed to the previous mixer loop's write time
3790 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003791 // This also ensures proper timing statistics.
3792 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003793 } else {
3794 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3795 if (diff > 0) {
3796 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003797 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003798 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3799 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003800 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003801 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3802 }
Andy Hung08fb1742015-05-31 23:22:10 -07003803 }
3804 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003805 }
Eric Laurent81784c32012-11-19 14:55:58 -08003806
Eric Laurentbfb1b832013-01-07 09:53:42 -08003807 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003808 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003809 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003810 // suspended requires accurate metering of sleep time.
3811 if (isSuspended()) {
3812 // advance by expected sleepTime
3813 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3814 const nsecs_t nowNs = systemTime();
3815
3816 // compute expected next time vs current time.
3817 // (negative deltas are treated as delays).
3818 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3819 if (deltaNs < -kMaxNextBufferDelayNs) {
3820 // Delays longer than the max allowed trigger a reset.
3821 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3822 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3823 timeLoopNextNs = nowNs + deltaNs;
3824 } else if (deltaNs < 0) {
3825 // Delays within the max delay allowed: zero the delta/sleepTime
3826 // to help the system catch up in the next iteration(s)
3827 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3828 deltaNs = 0;
3829 }
3830 // update sleep time (which is >= 0)
3831 mSleepTimeUs = deltaNs / 1000;
3832 }
Eric Laurente93cc032016-05-05 10:15:10 -07003833 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3834 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003835 }
Glenn Kastene7754022014-10-31 12:11:26 -07003836 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003837 }
Eric Laurent81784c32012-11-19 14:55:58 -08003838 }
3839
3840 // Finally let go of removed track(s), without the lock held
3841 // since we can't guarantee the destructors won't acquire that
3842 // same lock. This will also mutate and push a new fast mixer state.
3843 threadLoop_removeTracks(tracksToRemove);
3844 tracksToRemove.clear();
3845
3846 // FIXME I don't understand the need for this here;
3847 // it was in the original code but maybe the
3848 // assignment in saveOutputTracks() makes this unnecessary?
3849 clearOutputTracks();
3850
3851 // Effect chains will be actually deleted here if they were removed from
3852 // mEffectChains list during mixing or effects processing
3853 effectChains.clear();
3854
3855 // FIXME Note that the above .clear() is no longer necessary since effectChains
3856 // is now local to this block, but will keep it for now (at least until merge done).
3857 }
3858
Eric Laurentbfb1b832013-01-07 09:53:42 -08003859 threadLoop_exit();
3860
Eric Laurentcf817a22014-08-04 20:36:31 -07003861 if (!mStandby) {
3862 threadLoop_standby();
3863 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003864 }
3865
3866 releaseWakeLock();
3867
3868 ALOGV("Thread %p type %d exiting", this, mType);
3869 return false;
3870}
3871
Eric Laurentbfb1b832013-01-07 09:53:42 -08003872// removeTracks_l() must be called with ThreadBase::mLock held
3873void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3874{
Andy Hungfe726a62018-09-27 15:17:25 -07003875 for (const auto& track : tracksToRemove) {
3876 mActiveTracks.remove(track);
3877 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3878 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3879 if (chain != 0) {
3880 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3881 __func__, track->id(), chain.get(), track->sessionId());
3882 chain->decActiveTrackCnt();
3883 }
3884 // If an external client track, inform APM we're no longer active, and remove if needed.
3885 // We do this under lock so that the state is consistent if the Track is destroyed.
3886 if (track->isExternalTrack()) {
3887 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003888 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003889 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003890 }
3891 }
Andy Hungfe726a62018-09-27 15:17:25 -07003892 if (track->isTerminated()) {
3893 // remove from our tracks vector
3894 removeTrack_l(track);
3895 }
jiabin57303cc2018-12-18 15:45:57 -08003896 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
3897 && mHapticChannelCount > 0) {
3898 mLock.unlock();
3899 // Unlock due to VibratorService will lock for this call and will
3900 // call Tracks.mute/unmute which also require thread's lock.
3901 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
3902 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08003903 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003904 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003905}
Eric Laurent81784c32012-11-19 14:55:58 -08003906
Eric Laurentaccc1472013-09-20 09:36:34 -07003907status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3908{
3909 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003910 ExtendedTimestamp ets;
3911 status_t status = mNormalSink->getTimestamp(ets);
3912 if (status == NO_ERROR) {
3913 status = ets.getBestTimestamp(&timestamp);
3914 }
3915 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003916 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003917 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003918 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003919 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003920 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11003921 if (mDownstreamLatencyStatMs.getN() > 0) {
3922 const uint32_t positionOffset =
3923 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3924 if (positionOffset > timestamp.mPosition) {
3925 timestamp.mPosition = 0;
3926 } else {
3927 timestamp.mPosition -= positionOffset;
3928 }
3929 }
Eric Laurentaccc1472013-09-20 09:36:34 -07003930 return NO_ERROR;
3931 }
3932 }
3933 return INVALID_OPERATION;
3934}
Eric Laurent1c333e22014-05-20 10:48:17 -07003935
Eric Laurent054d9d32015-04-24 08:48:48 -07003936status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3937 audio_patch_handle_t *handle)
3938{
Andy Hungf60abce2016-08-26 11:37:54 -07003939 status_t status;
3940 if (property_get_bool("af.patch_park", false /* default_value */)) {
3941 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3942 // or if HAL does not properly lock against access.
3943 AutoPark<FastMixer> park(mFastMixer);
3944 status = PlaybackThread::createAudioPatch_l(patch, handle);
3945 } else {
3946 status = PlaybackThread::createAudioPatch_l(patch, handle);
3947 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003948 return status;
3949}
3950
Eric Laurent1c333e22014-05-20 10:48:17 -07003951status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3952 audio_patch_handle_t *handle)
3953{
3954 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003955
3956 // store new device and send to effects
3957 audio_devices_t type = AUDIO_DEVICE_NONE;
3958 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3959 type |= patch->sinks[i].ext.device.type;
3960 }
3961
François Gaffie0c280aa2018-07-25 10:02:15 +02003962 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07003963#ifdef ADD_BATTERY_DATA
3964 // when changing the audio output device, call addBatteryData to notify
3965 // the change
3966 if (mOutDevice != type) {
3967 uint32_t params = 0;
3968 // check whether speaker is on
3969 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3970 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003971 }
3972
Eric Laurent054d9d32015-04-24 08:48:48 -07003973 audio_devices_t deviceWithoutSpeaker
3974 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3975 // check if any other device (except speaker) is on
3976 if (type & deviceWithoutSpeaker) {
3977 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3978 }
3979
3980 if (params != 0) {
3981 addBatteryData(params);
3982 }
3983 }
3984#endif
3985
3986 for (size_t i = 0; i < mEffectChains.size(); i++) {
3987 mEffectChains[i]->setDevice_l(type);
3988 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003989
3990 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3991 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
François Gaffie0c280aa2018-07-25 10:02:15 +02003992 bool configChanged = (mPrevOutDevice != type) || (mDeviceId != sinkPortId);
Eric Laurent054d9d32015-04-24 08:48:48 -07003993 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003994 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003995
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003996 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003997 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3998 status = hwDevice->createAudioPatch(patch->num_sources,
3999 patch->sources,
4000 patch->num_sinks,
4001 patch->sinks,
4002 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004003 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004004 char *address;
4005 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4006 //FIXME: we only support address on first sink with HAL version < 3.0
4007 address = audio_device_address_to_parameter(
4008 patch->sinks[0].ext.device.type,
4009 patch->sinks[0].ext.device.address);
4010 } else {
4011 address = (char *)calloc(1, 1);
4012 }
4013 AudioParameter param = AudioParameter(String8(address));
4014 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004015 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004016 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004017 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004018 }
Eric Laurente8726fe2015-06-26 09:39:24 -07004019 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004020 mPrevOutDevice = type;
François Gaffie0c280aa2018-07-25 10:02:15 +02004021 mDeviceId = sinkPortId;
Eric Laurente8726fe2015-06-26 09:39:24 -07004022 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4023 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004024 return status;
4025}
4026
Eric Laurent054d9d32015-04-24 08:48:48 -07004027status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4028{
Andy Hungf60abce2016-08-26 11:37:54 -07004029 status_t status;
4030 if (property_get_bool("af.patch_park", false /* default_value */)) {
4031 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4032 // or if HAL does not properly lock against access.
4033 AutoPark<FastMixer> park(mFastMixer);
4034 status = PlaybackThread::releaseAudioPatch_l(handle);
4035 } else {
4036 status = PlaybackThread::releaseAudioPatch_l(handle);
4037 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004038 return status;
4039}
4040
Eric Laurent1c333e22014-05-20 10:48:17 -07004041status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4042{
4043 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004044
4045 mOutDevice = AUDIO_DEVICE_NONE;
4046
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004047 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004048 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4049 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004050 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004051 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004052 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004053 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004054 }
4055 return status;
4056}
4057
Eric Laurent83b88082014-06-20 18:31:16 -07004058void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4059{
4060 Mutex::Autolock _l(mLock);
4061 mTracks.add(track);
4062}
4063
4064void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4065{
4066 Mutex::Autolock _l(mLock);
4067 destroyTrack_l(track);
4068}
4069
Mikhail Naganovdc769682018-05-04 15:34:08 -07004070void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004071{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004072 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004073 config->role = AUDIO_PORT_ROLE_SOURCE;
4074 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4075 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004076 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4077 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4078 config->flags.output = mOutput->flags;
4079 }
Eric Laurent83b88082014-06-20 18:31:16 -07004080}
4081
Eric Laurent81784c32012-11-19 14:55:58 -08004082// ----------------------------------------------------------------------------
4083
4084AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07004085 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
4086 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004087 // mAudioMixer below
4088 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004089 mFastMixerFutex(0),
4090 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004091 // mOutputSink below
4092 // mPipeSink below
4093 // mNormalSink below
4094{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004095 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08004096 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004097 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004098 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004099 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4100 mNormalFrameCount);
4101 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4102
Andy Hungfbfc3952015-01-15 13:33:51 -08004103 if (type == DUPLICATING) {
4104 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4105 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4106 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4107 return;
4108 }
Eric Laurent81784c32012-11-19 14:55:58 -08004109 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004110 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004111 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004112 const NBAIO_Format offers[1] = {Format_from_SR_C(
4113 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004114#if !LOG_NDEBUG
4115 ssize_t index =
4116#else
4117 (void)
4118#endif
4119 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004120 ALOG_ASSERT(index == 0);
4121
4122 // initialize fast mixer depending on configuration
4123 bool initFastMixer;
4124 switch (kUseFastMixer) {
4125 case FastMixer_Never:
4126 initFastMixer = false;
4127 break;
4128 case FastMixer_Always:
4129 initFastMixer = true;
4130 break;
4131 case FastMixer_Static:
4132 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004133 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4134 // where the period is less than an experimentally determined threshold that can be
4135 // scheduled reliably with CFS. However, the BT A2DP HAL is
4136 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4137 initFastMixer = mFrameCount < mNormalFrameCount
4138 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004139 break;
4140 }
Andy Hungfda69402017-02-15 14:33:12 -08004141 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4142 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4143 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004144 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004145 audio_format_t fastMixerFormat;
4146 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4147 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4148 } else {
4149 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4150 }
4151 if (mFormat != fastMixerFormat) {
4152 // change our Sink format to accept our intermediate precision
4153 mFormat = fastMixerFormat;
4154 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004155 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004156 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4157 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4158 }
Eric Laurent81784c32012-11-19 14:55:58 -08004159
4160 // create a MonoPipe to connect our submix to FastMixer
4161 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004162
Andy Hung1258c1a2014-05-23 21:22:17 -07004163 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004164 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004165 format.mFormat = fastMixerFormat;
4166 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4167
Eric Laurent81784c32012-11-19 14:55:58 -08004168 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4169 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4170 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4171 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4172 const NBAIO_Format offers[1] = {format};
4173 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004174#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004175 ssize_t index =
4176#else
4177 (void)
4178#endif
4179 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004180 ALOG_ASSERT(index == 0);
4181 monoPipe->setAvgFrames((mScreenState & 1) ?
4182 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4183 mPipeSink = monoPipe;
4184
Eric Laurent81784c32012-11-19 14:55:58 -08004185 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004186 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004187 FastMixerStateQueue *sq = mFastMixer->sq();
4188#ifdef STATE_QUEUE_DUMP
4189 sq->setObserverDump(&mStateQueueObserverDump);
4190 sq->setMutatorDump(&mStateQueueMutatorDump);
4191#endif
4192 FastMixerState *state = sq->begin();
4193 FastTrack *fastTrack = &state->mFastTracks[0];
4194 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4195 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4196 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004197 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4198 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004199 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004200 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabin84114c32019-04-10 16:38:07 -07004201 fastTrack->mHapticIntensity = AudioMixer::HAPTIC_SCALE_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004202 fastTrack->mGeneration++;
4203 state->mFastTracksGen++;
4204 state->mTrackMask = 1;
4205 // fast mixer will use the HAL output sink
4206 state->mOutputSink = mOutputSink.get();
4207 state->mOutputSinkGen++;
4208 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004209 // specify sink channel mask when haptic channel mask present as it can not
4210 // be calculated directly from channel count
4211 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4212 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004213 state->mCommand = FastMixerState::COLD_IDLE;
4214 // already done in constructor initialization list
4215 //mFastMixerFutex = 0;
4216 state->mColdFutexAddr = &mFastMixerFutex;
4217 state->mColdGen++;
4218 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004219 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4220 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004221 sq->end();
4222 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4223
Eric Tan0513b5d2018-09-17 10:32:48 -07004224 NBLog::thread_info_t info;
4225 info.id = mId;
4226 info.type = NBLog::FASTMIXER;
4227 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4228
Eric Laurent81784c32012-11-19 14:55:58 -08004229 // start the fast mixer
4230 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4231 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004232 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004233 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004234
4235#ifdef AUDIO_WATCHDOG
4236 // create and start the watchdog
4237 mAudioWatchdog = new AudioWatchdog();
4238 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4239 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4240 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004241 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004242#endif
Andy Hung8946a282018-04-19 20:04:56 -07004243 } else {
4244#ifdef TEE_SINK
4245 // Only use the MixerThread tee if there is no FastMixer.
4246 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4247 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4248#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004249 }
4250
4251 switch (kUseFastMixer) {
4252 case FastMixer_Never:
4253 case FastMixer_Dynamic:
4254 mNormalSink = mOutputSink;
4255 break;
4256 case FastMixer_Always:
4257 mNormalSink = mPipeSink;
4258 break;
4259 case FastMixer_Static:
4260 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4261 break;
4262 }
4263}
4264
4265AudioFlinger::MixerThread::~MixerThread()
4266{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004267 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004268 FastMixerStateQueue *sq = mFastMixer->sq();
4269 FastMixerState *state = sq->begin();
4270 if (state->mCommand == FastMixerState::COLD_IDLE) {
4271 int32_t old = android_atomic_inc(&mFastMixerFutex);
4272 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004273 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004274 }
4275 }
4276 state->mCommand = FastMixerState::EXIT;
4277 sq->end();
4278 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4279 mFastMixer->join();
4280 // Though the fast mixer thread has exited, it's state queue is still valid.
4281 // We'll use that extract the final state which contains one remaining fast track
4282 // corresponding to our sub-mix.
4283 state = sq->begin();
4284 ALOG_ASSERT(state->mTrackMask == 1);
4285 FastTrack *fastTrack = &state->mFastTracks[0];
4286 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4287 delete fastTrack->mBufferProvider;
4288 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004289 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004290#ifdef AUDIO_WATCHDOG
4291 if (mAudioWatchdog != 0) {
4292 mAudioWatchdog->requestExit();
4293 mAudioWatchdog->requestExitAndWait();
4294 mAudioWatchdog.clear();
4295 }
4296#endif
4297 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004298 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004299 delete mAudioMixer;
4300}
4301
4302
4303uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4304{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004305 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004306 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4307 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4308 }
4309 return latency;
4310}
4311
Eric Laurentbfb1b832013-01-07 09:53:42 -08004312ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004313{
4314 // FIXME we should only do one push per cycle; confirm this is true
4315 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004316 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004317 FastMixerStateQueue *sq = mFastMixer->sq();
4318 FastMixerState *state = sq->begin();
4319 if (state->mCommand != FastMixerState::MIX_WRITE &&
4320 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4321 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004322
4323 // FIXME workaround for first HAL write being CPU bound on some devices
4324 ATRACE_BEGIN("write");
4325 mOutput->write((char *)mSinkBuffer, 0);
4326 ATRACE_END();
4327
Eric Laurent81784c32012-11-19 14:55:58 -08004328 int32_t old = android_atomic_inc(&mFastMixerFutex);
4329 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004330 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004331 }
4332#ifdef AUDIO_WATCHDOG
4333 if (mAudioWatchdog != 0) {
4334 mAudioWatchdog->resume();
4335 }
4336#endif
4337 }
4338 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004339#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004340 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004341 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004342#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004343 sq->end();
4344 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4345 if (kUseFastMixer == FastMixer_Dynamic) {
4346 mNormalSink = mPipeSink;
4347 }
4348 } else {
4349 sq->end(false /*didModify*/);
4350 }
4351 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004352 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004353}
4354
4355void AudioFlinger::MixerThread::threadLoop_standby()
4356{
4357 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004358 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004359 FastMixerStateQueue *sq = mFastMixer->sq();
4360 FastMixerState *state = sq->begin();
4361 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004362 // Report any frames trapped in the Monopipe
4363 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4364 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4365 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4366 "monoPipeWritten:%lld monoPipeLeft:%lld",
4367 (long long)mFramesWritten, (long long)mSuspendedFrames,
4368 (long long)mPipeSink->framesWritten(), pipeFrames);
4369 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4370
Eric Laurent81784c32012-11-19 14:55:58 -08004371 state->mCommand = FastMixerState::COLD_IDLE;
4372 state->mColdFutexAddr = &mFastMixerFutex;
4373 state->mColdGen++;
4374 mFastMixerFutex = 0;
4375 sq->end();
4376 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4377 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4378 if (kUseFastMixer == FastMixer_Dynamic) {
4379 mNormalSink = mOutputSink;
4380 }
4381#ifdef AUDIO_WATCHDOG
4382 if (mAudioWatchdog != 0) {
4383 mAudioWatchdog->pause();
4384 }
4385#endif
4386 } else {
4387 sq->end(false /*didModify*/);
4388 }
4389 }
4390 PlaybackThread::threadLoop_standby();
4391}
4392
Eric Laurentbfb1b832013-01-07 09:53:42 -08004393bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4394{
4395 return false;
4396}
4397
4398bool AudioFlinger::PlaybackThread::shouldStandby_l()
4399{
4400 return !mStandby;
4401}
4402
4403bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4404{
4405 Mutex::Autolock _l(mLock);
4406 return waitingAsyncCallback_l();
4407}
4408
Eric Laurent81784c32012-11-19 14:55:58 -08004409// shared by MIXER and DIRECT, overridden by DUPLICATING
4410void AudioFlinger::PlaybackThread::threadLoop_standby()
4411{
4412 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004413 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004414 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004415 // discard any pending drain or write ack by incrementing sequence
4416 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4417 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004418 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004419 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4420 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004421 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004422 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004423}
4424
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004425void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4426{
4427 ALOGV("signal playback thread");
4428 broadcast_l();
4429}
4430
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004431void AudioFlinger::PlaybackThread::onAsyncError()
4432{
4433 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4434 invalidateTracks((audio_stream_type_t)i);
4435 }
4436}
4437
Eric Laurent81784c32012-11-19 14:55:58 -08004438void AudioFlinger::MixerThread::threadLoop_mix()
4439{
Eric Laurent81784c32012-11-19 14:55:58 -08004440 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004441 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004442 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004443 // increase sleep time progressively when application underrun condition clears.
4444 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4445 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4446 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004447 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004448 sleepTimeShift--;
4449 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004450 mSleepTimeUs = 0;
4451 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004452 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004453
Eric Laurent81784c32012-11-19 14:55:58 -08004454}
4455
4456void AudioFlinger::MixerThread::threadLoop_sleepTime()
4457{
4458 // If no tracks are ready, sleep once for the duration of an output
4459 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004460 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004461 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004462 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4463 // Using the Monopipe availableToWrite, we estimate the
4464 // sleep time to retry for more data (before we underrun).
4465 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4466 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4467 const size_t pipeFrames = monoPipe->maxFrames();
4468 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4469 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4470 const size_t framesDelay = std::min(
4471 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4472 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4473 pipeFrames, framesLeft, framesDelay);
4474 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4475 } else {
4476 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4477 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4478 mSleepTimeUs = kMinThreadSleepTimeUs;
4479 }
4480 // reduce sleep time in case of consecutive application underruns to avoid
4481 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4482 // duration we would end up writing less data than needed by the audio HAL if
4483 // the condition persists.
4484 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4485 sleepTimeShift++;
4486 }
Eric Laurent81784c32012-11-19 14:55:58 -08004487 }
4488 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004489 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004490 }
4491 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004492 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4493 // before effects processing or output.
4494 if (mMixerBufferValid) {
4495 memset(mMixerBuffer, 0, mMixerBufferSize);
4496 } else {
4497 memset(mSinkBuffer, 0, mSinkBufferSize);
4498 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004499 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004500 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4501 "anticipated start");
4502 }
4503 // TODO add standby time extension fct of effect tail
4504}
4505
4506// prepareTracks_l() must be called with ThreadBase::mLock held
4507AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4508 Vector< sp<Track> > *tracksToRemove)
4509{
Andy Hungc0691382018-09-12 18:01:57 -07004510 // clean up deleted track ids in AudioMixer before allocating new tracks
4511 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4512 // for each trackId, destroy it in the AudioMixer
4513 if (mAudioMixer->exists(trackId)) {
4514 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004515 }
4516 });
Andy Hungc0691382018-09-12 18:01:57 -07004517 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004518
4519 mixer_state mixerStatus = MIXER_IDLE;
4520 // find out which tracks need to be processed
4521 size_t count = mActiveTracks.size();
4522 size_t mixedTracks = 0;
4523 size_t tracksWithEffect = 0;
4524 // counts only _active_ fast tracks
4525 size_t fastTracks = 0;
4526 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4527
4528 float masterVolume = mMasterVolume;
4529 bool masterMute = mMasterMute;
4530
4531 if (masterMute) {
4532 masterVolume = 0;
4533 }
4534 // Delegate master volume control to effect in output mix effect chain if needed
4535 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4536 if (chain != 0) {
4537 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4538 chain->setVolume_l(&v, &v);
4539 masterVolume = (float)((v + (1 << 23)) >> 24);
4540 chain.clear();
4541 }
4542
4543 // prepare a new state to push
4544 FastMixerStateQueue *sq = NULL;
4545 FastMixerState *state = NULL;
4546 bool didModify = false;
4547 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004548 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004549 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004550 sq = mFastMixer->sq();
4551 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004552 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004553 }
4554
Andy Hung69aed5f2014-02-25 17:24:40 -08004555 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004556 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004557
Andy Hungbd3b2b02018-05-21 10:53:11 -07004558 // DeferredOperations handles statistics after setting mixerStatus.
4559 class DeferredOperations {
4560 public:
4561 DeferredOperations(mixer_state *mixerStatus)
4562 : mMixerStatus(mixerStatus) { }
4563
4564 // when leaving scope, tally frames properly.
4565 ~DeferredOperations() {
4566 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4567 // because that is when the underrun occurs.
4568 // We do not distinguish between FastTracks and NormalTracks here.
4569 if (*mMixerStatus == MIXER_TRACKS_READY) {
4570 for (const auto &underrun : mUnderrunFrames) {
4571 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4572 underrun.second);
4573 }
4574 }
4575 }
4576
4577 // tallyUnderrunFrames() is called to update the track counters
4578 // with the number of underrun frames for a particular mixer period.
4579 // We defer tallying until we know the final mixer status.
4580 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4581 mUnderrunFrames.emplace_back(track, underrunFrames);
4582 }
4583
4584 private:
4585 const mixer_state * const mMixerStatus;
4586 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4587 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4588
jiabin245cdd92018-12-07 17:55:15 -08004589 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004590 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004591 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004592
4593 // this const just means the local variable doesn't change
4594 Track* const track = t.get();
4595
4596 // process fast tracks
4597 if (track->isFastTrack()) {
jiabin245cdd92018-12-07 17:55:15 -08004598 if (track->getHapticPlaybackEnabled()) {
4599 noFastHapticTrack = false;
4600 }
Eric Laurent81784c32012-11-19 14:55:58 -08004601
4602 // It's theoretically possible (though unlikely) for a fast track to be created
4603 // and then removed within the same normal mix cycle. This is not a problem, as
4604 // the track never becomes active so it's fast mixer slot is never touched.
4605 // The converse, of removing an (active) track and then creating a new track
4606 // at the identical fast mixer slot within the same normal mix cycle,
4607 // is impossible because the slot isn't marked available until the end of each cycle.
4608 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004609 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004610 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4611 FastTrack *fastTrack = &state->mFastTracks[j];
4612
4613 // Determine whether the track is currently in underrun condition,
4614 // and whether it had a recent underrun.
4615 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4616 FastTrackUnderruns underruns = ftDump->mUnderruns;
4617 uint32_t recentFull = (underruns.mBitFields.mFull -
4618 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4619 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4620 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4621 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4622 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4623 uint32_t recentUnderruns = recentPartial + recentEmpty;
4624 track->mObservedUnderruns = underruns;
4625 // don't count underruns that occur while stopping or pausing
4626 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004627 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004628 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4629 recentUnderruns > 0) {
4630 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004631 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004632 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004633 // Immediately account for FastTrack underruns.
4634 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004635
4636 // This is similar to the state machine for normal tracks,
4637 // with a few modifications for fast tracks.
4638 bool isActive = true;
4639 switch (track->mState) {
4640 case TrackBase::STOPPING_1:
4641 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004642 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004643 track->mState = TrackBase::STOPPING_2;
4644 }
4645 break;
4646 case TrackBase::PAUSING:
4647 // ramp down is not yet implemented
4648 track->setPaused();
4649 break;
4650 case TrackBase::RESUMING:
4651 // ramp up is not yet implemented
4652 track->mState = TrackBase::ACTIVE;
4653 break;
4654 case TrackBase::ACTIVE:
4655 if (recentFull > 0 || recentPartial > 0) {
4656 // track has provided at least some frames recently: reset retry count
4657 track->mRetryCount = kMaxTrackRetries;
4658 }
4659 if (recentUnderruns == 0) {
4660 // no recent underruns: stay active
4661 break;
4662 }
4663 // there has recently been an underrun of some kind
4664 if (track->sharedBuffer() == 0) {
4665 // were any of the recent underruns "empty" (no frames available)?
4666 if (recentEmpty == 0) {
4667 // no, then ignore the partial underruns as they are allowed indefinitely
4668 break;
4669 }
4670 // there has recently been an "empty" underrun: decrement the retry counter
4671 if (--(track->mRetryCount) > 0) {
4672 break;
4673 }
4674 // indicate to client process that the track was disabled because of underrun;
4675 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004676 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004677 // remove from active list, but state remains ACTIVE [confusing but true]
4678 isActive = false;
4679 break;
4680 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004681 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004682 case TrackBase::STOPPING_2:
4683 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004684 case TrackBase::STOPPED:
4685 case TrackBase::FLUSHED: // flush() while active
4686 // Check for presentation complete if track is inactive
4687 // We have consumed all the buffers of this track.
4688 // This would be incomplete if we auto-paused on underrun
4689 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004690 uint32_t latency = 0;
4691 status_t result = mOutput->stream->getLatency(&latency);
4692 ALOGE_IF(result != OK,
4693 "Error when retrieving output stream latency: %d", result);
4694 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004695 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004696 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4697 // track stays in active list until presentation is complete
4698 break;
4699 }
4700 }
4701 if (track->isStopping_2()) {
4702 track->mState = TrackBase::STOPPED;
4703 }
4704 if (track->isStopped()) {
4705 // Can't reset directly, as fast mixer is still polling this track
4706 // track->reset();
4707 // So instead mark this track as needing to be reset after push with ack
4708 resetMask |= 1 << i;
4709 }
4710 isActive = false;
4711 break;
4712 case TrackBase::IDLE:
4713 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004714 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004715 }
4716
4717 if (isActive) {
4718 // was it previously inactive?
4719 if (!(state->mTrackMask & (1 << j))) {
4720 ExtendedAudioBufferProvider *eabp = track;
4721 VolumeProvider *vp = track;
4722 fastTrack->mBufferProvider = eabp;
4723 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004724 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004725 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08004726 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08004727 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08004728 fastTrack->mGeneration++;
4729 state->mTrackMask |= 1 << j;
4730 didModify = true;
4731 // no acknowledgement required for newly active tracks
4732 }
Kevin Rocard12381092018-04-11 09:19:59 -07004733 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004734 // cache the combined master volume and stream type volume for fast mixer; this
4735 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004736 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004737 proxy->framesReleased()).first;
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08004738 float volume;
4739 if (track->isPlaybackRestricted()) {
4740 volume = 0.f;
4741 } else {
4742 volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004743 * mStreamTypes[track->streamType()].volume
4744 * vh;
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08004745 }
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004746 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004747 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4748 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4749 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4750 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004751 ++fastTracks;
4752 } else {
4753 // was it previously active?
4754 if (state->mTrackMask & (1 << j)) {
4755 fastTrack->mBufferProvider = NULL;
4756 fastTrack->mGeneration++;
4757 state->mTrackMask &= ~(1 << j);
4758 didModify = true;
4759 // If any fast tracks were removed, we must wait for acknowledgement
4760 // because we're about to decrement the last sp<> on those tracks.
4761 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4762 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004763 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4764 // AudioTrack may start (which may not be with a start() but with a write()
4765 // after underrun) and immediately paused or released. In that case the
4766 // FastTrack state hasn't had time to update.
4767 // TODO Remove the ALOGW when this theory is confirmed.
4768 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004769 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4770 j, track->mState, state->mTrackMask, recentUnderruns,
4771 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004772 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004773 }
4774 tracksToRemove->add(track);
4775 // Avoids a misleading display in dumpsys
4776 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4777 }
jiabin245cdd92018-12-07 17:55:15 -08004778 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
4779 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
4780 didModify = true;
4781 }
Eric Laurent81784c32012-11-19 14:55:58 -08004782 continue;
4783 }
4784
4785 { // local variable scope to avoid goto warning
4786
4787 audio_track_cblk_t* cblk = track->cblk();
4788
4789 // The first time a track is added we wait
4790 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004791 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004792
4793 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004794 // use the trackId as the AudioMixer name.
4795 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004796 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004797 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004798 track->mChannelMask,
4799 track->mFormat,
4800 track->mSessionId);
4801 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004802 ALOGW("%s(): AudioMixer cannot create track(%d)"
4803 " mask %#x, format %#x, sessionId %d",
4804 __func__, trackId,
4805 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004806 tracksToRemove->add(track);
4807 track->invalidate(); // consider it dead.
4808 continue;
4809 }
4810 }
4811
Eric Laurent81784c32012-11-19 14:55:58 -08004812 // make sure that we have enough frames to mix one full buffer.
4813 // enforce this condition only once to enable draining the buffer in case the client
4814 // app does not call stop() and relies on underrun to stop:
4815 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4816 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004817 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004818 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004819 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004820
4821 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004822 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004823 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4824 // add frames already consumed but not yet released by the resampler
4825 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004826 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004827
Eric Laurent81784c32012-11-19 14:55:58 -08004828 uint32_t minFrames = 1;
4829 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4830 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004831 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004832 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004833
4834 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004835 if (ATRACE_ENABLED()) {
4836 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004837 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004838 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004839 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004840 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004841 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004842 !track->isPaused() && !track->isTerminated())
4843 {
Andy Hungc0691382018-09-12 18:01:57 -07004844 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004845
4846 mixedTracks++;
4847
Andy Hung69aed5f2014-02-25 17:24:40 -08004848 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4849 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004850 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004851 if (track->mainBuffer() != mSinkBuffer &&
4852 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004853 if (mEffectBufferEnabled) {
4854 mEffectBufferValid = true; // Later can set directly.
4855 }
Eric Laurent81784c32012-11-19 14:55:58 -08004856 chain = getEffectChain_l(track->sessionId());
4857 // Delegate volume control to effect in track effect chain if needed
4858 if (chain != 0) {
4859 tracksWithEffect++;
4860 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004861 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004862 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004863 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004864 }
4865 }
4866
4867
4868 int param = AudioMixer::VOLUME;
4869 if (track->mFillingUpStatus == Track::FS_FILLED) {
4870 // no ramp for the first volume setting
4871 track->mFillingUpStatus = Track::FS_ACTIVE;
4872 if (track->mState == TrackBase::RESUMING) {
4873 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08004874 // If a new track is paused immediately after start, do not ramp on resume.
4875 if (cblk->mServer != 0) {
4876 param = AudioMixer::RAMP_VOLUME;
4877 }
Eric Laurent81784c32012-11-19 14:55:58 -08004878 }
Andy Hungc0691382018-09-12 18:01:57 -07004879 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004880 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004881 // FIXME should not make a decision based on mServer
4882 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004883 // If the track is stopped before the first frame was mixed,
4884 // do not apply ramp
4885 param = AudioMixer::RAMP_VOLUME;
4886 }
4887
4888 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004889 uint32_t vl, vr; // in U8.24 integer format
4890 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004891 // read original volumes with volume control
4892 float typeVolume = mStreamTypes[track->streamType()].volume;
4893 float v = masterVolume * typeVolume;
4894
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08004895 if (track->isPausing() || mStreamTypes[track->streamType()].mute
4896 || track->isPlaybackRestricted()) {
Andy Hung6be49402014-05-30 10:42:03 -07004897 vl = vr = 0;
4898 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004899 if (track->isPausing()) {
4900 track->setPaused();
4901 }
4902 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004903 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004904 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004905 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4906 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004907 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004908 if (vlf > GAIN_FLOAT_UNITY) {
4909 ALOGV("Track left volume out of range: %.3g", vlf);
4910 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004911 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004912 if (vrf > GAIN_FLOAT_UNITY) {
4913 ALOGV("Track right volume out of range: %.3g", vrf);
4914 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004915 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004916 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004917 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004918 // now apply the master volume and stream type volume and shaper volume
4919 vlf *= v * vh;
4920 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004921 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004922 // then derive vl and vr as U8.24 versions for the effect chain
4923 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4924 vl = (uint32_t) (scaleto8_24 * vlf);
4925 vr = (uint32_t) (scaleto8_24 * vrf);
4926 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004927 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004928 // send level comes from shared memory and so may be corrupt
4929 if (sendLevel > MAX_GAIN_INT) {
4930 ALOGV("Track send level out of range: %04X", sendLevel);
4931 sendLevel = MAX_GAIN_INT;
4932 }
Andy Hung6be49402014-05-30 10:42:03 -07004933 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4934 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004935 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004936
Kevin Rocard12381092018-04-11 09:19:59 -07004937 track->setFinalVolume((vrf + vlf) / 2.f);
4938
Eric Laurent81784c32012-11-19 14:55:58 -08004939 // Delegate volume control to effect in track effect chain if needed
4940 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4941 // Do not ramp volume if volume is controlled by effect
4942 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004943 // Update remaining floating point volume levels
4944 vlf = (float)vl / (1 << 24);
4945 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004946 track->mHasVolumeController = true;
4947 } else {
4948 // force no volume ramp when volume controller was just disabled or removed
4949 // from effect chain to avoid volume spike
4950 if (track->mHasVolumeController) {
4951 param = AudioMixer::VOLUME;
4952 }
4953 track->mHasVolumeController = false;
4954 }
4955
Eric Laurent7c29ec92017-09-20 17:54:22 -07004956 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4957 // still applied by the mixer.
4958 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4959 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4960 if (v != mLeftVolFloat) {
4961 status_t result = mOutput->stream->setVolume(v, v);
4962 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4963 if (result == OK) {
4964 mLeftVolFloat = v;
4965 }
4966 }
4967 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4968 // remove stream volume contribution from software volume.
4969 if (v != 0.0f && mLeftVolFloat == v) {
4970 vlf = min(1.0f, vlf / v);
4971 vrf = min(1.0f, vrf / v);
4972 vaf = min(1.0f, vaf / v);
4973 }
4974 }
Eric Laurent81784c32012-11-19 14:55:58 -08004975 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07004976 mAudioMixer->setBufferProvider(trackId, track);
4977 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004978
Andy Hungc0691382018-09-12 18:01:57 -07004979 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
4980 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
4981 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004982 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004983 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004984 AudioMixer::TRACK,
4985 AudioMixer::FORMAT, (void *)track->format());
4986 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004987 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004988 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004989 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004990 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004991 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07004992 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08004993 AudioMixer::MIXER_CHANNEL_MASK,
4994 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08004995 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004996 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004997 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004998 if (reqSampleRate == 0) {
4999 reqSampleRate = mSampleRate;
5000 } else if (reqSampleRate > maxSampleRate) {
5001 reqSampleRate = maxSampleRate;
5002 }
Eric Laurent81784c32012-11-19 14:55:58 -08005003 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005004 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005005 AudioMixer::RESAMPLE,
5006 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005007 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005008
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005009 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005010 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005011 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005012 AudioMixer::TIMESTRETCH,
5013 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005014 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005015
Andy Hung69aed5f2014-02-25 17:24:40 -08005016 /*
5017 * Select the appropriate output buffer for the track.
5018 *
Andy Hung98ef9782014-03-04 14:46:50 -08005019 * Tracks with effects go into their own effects chain buffer
5020 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005021 *
5022 * Other tracks can use mMixerBuffer for higher precision
5023 * channel accumulation. If this buffer is enabled
5024 * (mMixerBufferEnabled true), then selected tracks will accumulate
5025 * into it.
5026 *
5027 */
5028 if (mMixerBufferEnabled
5029 && (track->mainBuffer() == mSinkBuffer
5030 || track->mainBuffer() == mMixerBuffer)) {
5031 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005032 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005033 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005034 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005035 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005036 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005037 AudioMixer::TRACK,
5038 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5039 // TODO: override track->mainBuffer()?
5040 mMixerBufferValid = true;
5041 } else {
5042 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005043 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005044 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005045 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005046 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005047 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005048 AudioMixer::TRACK,
5049 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5050 }
Eric Laurent81784c32012-11-19 14:55:58 -08005051 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005052 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005053 AudioMixer::TRACK,
5054 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005055 mAudioMixer->setParameter(
5056 trackId,
5057 AudioMixer::TRACK,
5058 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005059 mAudioMixer->setParameter(
5060 trackId,
5061 AudioMixer::TRACK,
5062 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005063
5064 // reset retry count
5065 track->mRetryCount = kMaxTrackRetries;
5066
5067 // If one track is ready, set the mixer ready if:
5068 // - the mixer was not ready during previous round OR
5069 // - no other track is not ready
5070 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5071 mixerStatus != MIXER_TRACKS_ENABLED) {
5072 mixerStatus = MIXER_TRACKS_READY;
5073 }
5074 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005075 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005076 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07005077 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
5078 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005079 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005080 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005081 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005082
Eric Laurent81784c32012-11-19 14:55:58 -08005083 // clear effect chain input buffer if an active track underruns to avoid sending
5084 // previous audio buffer again to effects
5085 chain = getEffectChain_l(track->sessionId());
5086 if (chain != 0) {
5087 chain->clearInputBuffer();
5088 }
5089
Andy Hungc0691382018-09-12 18:01:57 -07005090 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005091 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5092 track->isStopped() || track->isPaused()) {
5093 // We have consumed all the buffers of this track.
5094 // Remove it from the list of active tracks.
5095 // TODO: use actual buffer filling status instead of latency when available from
5096 // audio HAL
5097 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005098 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005099 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5100 if (track->isStopped()) {
5101 track->reset();
5102 }
5103 tracksToRemove->add(track);
5104 }
5105 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005106 // No buffers for this track. Give it a few chances to
5107 // fill a buffer, then remove it from active list.
5108 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005109 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5110 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005111 tracksToRemove->add(track);
5112 // indicate to client process that the track was disabled because of underrun;
5113 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005114 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005115 // If one track is not ready, mark the mixer also not ready if:
5116 // - the mixer was ready during previous round OR
5117 // - no other track is ready
5118 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5119 mixerStatus != MIXER_TRACKS_READY) {
5120 mixerStatus = MIXER_TRACKS_ENABLED;
5121 }
5122 }
Andy Hungc0691382018-09-12 18:01:57 -07005123 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005124 }
5125
5126 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005127
5128 }
5129
jiabin245cdd92018-12-07 17:55:15 -08005130 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5131 // When there is no fast track playing haptic and FastMixer exists,
5132 // enabling the first FastTrack, which provides mixed data from normal
5133 // tracks, to play haptic data.
5134 FastTrack *fastTrack = &state->mFastTracks[0];
5135 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5136 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5137 didModify = true;
5138 }
5139 }
5140
Eric Laurent81784c32012-11-19 14:55:58 -08005141 // Push the new FastMixer state if necessary
5142 bool pauseAudioWatchdog = false;
5143 if (didModify) {
5144 state->mFastTracksGen++;
5145 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5146 if (kUseFastMixer == FastMixer_Dynamic &&
5147 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5148 state->mCommand = FastMixerState::COLD_IDLE;
5149 state->mColdFutexAddr = &mFastMixerFutex;
5150 state->mColdGen++;
5151 mFastMixerFutex = 0;
5152 if (kUseFastMixer == FastMixer_Dynamic) {
5153 mNormalSink = mOutputSink;
5154 }
5155 // If we go into cold idle, need to wait for acknowledgement
5156 // so that fast mixer stops doing I/O.
5157 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5158 pauseAudioWatchdog = true;
5159 }
Eric Laurent81784c32012-11-19 14:55:58 -08005160 }
5161 if (sq != NULL) {
5162 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005163 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5164 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5165 // when bringing the output sink into standby.)
5166 //
5167 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5168 //
5169 // This occurs with BT suspend when we idle the FastMixer with
5170 // active tracks, which may be added or removed.
5171 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005172 }
5173#ifdef AUDIO_WATCHDOG
5174 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5175 mAudioWatchdog->pause();
5176 }
5177#endif
5178
5179 // Now perform the deferred reset on fast tracks that have stopped
5180 while (resetMask != 0) {
5181 size_t i = __builtin_ctz(resetMask);
5182 ALOG_ASSERT(i < count);
5183 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005184 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005185 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5186 track->reset();
5187 }
5188
Andy Hung80d03d22018-04-10 10:32:11 -07005189 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5190 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5191 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5192 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5193 // See also the implementation of destroyTrack_l().
5194 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005195 const int trackId = track->id();
5196 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5197 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005198 }
5199 }
5200
Eric Laurent81784c32012-11-19 14:55:58 -08005201 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005202 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005203
Eric Laurent97d547d2014-09-02 14:45:53 -07005204 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5205 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005206 }
5207
5208 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005209 // as long as there are effects we should clear the effects buffer, to avoid
5210 // passing a non-clean buffer to the effect chain
5211 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005212 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005213 // sink or mix buffer must be cleared if all tracks are connected to an
5214 // effect chain as in this case the mixer will not write to the sink or mix buffer
5215 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005216 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5217 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005218 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005219 if (mMixerBufferValid) {
5220 memset(mMixerBuffer, 0, mMixerBufferSize);
5221 // TODO: In testing, mSinkBuffer below need not be cleared because
5222 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5223 // after mixing.
5224 //
5225 // To enforce this guarantee:
5226 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5227 // (mixedTracks == 0 && fastTracks > 0))
5228 // must imply MIXER_TRACKS_READY.
5229 // Later, we may clear buffers regardless, and skip much of this logic.
5230 }
Andy Hung98ef9782014-03-04 14:46:50 -08005231 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005232 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005233 }
5234
5235 // if any fast tracks, then status is ready
5236 mMixerStatusIgnoringFastTracks = mixerStatus;
5237 if (fastTracks > 0) {
5238 mixerStatus = MIXER_TRACKS_READY;
5239 }
5240 return mixerStatus;
5241}
5242
Eric Laurentad7dd962016-09-22 12:38:37 -07005243// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005244uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005245{
5246 uint32_t trackCount = 0;
5247 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005248 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005249 trackCount++;
5250 }
5251 }
5252 return trackCount;
5253}
5254
Andy Hung1bc088a2018-02-09 15:57:31 -08005255// isTrackAllowed_l() must be called with ThreadBase::mLock held
5256bool AudioFlinger::MixerThread::isTrackAllowed_l(
5257 audio_channel_mask_t channelMask, audio_format_t format,
5258 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005259{
Andy Hung1bc088a2018-02-09 15:57:31 -08005260 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5261 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005262 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005263 // Check validity as we don't call AudioMixer::create() here.
5264 if (!AudioMixer::isValidFormat(format)) {
5265 ALOGW("%s: invalid format: %#x", __func__, format);
5266 return false;
5267 }
5268 if (!AudioMixer::isValidChannelMask(channelMask)) {
5269 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5270 return false;
5271 }
5272 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005273}
5274
Eric Laurent10351942014-05-08 18:49:52 -07005275// checkForNewParameter_l() must be called with ThreadBase::mLock held
5276bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5277 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005278{
Eric Laurent81784c32012-11-19 14:55:58 -08005279 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005280 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005281
Eric Laurent10351942014-05-08 18:49:52 -07005282 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005283
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005284 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005285
Eric Laurent10351942014-05-08 18:49:52 -07005286 AudioParameter param = AudioParameter(keyValuePair);
5287 int value;
5288 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5289 reconfig = true;
5290 }
5291 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005292 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005293 status = BAD_VALUE;
5294 } else {
5295 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005296 reconfig = true;
5297 }
Eric Laurent10351942014-05-08 18:49:52 -07005298 }
5299 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005300 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005301 status = BAD_VALUE;
5302 } else {
5303 // no need to save value, since it's constant
5304 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005305 }
Eric Laurent10351942014-05-08 18:49:52 -07005306 }
5307 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5308 // do not accept frame count changes if tracks are open as the track buffer
5309 // size depends on frame count and correct behavior would not be guaranteed
5310 // if frame count is changed after track creation
5311 if (!mTracks.isEmpty()) {
5312 status = INVALID_OPERATION;
5313 } else {
5314 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005315 }
Eric Laurent10351942014-05-08 18:49:52 -07005316 }
5317 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005318#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005319 // when changing the audio output device, call addBatteryData to notify
5320 // the change
5321 if (mOutDevice != value) {
5322 uint32_t params = 0;
5323 // check whether speaker is on
5324 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5325 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005326 }
Eric Laurent10351942014-05-08 18:49:52 -07005327
5328 audio_devices_t deviceWithoutSpeaker
5329 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5330 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005331 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005332 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5333 }
5334
5335 if (params != 0) {
5336 addBatteryData(params);
5337 }
5338 }
Eric Laurent81784c32012-11-19 14:55:58 -08005339#endif
5340
Eric Laurent10351942014-05-08 18:49:52 -07005341 // forward device change to effects that have requested to be
5342 // aware of attached audio device.
5343 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005344 a2dpDeviceChanged =
5345 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005346 mOutDevice = value;
5347 for (size_t i = 0; i < mEffectChains.size(); i++) {
5348 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005349 }
5350 }
Eric Laurent10351942014-05-08 18:49:52 -07005351 }
Eric Laurent81784c32012-11-19 14:55:58 -08005352
Eric Laurent10351942014-05-08 18:49:52 -07005353 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005354 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005355 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005356 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005357 mStandby = true;
5358 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005359 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005360 }
Eric Laurent10351942014-05-08 18:49:52 -07005361 if (status == NO_ERROR && reconfig) {
5362 readOutputParameters_l();
5363 delete mAudioMixer;
5364 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005365 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005366 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005367 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005368 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005369 track->mChannelMask,
5370 track->mFormat,
5371 track->mSessionId);
5372 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005373 "%s(): AudioMixer cannot create track(%d)"
5374 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005375 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005376 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005377 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005378 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005379 }
Eric Laurent81784c32012-11-19 14:55:58 -08005380 }
5381
Eric Laurent42537be2016-01-08 17:16:42 -08005382 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005383}
5384
5385
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005386void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005387{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005388 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005389 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005390 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005391 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005392 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5393 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5394 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005395 if (hasFastMixer()) {
5396 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5397
5398 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5399 // while we are dumping it. It may be inconsistent, but it won't mutate!
5400 // This is a large object so we place it on the heap.
5401 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005402 const std::unique_ptr<FastMixerDumpState> copy =
5403 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005404 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005405
5406#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005407 // Similar for state queue
5408 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5409 observerCopy.dump(fd);
5410 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5411 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005412#endif
5413
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005414#ifdef AUDIO_WATCHDOG
5415 if (mAudioWatchdog != 0) {
5416 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5417 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5418 wdCopy.dump(fd);
5419 }
5420#endif
5421
5422 } else {
5423 dprintf(fd, " No FastMixer\n");
5424 }
Eric Laurent81784c32012-11-19 14:55:58 -08005425}
5426
5427uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5428{
5429 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5430}
5431
5432uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5433{
5434 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5435}
5436
5437void AudioFlinger::MixerThread::cacheParameters_l()
5438{
5439 PlaybackThread::cacheParameters_l();
5440
5441 // FIXME: Relaxed timing because of a certain device that can't meet latency
5442 // Should be reduced to 2x after the vendor fixes the driver issue
5443 // increase threshold again due to low power audio mode. The way this warning
5444 // threshold is calculated and its usefulness should be reconsidered anyway.
5445 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5446}
5447
5448// ----------------------------------------------------------------------------
5449
5450AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Andy Hung48f59ed2019-01-28 15:06:59 -08005451 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005452 ThreadBase::type_t type, bool systemReady)
5453 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005454{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005455 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005456}
5457
Eric Laurent81784c32012-11-19 14:55:58 -08005458AudioFlinger::DirectOutputThread::~DirectOutputThread()
5459{
5460}
5461
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005462void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005463{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005464 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005465 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5466 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5467}
5468
5469void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5470{
5471 Mutex::Autolock _l(mLock);
5472 if (mMasterBalance != balance) {
5473 mMasterBalance.store(balance);
5474 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5475 broadcast_l();
5476 }
5477}
5478
Eric Laurent5850c4c2016-11-10 13:04:31 -08005479void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005480{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005481 float left, right;
5482
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005483 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005484 left = right = 0;
5485 } else {
5486 float typeVolume = mStreamTypes[track->streamType()].volume;
5487 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005488 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005489
Andy Hung10cbff12017-02-21 17:30:14 -08005490 // Get volumeshaper scaling
5491 std::pair<float /* volume */, bool /* active */>
5492 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005493 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005494 v *= vh.first;
5495 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005496
Glenn Kastenc56f3422014-03-21 17:53:17 -07005497 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5498 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5499 if (left > GAIN_FLOAT_UNITY) {
5500 left = GAIN_FLOAT_UNITY;
5501 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005502 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005503 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5504 if (right > GAIN_FLOAT_UNITY) {
5505 right = GAIN_FLOAT_UNITY;
5506 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005507 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005508 }
5509
5510 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005511 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005512 if (left != mLeftVolFloat || right != mRightVolFloat) {
5513 mLeftVolFloat = left;
5514 mRightVolFloat = right;
5515
Eric Laurentbfb1b832013-01-07 09:53:42 -08005516 // Delegate volume control to effect in track effect chain if needed
5517 // only one effect chain can be present on DirectOutputThread, so if
5518 // there is one, the track is connected to it
5519 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005520 // if effect chain exists, volume is handled by it.
5521 // Convert volumes from float to 8.24
5522 uint32_t vl = (uint32_t)(left * (1 << 24));
5523 uint32_t vr = (uint32_t)(right * (1 << 24));
5524 // Direct/Offload effect chains set output volume in setVolume_l().
5525 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5526 } else {
5527 // otherwise we directly set the volume.
5528 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005529 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005530 }
5531 }
5532}
5533
Phil Burk43b4dcc2015-06-09 16:53:44 -07005534void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5535{
5536 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005537 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005538
Eric Laurent0f0631e2015-07-06 18:01:25 -07005539 if (previousTrack != 0 && latestTrack != 0) {
5540 if (mType == DIRECT) {
5541 if (previousTrack.get() != latestTrack.get()) {
5542 mFlushPending = true;
5543 }
5544 } else /* mType == OFFLOAD */ {
5545 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5546 mFlushPending = true;
5547 }
5548 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005549 } else if (previousTrack == 0) {
5550 // there could be an old track added back during track transition for direct
5551 // output, so always issues flush to flush data of the previous track if it
5552 // was already destroyed with HAL paused, then flush can resume the playback
5553 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005554 }
5555 PlaybackThread::onAddNewTrack_l();
5556}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005557
Eric Laurent81784c32012-11-19 14:55:58 -08005558AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5559 Vector< sp<Track> > *tracksToRemove
5560)
5561{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005562 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005563 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005564 bool doHwPause = false;
5565 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005566
5567 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005568 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005569 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005570 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005571 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005572 continue;
5573 }
5574
Eric Laurent5850c4c2016-11-10 13:04:31 -08005575 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005576#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005577 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005578#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005579 // Only consider last track started for volume and mixer state control.
5580 // In theory an older track could underrun and restart after the new one starts
5581 // but as we only care about the transition phase between two tracks on a
5582 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005583 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005584 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005585
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005586 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005587 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005588 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005589 doHwPause = true;
5590 mHwPaused = true;
5591 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005592 } else if (track->isFlushPending()) {
5593 track->flushAck();
5594 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005595 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005596 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005597 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005598 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005599 if (last) {
5600 mLeftVolFloat = mRightVolFloat = -1.0;
5601 if (mHwPaused) {
5602 doHwResume = true;
5603 mHwPaused = false;
5604 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005605 }
5606 }
5607
Eric Laurent81784c32012-11-19 14:55:58 -08005608 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005609 // for all its buffers to be filled before processing it.
5610 // Allow draining the buffer in case the client
5611 // app does not call stop() and relies on underrun to stop:
5612 // hence the test on (track->mRetryCount > 1).
5613 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005614 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005615 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005616 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005617 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005618 minFrames = mNormalFrameCount;
5619 } else {
5620 minFrames = 1;
5621 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005622
Eric Laurentab5cdba2014-06-09 17:22:27 -07005623 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5624 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005625 {
Andy Hungc0691382018-09-12 18:01:57 -07005626 ALOGVV("track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005627
5628 if (track->mFillingUpStatus == Track::FS_FILLED) {
5629 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005630 if (last) {
5631 // make sure processVolume_l() will apply new volume even if 0
5632 mLeftVolFloat = mRightVolFloat = -1.0;
5633 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005634 if (!mHwSupportsPause) {
5635 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005636 }
5637 }
5638
5639 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005640 processVolume_l(track, last);
5641 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005642 sp<Track> previousTrack = mPreviousTrack.promote();
5643 if (previousTrack != 0) {
5644 if (track != previousTrack.get()) {
5645 // Flush any data still being written from last track
5646 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005647 // Invalidate previous track to force a seek when resuming.
5648 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005649 }
5650 }
5651 mPreviousTrack = track;
5652
Eric Laurentd595b7c2013-04-03 17:27:56 -07005653 // reset retry count
5654 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005655 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005656 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005657 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005658 doHwResume = true;
5659 mHwPaused = false;
5660 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005661 }
Eric Laurent81784c32012-11-19 14:55:58 -08005662 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005663 // clear effect chain input buffer if the last active track started underruns
5664 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005665 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005666 mEffectChains[0]->clearInputBuffer();
5667 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005668 if (track->isStopping_1()) {
5669 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005670 if (last && mHwPaused) {
5671 doHwResume = true;
5672 mHwPaused = false;
5673 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005674 }
5675 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5676 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005677 // We have consumed all the buffers of this track.
5678 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005679 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005680 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005681 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5682 } else {
5683 audioHALFrames = 0;
5684 }
5685
Andy Hung818e7a32016-02-16 18:08:07 -08005686 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005687 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005688 track->presentationComplete(framesWritten, audioHALFrames) ||
5689 track->isPaused()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005690 if (track->isStopping_2()) {
5691 track->mState = TrackBase::STOPPED;
5692 }
Eric Laurent81784c32012-11-19 14:55:58 -08005693 if (track->isStopped()) {
5694 track->reset();
5695 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005696 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005697 }
5698 } else {
5699 // No buffers for this track. Give it a few chances to
5700 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005701 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005702 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005703 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", track->id());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005704 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005705 // indicate to client process that the track was disabled because of underrun;
5706 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005707 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005708 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005709 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5710 "minFrames = %u, mFormat = %#x",
5711 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005712 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005713 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005714 doHwPause = true;
5715 mHwPaused = true;
5716 }
Eric Laurent81784c32012-11-19 14:55:58 -08005717 }
5718 }
5719 }
5720 }
5721
Eric Laurentd1f69b02014-12-15 14:33:13 -08005722 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005723 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005724 for (size_t i = 0; i < mTracks.size(); i++) {
5725 if (mTracks[i]->isFlushPending()) {
5726 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005727 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005728 }
5729 }
5730 }
5731
5732 // make sure the pause/flush/resume sequence is executed in the right order.
5733 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5734 // before flush and then resume HW. This can happen in case of pause/flush/resume
5735 // if resume is received before pause is executed.
5736 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005737 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005738 status_t result = mOutput->stream->pause();
5739 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005740 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005741 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005742 flushHw_l();
5743 }
5744 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005745 status_t result = mOutput->stream->resume();
5746 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005747 }
Eric Laurent81784c32012-11-19 14:55:58 -08005748 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005749 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005750
5751 return mixerStatus;
5752}
5753
5754void AudioFlinger::DirectOutputThread::threadLoop_mix()
5755{
Eric Laurent81784c32012-11-19 14:55:58 -08005756 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005757 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005758 // output audio to hardware
5759 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005760 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005761 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005762 status_t status = mActiveTrack->getNextBuffer(&buffer);
5763 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005764 // no need to pad with 0 for compressed audio
5765 if (audio_has_proportional_frames(mFormat)) {
5766 memset(curBuf, 0, frameCount * mFrameSize);
5767 }
Eric Laurent81784c32012-11-19 14:55:58 -08005768 break;
5769 }
5770 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5771 frameCount -= buffer.frameCount;
5772 curBuf += buffer.frameCount * mFrameSize;
5773 mActiveTrack->releaseBuffer(&buffer);
5774 }
Andy Hung2098f272014-02-27 14:00:06 -08005775 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005776 mSleepTimeUs = 0;
5777 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005778 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005779}
5780
5781void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5782{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005783 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005784 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005785 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005786 return;
5787 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005788 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005789 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005790 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005791 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005792 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005793 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005794 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005795 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005796 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005797 }
5798}
5799
Eric Laurentd1f69b02014-12-15 14:33:13 -08005800void AudioFlinger::DirectOutputThread::threadLoop_exit()
5801{
5802 {
5803 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005804 for (size_t i = 0; i < mTracks.size(); i++) {
5805 if (mTracks[i]->isFlushPending()) {
5806 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005807 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005808 }
5809 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005810 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005811 flushHw_l();
5812 }
5813 }
5814 PlaybackThread::threadLoop_exit();
5815}
5816
5817// must be called with thread mutex locked
5818bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5819{
5820 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005821 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005822
vivek mehta9cd7ad12016-03-17 00:18:29 -07005823 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5824 return !mStandby;
5825 }
5826
Eric Laurentd1f69b02014-12-15 14:33:13 -08005827 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5828 // after a timeout and we will enter standby then.
5829 if (mTracks.size() > 0) {
5830 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005831 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5832 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005833 }
5834
Eric Laurent5cff4032015-05-26 13:49:58 -07005835 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005836}
5837
Eric Laurent10351942014-05-08 18:49:52 -07005838// checkForNewParameter_l() must be called with ThreadBase::mLock held
5839bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5840 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005841{
5842 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005843 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005844
Eric Laurent10351942014-05-08 18:49:52 -07005845 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005846
Eric Laurent10351942014-05-08 18:49:52 -07005847 AudioParameter param = AudioParameter(keyValuePair);
5848 int value;
5849 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5850 // forward device change to effects that have requested to be
5851 // aware of attached audio device.
5852 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005853 a2dpDeviceChanged =
5854 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005855 mOutDevice = value;
5856 for (size_t i = 0; i < mEffectChains.size(); i++) {
5857 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005858 }
5859 }
Eric Laurent81784c32012-11-19 14:55:58 -08005860 }
Eric Laurent10351942014-05-08 18:49:52 -07005861 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5862 // do not accept frame count changes if tracks are open as the track buffer
5863 // size depends on frame count and correct behavior would not be garantied
5864 // if frame count is changed after track creation
5865 if (!mTracks.isEmpty()) {
5866 status = INVALID_OPERATION;
5867 } else {
5868 reconfig = true;
5869 }
5870 }
5871 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005872 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005873 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005874 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005875 mStandby = true;
5876 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005877 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005878 }
5879 if (status == NO_ERROR && reconfig) {
5880 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005881 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005882 }
5883 }
5884
Eric Laurent42537be2016-01-08 17:16:42 -08005885 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005886}
5887
5888uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5889{
5890 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005891 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005892 time = PlaybackThread::activeSleepTimeUs();
5893 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005894 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005895 }
5896 return time;
5897}
5898
5899uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5900{
5901 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005902 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005903 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5904 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005905 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005906 }
5907 return time;
5908}
5909
5910uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5911{
5912 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005913 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005914 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5915 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005916 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005917 }
5918 return time;
5919}
5920
5921void AudioFlinger::DirectOutputThread::cacheParameters_l()
5922{
5923 PlaybackThread::cacheParameters_l();
5924
5925 // use shorter standby delay as on normal output to release
5926 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005927 // no delay on outputs with HW A/V sync
5928 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005929 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005930 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005931 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005932 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005933 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005934 }
Eric Laurent81784c32012-11-19 14:55:58 -08005935}
5936
Eric Laurente659ef42014-09-29 13:06:46 -07005937void AudioFlinger::DirectOutputThread::flushHw_l()
5938{
Phil Burk062e67a2015-02-11 13:40:50 -08005939 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005940 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005941 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005942 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005943}
5944
Andy Hung10cbff12017-02-21 17:30:14 -08005945int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5946 // If a VolumeShaper is active, we must wake up periodically to update volume.
5947 const int64_t NS_PER_MS = 1000000;
5948 return mVolumeShaperActive ?
5949 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5950}
5951
Eric Laurent81784c32012-11-19 14:55:58 -08005952// ----------------------------------------------------------------------------
5953
Eric Laurentbfb1b832013-01-07 09:53:42 -08005954AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005955 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005956 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005957 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005958 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005959 mDrainSequence(0),
5960 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005961{
5962}
5963
5964AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5965{
5966}
5967
5968void AudioFlinger::AsyncCallbackThread::onFirstRef()
5969{
5970 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5971}
5972
5973bool AudioFlinger::AsyncCallbackThread::threadLoop()
5974{
5975 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005976 uint32_t writeAckSequence;
5977 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005978 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005979
5980 {
5981 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005982 while (!((mWriteAckSequence & 1) ||
5983 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005984 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005985 exitPending())) {
5986 mWaitWorkCV.wait(mLock);
5987 }
5988
Eric Laurentbfb1b832013-01-07 09:53:42 -08005989 if (exitPending()) {
5990 break;
5991 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005992 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5993 mWriteAckSequence, mDrainSequence);
5994 writeAckSequence = mWriteAckSequence;
5995 mWriteAckSequence &= ~1;
5996 drainSequence = mDrainSequence;
5997 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005998 asyncError = mAsyncError;
5999 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006000 }
6001 {
Eric Laurent4de95592013-09-26 15:28:21 -07006002 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6003 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006004 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006005 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006006 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006007 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006008 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006009 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006010 if (asyncError) {
6011 playbackThread->onAsyncError();
6012 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006013 }
6014 }
6015 }
6016 return false;
6017}
6018
6019void AudioFlinger::AsyncCallbackThread::exit()
6020{
6021 ALOGV("AsyncCallbackThread::exit");
6022 Mutex::Autolock _l(mLock);
6023 requestExit();
6024 mWaitWorkCV.broadcast();
6025}
6026
Eric Laurent3b4529e2013-09-05 18:09:19 -07006027void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006028{
6029 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006030 // bit 0 is cleared
6031 mWriteAckSequence = sequence << 1;
6032}
6033
6034void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6035{
6036 Mutex::Autolock _l(mLock);
6037 // ignore unexpected callbacks
6038 if (mWriteAckSequence & 2) {
6039 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006040 mWaitWorkCV.signal();
6041 }
6042}
6043
Eric Laurent3b4529e2013-09-05 18:09:19 -07006044void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006045{
6046 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006047 // bit 0 is cleared
6048 mDrainSequence = sequence << 1;
6049}
6050
6051void AudioFlinger::AsyncCallbackThread::resetDraining()
6052{
6053 Mutex::Autolock _l(mLock);
6054 // ignore unexpected callbacks
6055 if (mDrainSequence & 2) {
6056 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006057 mWaitWorkCV.signal();
6058 }
6059}
6060
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006061void AudioFlinger::AsyncCallbackThread::setAsyncError()
6062{
6063 Mutex::Autolock _l(mLock);
6064 mAsyncError = true;
6065 mWaitWorkCV.signal();
6066}
6067
Eric Laurentbfb1b832013-01-07 09:53:42 -08006068
6069// ----------------------------------------------------------------------------
6070AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07006071 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
6072 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006073 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6074 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006075{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006076 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006077 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006078 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006079}
6080
Eric Laurentbfb1b832013-01-07 09:53:42 -08006081void AudioFlinger::OffloadThread::threadLoop_exit()
6082{
6083 if (mFlushPending || mHwPaused) {
6084 // If a flush is pending or track was paused, just discard buffered data
6085 flushHw_l();
6086 } else {
6087 mMixerStatus = MIXER_DRAIN_ALL;
6088 threadLoop_drain();
6089 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006090 if (mUseAsyncWrite) {
6091 ALOG_ASSERT(mCallbackThread != 0);
6092 mCallbackThread->exit();
6093 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006094 PlaybackThread::threadLoop_exit();
6095}
6096
6097AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6098 Vector< sp<Track> > *tracksToRemove
6099)
6100{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006101 size_t count = mActiveTracks.size();
6102
6103 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006104 bool doHwPause = false;
6105 bool doHwResume = false;
6106
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006107 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006108
Eric Laurentbfb1b832013-01-07 09:53:42 -08006109 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006110 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006111 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006112#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006113 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006114#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006115 // Only consider last track started for volume and mixer state control.
6116 // In theory an older track could underrun and restart after the new one starts
6117 // but as we only care about the transition phase between two tracks on a
6118 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006119 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006120 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006121
Haynes Mathew George7844f672014-01-15 12:32:55 -08006122 if (track->isInvalid()) {
6123 ALOGW("An invalidated track shouldn't be in active list");
6124 tracksToRemove->add(track);
6125 continue;
6126 }
6127
6128 if (track->mState == TrackBase::IDLE) {
6129 ALOGW("An idle track shouldn't be in active list");
6130 continue;
6131 }
6132
Eric Laurentbfb1b832013-01-07 09:53:42 -08006133 if (track->isPausing()) {
6134 track->setPaused();
6135 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006136 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006137 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006138 mHwPaused = true;
6139 }
6140 // If we were part way through writing the mixbuffer to
6141 // the HAL we must save this until we resume
6142 // BUG - this will be wrong if a different track is made active,
6143 // in that case we want to discard the pending data in the
6144 // mixbuffer and tell the client to present it again when the
6145 // track is resumed
6146 mPausedWriteLength = mCurrentWriteLength;
6147 mPausedBytesRemaining = mBytesRemaining;
6148 mBytesRemaining = 0; // stop writing
6149 }
6150 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006151 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006152 if (track->isStopping_1()) {
6153 track->mRetryCount = kMaxTrackStopRetriesOffload;
6154 } else {
6155 track->mRetryCount = kMaxTrackRetriesOffload;
6156 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006157 track->flushAck();
6158 if (last) {
6159 mFlushPending = true;
6160 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006161 } else if (track->isResumePending()){
6162 track->resumeAck();
6163 if (last) {
6164 if (mPausedBytesRemaining) {
6165 // Need to continue write that was interrupted
6166 mCurrentWriteLength = mPausedWriteLength;
6167 mBytesRemaining = mPausedBytesRemaining;
6168 mPausedBytesRemaining = 0;
6169 }
6170 if (mHwPaused) {
6171 doHwResume = true;
6172 mHwPaused = false;
6173 // threadLoop_mix() will handle the case that we need to
6174 // resume an interrupted write
6175 }
6176 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006177 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006178
Eric Laurent3df841a2016-07-15 15:15:40 -07006179 mLeftVolFloat = mRightVolFloat = -1.0;
6180
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006181 // Do not handle new data in this iteration even if track->framesReady()
6182 mixerStatus = MIXER_TRACKS_ENABLED;
6183 }
6184 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006185 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006186 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006187 if (track->mFillingUpStatus == Track::FS_FILLED) {
6188 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006189 if (last) {
6190 // make sure processVolume_l() will apply new volume even if 0
6191 mLeftVolFloat = mRightVolFloat = -1.0;
6192 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006193 }
6194
6195 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006196 sp<Track> previousTrack = mPreviousTrack.promote();
6197 if (previousTrack != 0) {
6198 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006199 // Flush any data still being written from last track
6200 mBytesRemaining = 0;
6201 if (mPausedBytesRemaining) {
6202 // Last track was paused so we also need to flush saved
6203 // mixbuffer state and invalidate track so that it will
6204 // re-submit that unwritten data when it is next resumed
6205 mPausedBytesRemaining = 0;
6206 // Invalidate is a bit drastic - would be more efficient
6207 // to have a flag to tell client that some of the
6208 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006209 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006210 }
6211 // flush data already sent to the DSP if changing audio session as audio
6212 // comes from a different source. Also invalidate previous track to force a
6213 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006214 if (previousTrack->sessionId() != track->sessionId()) {
6215 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006216 }
6217 }
6218 }
6219 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006220 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006221 if (track->isStopping_1()) {
6222 track->mRetryCount = kMaxTrackStopRetriesOffload;
6223 } else {
6224 track->mRetryCount = kMaxTrackRetriesOffload;
6225 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006226 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006227 mixerStatus = MIXER_TRACKS_READY;
6228 }
6229 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006230 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006231 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006232 if (--(track->mRetryCount) <= 0) {
6233 // Hardware buffer can hold a large amount of audio so we must
6234 // wait for all current track's data to drain before we say
6235 // that the track is stopped.
6236 if (mBytesRemaining == 0) {
6237 // Only start draining when all data in mixbuffer
6238 // has been written
6239 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6240 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6241 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6242 if (last && !mStandby) {
6243 // do not modify drain sequence if we are already draining. This happens
6244 // when resuming from pause after drain.
6245 if ((mDrainSequence & 1) == 0) {
6246 mSleepTimeUs = 0;
6247 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6248 mixerStatus = MIXER_DRAIN_TRACK;
6249 mDrainSequence += 2;
6250 }
6251 if (mHwPaused) {
6252 // It is possible to move from PAUSED to STOPPING_1 without
6253 // a resume so we must ensure hardware is running
6254 doHwResume = true;
6255 mHwPaused = false;
6256 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006257 }
6258 }
Eric Laurente93cc032016-05-05 10:15:10 -07006259 } else if (last) {
6260 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6261 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006262 }
6263 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006264 // Drain has completed or we are in standby, signal presentation complete
6265 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006266 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006267 uint32_t latency = 0;
6268 status_t result = mOutput->stream->getLatency(&latency);
6269 ALOGE_IF(result != OK,
6270 "Error when retrieving output stream latency: %d", result);
6271 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006272 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006273 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006274 track->presentationComplete(framesWritten, audioHALFrames);
6275 track->reset();
6276 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006277 // DIRECT and OFFLOADED stop resets frame counts.
6278 if (!mUseAsyncWrite) {
6279 // If we don't get explicit drain notification we must
6280 // register discontinuity regardless of whether this is
6281 // the previous (!last) or the upcoming (last) track
6282 // to avoid skipping the discontinuity.
6283 mTimestampVerifier.discontinuity();
6284 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006285 }
6286 } else {
6287 // No buffers for this track. Give it a few chances to
6288 // fill a buffer, then remove it from active list.
6289 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006290 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006291 uint64_t position = 0;
6292 struct timespec unused;
6293 // The running check restarts the retry counter at least once.
6294 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6295 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6296 running = true;
6297 mOffloadUnderrunPosition = position;
6298 }
6299 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006300 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6301 (long long)position, (long long)mOffloadUnderrunPosition);
6302 }
6303 if (running) { // still running, give us more time.
6304 track->mRetryCount = kMaxTrackRetriesOffload;
6305 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006306 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6307 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006308 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006309 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006310 // it will then automatically call start() when data is available
6311 track->disable();
6312 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006313 } else if (last){
6314 mixerStatus = MIXER_TRACKS_ENABLED;
6315 }
6316 }
6317 }
6318 // compute volume for this track
6319 processVolume_l(track, last);
6320 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006321
Eric Laurentea0fade2013-10-04 16:23:48 -07006322 // make sure the pause/flush/resume sequence is executed in the right order.
6323 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6324 // before flush and then resume HW. This can happen in case of pause/flush/resume
6325 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006326 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006327 status_t result = mOutput->stream->pause();
6328 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006329 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006330 if (mFlushPending) {
6331 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006332 }
Eric Laurentfd477972013-10-25 18:10:40 -07006333 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006334 status_t result = mOutput->stream->resume();
6335 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006336 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006337
Eric Laurentbfb1b832013-01-07 09:53:42 -08006338 // remove all the tracks that need to be...
6339 removeTracks_l(*tracksToRemove);
6340
6341 return mixerStatus;
6342}
6343
Eric Laurentbfb1b832013-01-07 09:53:42 -08006344// must be called with thread mutex locked
6345bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6346{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006347 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6348 mWriteAckSequence, mDrainSequence);
6349 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006350 return true;
6351 }
6352 return false;
6353}
6354
Eric Laurentbfb1b832013-01-07 09:53:42 -08006355bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6356{
6357 Mutex::Autolock _l(mLock);
6358 return waitingAsyncCallback_l();
6359}
6360
6361void AudioFlinger::OffloadThread::flushHw_l()
6362{
Eric Laurente659ef42014-09-29 13:06:46 -07006363 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006364 // Flush anything still waiting in the mixbuffer
6365 mCurrentWriteLength = 0;
6366 mBytesRemaining = 0;
6367 mPausedWriteLength = 0;
6368 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006369 // reset bytes written count to reflect that DSP buffers are empty after flush.
6370 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006371 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006372
Eric Laurentbfb1b832013-01-07 09:53:42 -08006373 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006374 // discard any pending drain or write ack by incrementing sequence
6375 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6376 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006377 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006378 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6379 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006380 }
6381}
6382
Haynes Mathew George05317d22016-05-03 16:34:26 -07006383void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6384{
6385 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006386 if (PlaybackThread::invalidateTracks_l(streamType)) {
6387 mFlushPending = true;
6388 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006389}
6390
Eric Laurentbfb1b832013-01-07 09:53:42 -08006391// ----------------------------------------------------------------------------
6392
Eric Laurent81784c32012-11-19 14:55:58 -08006393AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006394 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006395 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006396 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006397 mWaitTimeMs(UINT_MAX)
6398{
6399 addOutputTrack(mainThread);
6400}
6401
6402AudioFlinger::DuplicatingThread::~DuplicatingThread()
6403{
6404 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6405 mOutputTracks[i]->destroy();
6406 }
6407}
6408
6409void AudioFlinger::DuplicatingThread::threadLoop_mix()
6410{
6411 // mix buffers...
6412 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006413 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006414 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006415 if (mMixerBufferValid) {
6416 memset(mMixerBuffer, 0, mMixerBufferSize);
6417 } else {
6418 memset(mSinkBuffer, 0, mSinkBufferSize);
6419 }
Eric Laurent81784c32012-11-19 14:55:58 -08006420 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006421 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006422 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006423 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006424 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006425}
6426
6427void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6428{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006429 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006430 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006431 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006432 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006433 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006434 }
6435 } else if (mBytesWritten != 0) {
6436 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6437 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006438 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006439 } else {
6440 // flush remaining overflow buffers in output tracks
6441 writeFrames = 0;
6442 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006443 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006444 }
6445}
6446
Eric Laurentbfb1b832013-01-07 09:53:42 -08006447ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006448{
6449 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006450 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6451
6452 // Consider the first OutputTrack for timestamp and frame counting.
6453
6454 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6455 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6456 // we always claim success.
6457 if (i == 0) {
6458 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6459 ALOGD_IF(correction != 0 && writeFrames != 0,
6460 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6461 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6462 mFramesWritten -= correction;
6463 }
6464
6465 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006466 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006467 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006468 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006469}
6470
6471void AudioFlinger::DuplicatingThread::threadLoop_standby()
6472{
6473 // DuplicatingThread implements standby by stopping all tracks
6474 for (size_t i = 0; i < outputTracks.size(); i++) {
6475 outputTracks[i]->stop();
6476 }
6477}
6478
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006479void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006480{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006481 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006482
6483 std::stringstream ss;
6484 const size_t numTracks = mOutputTracks.size();
6485 ss << " " << numTracks << " OutputTracks";
6486 if (numTracks > 0) {
6487 ss << ":";
6488 for (const auto &track : mOutputTracks) {
6489 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006490 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006491 if (thread.get() != nullptr) {
6492 ss << thread.get() << ", " << thread->id();
6493 } else {
6494 ss << "null";
6495 }
6496 ss << ")";
6497 }
6498 }
6499 ss << "\n";
6500 std::string result = ss.str();
6501 write(fd, result.c_str(), result.size());
6502}
6503
Eric Laurent81784c32012-11-19 14:55:58 -08006504void AudioFlinger::DuplicatingThread::saveOutputTracks()
6505{
6506 outputTracks = mOutputTracks;
6507}
6508
6509void AudioFlinger::DuplicatingThread::clearOutputTracks()
6510{
6511 outputTracks.clear();
6512}
6513
6514void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6515{
6516 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006517 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6518 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6519 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6520 const size_t frameCount =
6521 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6522 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6523 // from different OutputTracks and their associated MixerThreads (e.g. one may
6524 // nearly empty and the other may be dropping data).
6525
6526 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006527 this,
6528 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006529 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006530 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006531 frameCount,
6532 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006533 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6534 if (status != NO_ERROR) {
6535 ALOGE("addOutputTrack() initCheck failed %d", status);
6536 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006537 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006538 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6539 mOutputTracks.add(outputTrack);
6540 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6541 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006542}
6543
6544void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6545{
6546 Mutex::Autolock _l(mLock);
6547 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6548 if (mOutputTracks[i]->thread() == thread) {
6549 mOutputTracks[i]->destroy();
6550 mOutputTracks.removeAt(i);
6551 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006552 if (thread->getOutput() == mOutput) {
6553 mOutput = NULL;
6554 }
Eric Laurent81784c32012-11-19 14:55:58 -08006555 return;
6556 }
6557 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006558 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006559}
6560
6561// caller must hold mLock
6562void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6563{
6564 mWaitTimeMs = UINT_MAX;
6565 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6566 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6567 if (strong != 0) {
6568 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6569 if (waitTimeMs < mWaitTimeMs) {
6570 mWaitTimeMs = waitTimeMs;
6571 }
6572 }
6573 }
6574}
6575
6576
6577bool AudioFlinger::DuplicatingThread::outputsReady(
6578 const SortedVector< sp<OutputTrack> > &outputTracks)
6579{
6580 for (size_t i = 0; i < outputTracks.size(); i++) {
6581 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6582 if (thread == 0) {
6583 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6584 outputTracks[i].get());
6585 return false;
6586 }
6587 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6588 // see note at standby() declaration
6589 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6590 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6591 thread.get());
6592 return false;
6593 }
6594 }
6595 return true;
6596}
6597
Kevin Rocard12381092018-04-11 09:19:59 -07006598void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6599 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006600{
Kevin Rocard12381092018-04-11 09:19:59 -07006601 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6602 outputTrack->setMetadatas(metadata.tracks);
6603 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006604}
6605
Eric Laurent81784c32012-11-19 14:55:58 -08006606uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6607{
6608 return (mWaitTimeMs * 1000) / 2;
6609}
6610
6611void AudioFlinger::DuplicatingThread::cacheParameters_l()
6612{
6613 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6614 updateWaitTime_l();
6615
6616 MixerThread::cacheParameters_l();
6617}
6618
Eric Laurent6acd1d42017-01-04 14:23:29 -08006619
Eric Laurent81784c32012-11-19 14:55:58 -08006620// ----------------------------------------------------------------------------
6621// Record
6622// ----------------------------------------------------------------------------
6623
6624AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6625 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006626 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006627 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006628 audio_devices_t inDevice,
6629 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006630 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006631 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006632 mInput(input),
6633 mActiveTracks(&this->mLocalLog),
6634 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006635 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006636 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006637 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6638 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006639 // mFastCapture below
6640 , mFastCaptureFutex(0)
6641 // mInputSource
6642 // mPipeSink
6643 // mPipeSource
6644 , mPipeFramesP2(0)
6645 // mPipeMemory
6646 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006647 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006648 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006649{
Glenn Kastend7dca052015-03-05 16:05:54 -08006650 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6651 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006652
Andy Hungc8fddf32018-08-08 18:32:37 -07006653 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6654 mIsMsdDevice = strcmp(
6655 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6656 }
6657
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006658 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006659
Andy Hungc8fddf32018-08-08 18:32:37 -07006660 // TODO: We may also match on address as well as device type for
6661 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
6662 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
6663 "audio.timestamp.corrected_input_devices",
6664 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6665 : AUDIO_DEVICE_NONE));
6666
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006667 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006668 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006669 size_t numCounterOffers = 0;
6670 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006671#if !LOG_NDEBUG
6672 ssize_t index =
6673#else
6674 (void)
6675#endif
6676 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006677 ALOG_ASSERT(index == 0);
6678
6679 // initialize fast capture depending on configuration
6680 bool initFastCapture;
6681 switch (kUseFastCapture) {
6682 case FastCapture_Never:
6683 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006684 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006685 break;
6686 case FastCapture_Always:
6687 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006688 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006689 break;
6690 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006691 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006692 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6693 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6694 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006695 break;
6696 // case FastCapture_Dynamic:
6697 }
6698
6699 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006700 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006701 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006702 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6703 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006704 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006705 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006706 const sp<MemoryDealer> roHeap(readOnlyHeap());
6707 sp<IMemory> pipeMemory;
6708 if ((roHeap == 0) ||
6709 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006710 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6711 ALOGE("not enough memory for pipe buffer size=%zu; "
6712 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6713 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6714 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006715 goto failed;
6716 }
6717 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6718 memset(pipeBuffer, 0, pipeSize);
6719 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6720 const NBAIO_Format offers[1] = {format};
6721 size_t numCounterOffers = 0;
6722 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6723 ALOG_ASSERT(index == 0);
6724 mPipeSink = pipe;
6725 PipeReader *pipeReader = new PipeReader(*pipe);
6726 numCounterOffers = 0;
6727 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6728 ALOG_ASSERT(index == 0);
6729 mPipeSource = pipeReader;
6730 mPipeFramesP2 = pipeFramesP2;
6731 mPipeMemory = pipeMemory;
6732
6733 // create fast capture
6734 mFastCapture = new FastCapture();
6735 FastCaptureStateQueue *sq = mFastCapture->sq();
6736#ifdef STATE_QUEUE_DUMP
6737 // FIXME
6738#endif
6739 FastCaptureState *state = sq->begin();
6740 state->mCblk = NULL;
6741 state->mInputSource = mInputSource.get();
6742 state->mInputSourceGen++;
6743 state->mPipeSink = pipe;
6744 state->mPipeSinkGen++;
6745 state->mFrameCount = mFrameCount;
6746 state->mCommand = FastCaptureState::COLD_IDLE;
6747 // already done in constructor initialization list
6748 //mFastCaptureFutex = 0;
6749 state->mColdFutexAddr = &mFastCaptureFutex;
6750 state->mColdGen++;
6751 state->mDumpState = &mFastCaptureDumpState;
6752#ifdef TEE_SINK
6753 // FIXME
6754#endif
6755 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6756 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6757 sq->end();
6758 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6759
6760 // start the fast capture
6761 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6762 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006763 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006764 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006765#ifdef AUDIO_WATCHDOG
6766 // FIXME
6767#endif
6768
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006769 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006770 }
Andy Hung8946a282018-04-19 20:04:56 -07006771#ifdef TEE_SINK
6772 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6773 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6774#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006775failed: ;
6776
6777 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006778}
6779
Eric Laurent81784c32012-11-19 14:55:58 -08006780AudioFlinger::RecordThread::~RecordThread()
6781{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006782 if (mFastCapture != 0) {
6783 FastCaptureStateQueue *sq = mFastCapture->sq();
6784 FastCaptureState *state = sq->begin();
6785 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6786 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6787 if (old == -1) {
6788 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6789 }
6790 }
6791 state->mCommand = FastCaptureState::EXIT;
6792 sq->end();
6793 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6794 mFastCapture->join();
6795 mFastCapture.clear();
6796 }
6797 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006798 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006799 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006800}
6801
6802void AudioFlinger::RecordThread::onFirstRef()
6803{
Glenn Kastend7dca052015-03-05 16:05:54 -08006804 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006805}
6806
Eric Laurent555530a2017-02-07 18:17:24 -08006807void AudioFlinger::RecordThread::preExit()
6808{
6809 ALOGV(" preExit()");
6810 Mutex::Autolock _l(mLock);
6811 for (size_t i = 0; i < mTracks.size(); i++) {
6812 sp<RecordTrack> track = mTracks[i];
6813 track->invalidate();
6814 }
6815 mActiveTracks.clear();
6816 mStartStopCond.broadcast();
6817}
6818
Eric Laurent81784c32012-11-19 14:55:58 -08006819bool AudioFlinger::RecordThread::threadLoop()
6820{
Eric Laurent81784c32012-11-19 14:55:58 -08006821 nsecs_t lastWarning = 0;
6822
6823 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006824
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006825reacquire_wakelock:
6826 sp<RecordTrack> activeTrack;
6827 {
6828 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006829 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006830 }
6831
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006832 // used to request a deferred sleep, to be executed later while mutex is unlocked
6833 uint32_t sleepUs = 0;
6834
Andy Hung446f4df2019-02-21 12:26:41 -08006835 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
6836
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006837 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08006838 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006839 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006840
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006841 // activeTracks accumulates a copy of a subset of mActiveTracks
6842 Vector< sp<RecordTrack> > activeTracks;
6843
Glenn Kasten735f45f2014-08-18 15:51:59 -07006844 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006845 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006846
Glenn Kasten735f45f2014-08-18 15:51:59 -07006847 // reference to a fast track which is about to be removed
6848 sp<RecordTrack> fastTrackToRemove;
6849
Eric Laurent81784c32012-11-19 14:55:58 -08006850 { // scope for mLock
6851 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006852
Eric Laurent021cf962014-05-13 10:18:14 -07006853 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006854
Eric Laurent000a4192014-01-29 15:17:32 -08006855 // check exitPending here because checkForNewParameters_l() and
6856 // checkForNewParameters_l() can temporarily release mLock
6857 if (exitPending()) {
6858 break;
6859 }
6860
Eric Laurent5c25d562016-07-13 17:17:45 -07006861 // sleep with mutex unlocked
6862 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006863 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006864 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6865 ATRACE_END();
6866 sleepUs = 0;
6867 continue;
6868 }
6869
Glenn Kasten2b806402013-11-20 16:37:38 -08006870 // if no active track(s), then standby and release wakelock
6871 size_t size = mActiveTracks.size();
6872 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006873 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006874 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006875 releaseWakeLock_l();
6876 ALOGV("RecordThread: loop stopping");
6877 // go to sleep
6878 mWaitWorkCV.wait(mLock);
6879 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006880 goto reacquire_wakelock;
6881 }
6882
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006883 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006884 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006885 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006886
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006887 activeTrack = mActiveTracks[i];
6888 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006889 if (activeTrack->isFastTrack()) {
6890 ALOG_ASSERT(fastTrackToRemove == 0);
6891 fastTrackToRemove = activeTrack;
6892 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006893 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006894 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006895 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006896 continue;
6897 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006898
6899 TrackBase::track_state activeTrackState = activeTrack->mState;
6900 switch (activeTrackState) {
6901
6902 case TrackBase::PAUSING:
6903 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006904 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006905 doBroadcast = true;
6906 size--;
6907 continue;
6908
6909 case TrackBase::STARTING_1:
6910 sleepUs = 10000;
6911 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006912 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006913 continue;
6914
6915 case TrackBase::STARTING_2:
6916 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006917 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006918 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006919 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006920 break;
6921
6922 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006923 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006924 break;
6925
Andy Hungce685402018-10-05 17:23:27 -07006926 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6927 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6928 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006929 default:
Andy Hungce685402018-10-05 17:23:27 -07006930 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6931 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006932 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006933
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006934 activeTracks.add(activeTrack);
6935 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006936
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006937 if (activeTrack->isFastTrack()) {
6938 ALOG_ASSERT(!mFastTrackAvail);
6939 ALOG_ASSERT(fastTrack == 0);
6940 fastTrack = activeTrack;
6941 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006942 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006943
Andy Hungdae27702016-10-31 14:01:16 -07006944 mActiveTracks.updatePowerState(this);
6945
Kevin Rocard069c2712018-03-29 19:09:14 -07006946 updateMetadata_l();
6947
Eric Laurent5c25d562016-07-13 17:17:45 -07006948 if (allStopped) {
6949 standbyIfNotAlreadyInStandby();
6950 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006951 if (doBroadcast) {
6952 mStartStopCond.broadcast();
6953 }
6954
6955 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006956 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006957 if (sleepUs == 0) {
6958 sleepUs = kRecordThreadSleepUs;
6959 }
6960 continue;
6961 }
6962 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006963
Eric Laurent81784c32012-11-19 14:55:58 -08006964 lockEffectChains_l(effectChains);
6965 }
6966
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006967 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006968
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006969 size_t size = effectChains.size();
6970 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006971 // thread mutex is not locked, but effect chain is locked
6972 effectChains[i]->process_l();
6973 }
6974
Glenn Kasten735f45f2014-08-18 15:51:59 -07006975 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006976 if (mFastCapture != 0) {
6977 FastCaptureStateQueue *sq = mFastCapture->sq();
6978 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006979 bool didModify = false;
6980 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006981 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6982 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6983 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6984 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6985 if (old == -1) {
6986 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6987 }
6988 }
6989 state->mCommand = FastCaptureState::READ_WRITE;
6990#if 0 // FIXME
6991 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006992 FastThreadDumpState::kSamplingNforLowRamDevice :
6993 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006994#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006995 didModify = true;
6996 }
6997 audio_track_cblk_t *cblkOld = state->mCblk;
6998 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6999 if (cblkNew != cblkOld) {
7000 state->mCblk = cblkNew;
7001 // block until acked if removing a fast track
7002 if (cblkOld != NULL) {
7003 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7004 }
7005 didModify = true;
7006 }
jiabin01c8f562018-07-19 17:47:28 -07007007 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7008 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7009 if (state->mFastPatchRecordBufferProvider != abp) {
7010 state->mFastPatchRecordBufferProvider = abp;
7011 state->mFastPatchRecordFormat = fastTrack == 0 ?
7012 AUDIO_FORMAT_INVALID : fastTrack->format();
7013 didModify = true;
7014 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007015 sq->end(didModify);
7016 if (didModify) {
7017 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007018#if 0
7019 if (kUseFastCapture == FastCapture_Dynamic) {
7020 mNormalSource = mPipeSource;
7021 }
7022#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007023 }
7024 }
7025
Glenn Kasten735f45f2014-08-18 15:51:59 -07007026 // now run the fast track destructor with thread mutex unlocked
7027 fastTrackToRemove.clear();
7028
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007029 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7030 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7031 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7032 // If destination is non-contiguous, first read past the nominal end of buffer, then
7033 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007034
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007035 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007036 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007037 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007038
7039 // If an NBAIO source is present, use it to read the normal capture's data
7040 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007041 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007042
7043 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7044 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7045 // we immediately retry the read() to get data and prevent another overflow.
7046 for (int retries = 0; retries <= 2; ++retries) {
7047 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7048 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7049 framesToRead);
7050 if (framesRead != OVERRUN) break;
7051 }
7052
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007053 const ssize_t availableToRead = mPipeSource->availableToRead();
7054 if (availableToRead >= 0) {
7055 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
7056 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7057 "more frames to read than fifo size, %zd > %zu",
7058 availableToRead, mPipeFramesP2);
7059 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7060 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7061 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7062 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007063 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7064 }
7065 if (framesRead < 0) {
7066 status_t status = (status_t) framesRead;
7067 switch (status) {
7068 case OVERRUN:
7069 ALOGW("overrun on read from pipe");
7070 framesRead = 0;
7071 break;
7072 case NEGOTIATE:
7073 ALOGE("re-negotiation is needed");
7074 framesRead = -1; // Will cause an attempt to recover.
7075 break;
7076 default:
7077 ALOGE("unknown error %d on read from pipe", status);
7078 break;
7079 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007080 }
7081 // otherwise use the HAL / AudioStreamIn directly
7082 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007083 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007084 size_t bytesRead;
7085 status_t result = mInput->stream->read(
7086 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007087 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007088 if (result < 0) {
7089 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007090 } else {
7091 framesRead = bytesRead / mFrameSize;
7092 }
7093 }
7094
Andy Hung446f4df2019-02-21 12:26:41 -08007095 const int64_t lastIoEndNs = systemTime(); // end IO timing
7096
Andy Hung3f0c9022016-01-15 17:49:46 -08007097 // Update server timestamp with server stats
7098 // systemTime() is optional if the hardware supports timestamps.
7099 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007100 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
Andy Hung3f0c9022016-01-15 17:49:46 -08007101
7102 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007103 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007104 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007105 if (mStandby) {
7106 mTimestampVerifier.discontinuity();
Andy Hungc8fddf32018-08-08 18:32:37 -07007107 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR
7108 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7109
7110 mTimestampVerifier.add(position, time, mSampleRate);
7111
7112 // Correct timestamps
7113 if (isTimestampCorrectionEnabled()) {
7114 ALOGV("TS_BEFORE: %d %lld %lld",
7115 id(), (long long)time, (long long)position);
7116 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7117 position = correctedTimestamp.mFrames;
7118 time = correctedTimestamp.mTimeNs;
7119 ALOGV("TS_AFTER: %d %lld %lld",
7120 id(), (long long)time, (long long)position);
7121 }
7122
Andy Hung3f0c9022016-01-15 17:49:46 -08007123 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7124 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7125 // Note: In general record buffers should tend to be empty in
7126 // a properly running pipeline.
7127 //
7128 // Also, it is not advantageous to call get_presentation_position during the read
7129 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007130 } else {
7131 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007132 }
7133 }
Andy Hunge6c37112019-02-26 17:38:10 -08007134
7135 // From the timestamp, input read latency is negative output write latency.
7136 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7137 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7138 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7139 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7140 mLatencyMs.add(latencyMs);
7141 }
7142
Andy Hung3f0c9022016-01-15 17:49:46 -08007143 // Use this to track timestamp information
7144 // ALOGD("%s", mTimestamp.toString().c_str());
7145
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007146 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007147 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007148 // Force input into standby so that it tries to recover at next read attempt
7149 inputStandBy();
7150 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007151 }
7152 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007153 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007154 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007155 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007156 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007157
Andy Hung8946a282018-04-19 20:04:56 -07007158#ifdef TEE_SINK
7159 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7160#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007161 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007162 {
7163 size_t part1 = mRsmpInFramesP2 - rear;
7164 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007165 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007166 (framesRead - part1) * mFrameSize);
7167 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007168 }
7169 rear = mRsmpInRear += framesRead;
7170
7171 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007172
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007173 // loop over each active track
7174 for (size_t i = 0; i < size; i++) {
7175 activeTrack = activeTracks[i];
7176
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007177 // skip fast tracks, as those are handled directly by FastCapture
7178 if (activeTrack->isFastTrack()) {
7179 continue;
7180 }
7181
Andy Hung73c02e42015-03-29 01:13:58 -07007182 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007183 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7184
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007185 enum {
7186 OVERRUN_UNKNOWN,
7187 OVERRUN_TRUE,
7188 OVERRUN_FALSE
7189 } overrun = OVERRUN_UNKNOWN;
7190
7191 // loop over getNextBuffer to handle circular sink
7192 for (;;) {
7193
7194 activeTrack->mSink.frameCount = ~0;
7195 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7196 size_t framesOut = activeTrack->mSink.frameCount;
7197 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7198
Andy Hung73c02e42015-03-29 01:13:58 -07007199 // check available frames and handle overrun conditions
7200 // if the record track isn't draining fast enough.
7201 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007202 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007203 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7204 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007205 overrun = OVERRUN_TRUE;
7206 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007207 if (framesOut == 0 || framesIn == 0) {
7208 break;
7209 }
7210
Andy Hung6770c6f2015-04-07 13:43:36 -07007211 // Don't allow framesOut to be larger than what is possible with resampling
7212 // from framesIn.
7213 // This isn't strictly necessary but helps limit buffer resizing in
7214 // RecordBufferConverter. TODO: remove when no longer needed.
7215 framesOut = min(framesOut,
7216 destinationFramesPossible(
7217 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007218
7219 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007220 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007221 // straight from RecordThread buffer to RecordTrack buffer.
7222 AudioBufferProvider::Buffer buffer;
7223 buffer.frameCount = framesOut;
7224 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7225 if (status == OK && buffer.frameCount != 0) {
7226 ALOGV_IF(buffer.frameCount != framesOut,
7227 "%s() read less than expected (%zu vs %zu)",
7228 __func__, buffer.frameCount, framesOut);
7229 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007230 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007231 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7232 } else {
7233 framesOut = 0;
7234 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7235 __func__, status, buffer.frameCount);
7236 }
7237 } else {
7238 // process frames from the RecordThread buffer provider to the RecordTrack
7239 // buffer
7240 framesOut = activeTrack->mRecordBufferConverter->convert(
7241 activeTrack->mSink.raw,
7242 activeTrack->mResamplerBufferProvider,
7243 framesOut);
7244 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007245
7246 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7247 overrun = OVERRUN_FALSE;
7248 }
7249
7250 if (activeTrack->mFramesToDrop == 0) {
7251 if (framesOut > 0) {
7252 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007253 // Sanitize before releasing if the track has no access to the source data
7254 // An idle UID receives silence from non virtual devices until active
7255 if (activeTrack->isSilenced()) {
7256 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
7257 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007258 activeTrack->releaseBuffer(&activeTrack->mSink);
7259 }
7260 } else {
7261 // FIXME could do a partial drop of framesOut
7262 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007263 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007264 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007265 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007266 }
7267 } else {
7268 activeTrack->mFramesToDrop += framesOut;
7269 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7270 activeTrack->mSyncStartEvent->isCancelled()) {
7271 ALOGW("Synced record %s, session %d, trigger session %d",
7272 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7273 activeTrack->sessionId(),
7274 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007275 activeTrack->mSyncStartEvent->triggerSession() :
7276 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007277 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007278 }
7279 }
7280 }
7281
7282 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007283 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007284 }
7285 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007286
7287 switch (overrun) {
7288 case OVERRUN_TRUE:
7289 // client isn't retrieving buffers fast enough
7290 if (!activeTrack->setOverflow()) {
7291 nsecs_t now = systemTime();
7292 // FIXME should lastWarning per track?
7293 if ((now - lastWarning) > kWarningThrottleNs) {
7294 ALOGW("RecordThread: buffer overflow");
7295 lastWarning = now;
7296 }
7297 }
7298 break;
7299 case OVERRUN_FALSE:
7300 activeTrack->clearOverflow();
7301 break;
7302 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007303 break;
7304 }
7305
Andy Hung3f0c9022016-01-15 17:49:46 -08007306 // update frame information and push timestamp out
7307 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007308 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007309 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7310 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007311 }
7312
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007313unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007314 // enable changes in effect chain
7315 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007316 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007317 if (audio_has_proportional_frames(mFormat)
7318 && loopCount == lastLoopCountRead + 1) {
7319 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7320 const double jitterMs =
7321 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7322 {framesRead, readPeriodNs},
7323 {0, 0} /* lastTimestamp */, mSampleRate);
7324 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7325
7326 Mutex::Autolock _l(mLock);
7327 mIoJitterMs.add(jitterMs);
7328 mProcessTimeMs.add(processMs);
7329 }
7330 // update timing info.
7331 mLastIoBeginNs = lastIoBeginNs;
7332 mLastIoEndNs = lastIoEndNs;
7333 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007334 }
7335
Glenn Kasten93e471f2013-08-19 08:40:07 -07007336 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007337
7338 {
7339 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007340 for (size_t i = 0; i < mTracks.size(); i++) {
7341 sp<RecordTrack> track = mTracks[i];
7342 track->invalidate();
7343 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007344 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007345 mStartStopCond.broadcast();
7346 }
7347
7348 releaseWakeLock();
7349
7350 ALOGV("RecordThread %p exiting", this);
7351 return false;
7352}
7353
Glenn Kasten93e471f2013-08-19 08:40:07 -07007354void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007355{
7356 if (!mStandby) {
7357 inputStandBy();
7358 mStandby = true;
7359 }
7360}
7361
7362void AudioFlinger::RecordThread::inputStandBy()
7363{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007364 // Idle the fast capture if it's currently running
7365 if (mFastCapture != 0) {
7366 FastCaptureStateQueue *sq = mFastCapture->sq();
7367 FastCaptureState *state = sq->begin();
7368 if (!(state->mCommand & FastCaptureState::IDLE)) {
7369 state->mCommand = FastCaptureState::COLD_IDLE;
7370 state->mColdFutexAddr = &mFastCaptureFutex;
7371 state->mColdGen++;
7372 mFastCaptureFutex = 0;
7373 sq->end();
7374 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7375 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7376#if 0
7377 if (kUseFastCapture == FastCapture_Dynamic) {
7378 // FIXME
7379 }
7380#endif
7381#ifdef AUDIO_WATCHDOG
7382 // FIXME
7383#endif
7384 } else {
7385 sq->end(false /*didModify*/);
7386 }
7387 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007388 status_t result = mInput->stream->standby();
7389 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007390
7391 // If going into standby, flush the pipe source.
7392 if (mPipeSource.get() != nullptr) {
7393 const ssize_t flushed = mPipeSource->flush();
7394 if (flushed > 0) {
7395 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7396 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7397 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7398 }
7399 }
Eric Laurent81784c32012-11-19 14:55:58 -08007400}
7401
Glenn Kasten05997e22014-03-13 15:08:33 -07007402// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007403sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007404 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007405 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007406 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007407 audio_format_t format,
7408 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007409 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007410 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007411 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007412 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007413 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007414 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007415 status_t *status,
7416 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007417{
Glenn Kasten74935e42013-12-19 08:56:45 -08007418 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007419 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007420 sp<RecordTrack> track;
7421 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007422 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007423 audio_input_flags_t requestedFlags = *flags;
7424 uint32_t sampleRate;
7425
7426 lStatus = initCheck();
7427 if (lStatus != NO_ERROR) {
7428 ALOGE("createRecordTrack_l() audio driver not initialized");
7429 goto Exit;
7430 }
7431
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007432 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7433 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7434 lStatus = BAD_VALUE;
7435 goto Exit;
7436 }
7437
Eric Laurentf14db3c2017-12-08 14:20:36 -08007438 if (*pSampleRate == 0) {
7439 *pSampleRate = mSampleRate;
7440 }
7441 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007442
7443 // special case for FAST flag considered OK if fast capture is present
7444 if (hasFastCapture()) {
7445 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7446 }
7447
Eric Laurentf14db3c2017-12-08 14:20:36 -08007448 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007449 if ((*flags & inputFlags) != *flags) {
7450 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7451 " input flags (%08x)",
7452 *flags, inputFlags);
7453 *flags = (audio_input_flags_t)(*flags & inputFlags);
7454 }
Eric Laurent81784c32012-11-19 14:55:58 -08007455
Glenn Kasten90e58b12013-07-31 16:16:02 -07007456 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007457 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007458 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007459 // we formerly checked for a callback handler (non-0 tid),
7460 // but that is no longer required for TRANSFER_OBTAIN mode
7461 //
Glenn Kasten74105912014-07-03 12:28:53 -07007462 // frame count is not specified, or is exactly the pipe depth
7463 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007464 // PCM data
7465 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007466 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007467 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007468 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007469 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007470 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007471 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007472 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007473 hasFastCapture() &&
7474 // there are sufficient fast track slots available
7475 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007476 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007477 // check compatibility with audio effects.
7478 Mutex::Autolock _l(mLock);
7479 // Do not accept FAST flag if the session has software effects
7480 sp<EffectChain> chain = getEffectChain_l(sessionId);
7481 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007482 audio_input_flags_t old = *flags;
7483 chain->checkInputFlagCompatibility(flags);
7484 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007485 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7486 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007487 }
7488 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007489 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007490 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7491 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007492 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007493 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7494 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007495 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007496 this, frameCount, mFrameCount, mPipeFramesP2,
7497 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007498 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007499 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007500 }
7501 }
7502
Eric Laurentf14db3c2017-12-08 14:20:36 -08007503 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7504 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7505 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7506 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7507 lStatus = BAD_TYPE;
7508 goto Exit;
7509 }
7510
Glenn Kasten74105912014-07-03 12:28:53 -07007511 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007512 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007513 // fast track: frame count is exactly the pipe depth
7514 frameCount = mPipeFramesP2;
7515 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007516 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007517 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007518 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7519 // or 20 ms if there is a fast capture
7520 // TODO This could be a roundupRatio inline, and const
7521 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7522 * sampleRate + mSampleRate - 1) / mSampleRate;
7523 // minimum number of notification periods is at least kMinNotifications,
7524 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7525 static const size_t kMinNotifications = 3;
7526 static const uint32_t kMinMs = 30;
7527 // TODO This could be a roundupRatio inline
7528 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7529 // TODO This could be a roundupRatio inline
7530 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7531 maxNotificationFrames;
7532 const size_t minFrameCount = maxNotificationFrames *
7533 max(kMinNotifications, minNotificationsByMs);
7534 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007535 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7536 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007537 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007538 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007539 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007540 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007541
7542 { // scope for mLock
7543 Mutex::Autolock _l(mLock);
7544
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007545 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007546 format, channelMask, frameCount,
7547 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007548 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007549
Glenn Kasten03003332013-08-06 15:40:54 -07007550 lStatus = track->initCheck();
7551 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007552 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007553 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007554 goto Exit;
7555 }
7556 mTracks.add(track);
7557
Eric Laurent05067782016-06-01 18:27:28 -07007558 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007559 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7560 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7561 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007562 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007563 }
Eric Laurent81784c32012-11-19 14:55:58 -08007564 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007565
Eric Laurent81784c32012-11-19 14:55:58 -08007566 lStatus = NO_ERROR;
7567
7568Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007569 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007570 return track;
7571}
7572
7573status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7574 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007575 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007576{
7577 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7578 sp<ThreadBase> strongMe = this;
7579 status_t status = NO_ERROR;
7580
7581 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007582 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007583 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007584 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007585 triggerSession,
7586 recordTrack->sessionId(),
7587 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007588 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007589 // Sync event can be cancelled by the trigger session if the track is not in a
7590 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007591 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007592 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007593 } else {
7594 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007595 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007596 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007597 }
7598 }
7599
7600 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007601 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007602 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007603 if (recordTrack->isInvalid()) {
7604 recordTrack->clearSyncStartEvent();
7605 return INVALID_OPERATION;
7606 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007607 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7608 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007609 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7610 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007611 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007612 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007613 } else {
7614 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007615 }
7616 return status;
7617 }
7618
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007619 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7620 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7621 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007622 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007623 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007624 status_t status = NO_ERROR;
7625 if (recordTrack->isExternalTrack()) {
7626 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007627 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007628 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007629 if (recordTrack->isInvalid()) {
7630 recordTrack->clearSyncStartEvent();
7631 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7632 recordTrack->mState = TrackBase::STARTING_2;
7633 // STARTING_2 forces destroy to call stopInput.
7634 }
7635 return INVALID_OPERATION;
7636 }
7637 if (recordTrack->mState != TrackBase::STARTING_1) {
7638 ALOGW("%s(%d): unsynchronized mState:%d change",
7639 __func__, recordTrack->id(), recordTrack->mState);
7640 // Someone else has changed state, let them take over,
7641 // leave mState in the new state.
7642 recordTrack->clearSyncStartEvent();
7643 return INVALID_OPERATION;
7644 }
7645 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007646 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007647 ALOGW("%s(%d): startInput failed, status %d",
7648 __func__, recordTrack->id(), status);
7649 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7650 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007651 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007652 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007653 return status;
7654 }
Eric Laurent81784c32012-11-19 14:55:58 -08007655 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007656 // Catch up with current buffer indices if thread is already running.
7657 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7658 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7659 // see previously buffered data before it called start(), but with greater risk of overrun.
7660
Andy Hung73c02e42015-03-29 01:13:58 -07007661 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007662 if (!recordTrack->isDirect()) {
7663 // clear any converter state as new data will be discontinuous
7664 recordTrack->mRecordBufferConverter->reset();
7665 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007666 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007667 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007668 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007669 return status;
7670 }
Eric Laurent81784c32012-11-19 14:55:58 -08007671}
7672
Eric Laurent81784c32012-11-19 14:55:58 -08007673void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7674{
7675 sp<SyncEvent> strongEvent = event.promote();
7676
7677 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007678 sp<RefBase> ptr = strongEvent->cookie().promote();
7679 if (ptr != 0) {
7680 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7681 recordTrack->handleSyncStartEvent(strongEvent);
7682 }
Eric Laurent81784c32012-11-19 14:55:58 -08007683 }
7684}
7685
Glenn Kastena8356f62013-07-25 14:37:52 -07007686bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007687 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007688 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007689 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007690 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007691 return false;
7692 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007693 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007694 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007695
Andy Hungabfab202019-03-07 19:45:54 -08007696 // NOTE: Waiting here is important to keep stop synchronous.
7697 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07007698 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7699 mWaitWorkCV.broadcast(); // signal thread to stop
7700 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007701 }
Andy Hungce685402018-10-05 17:23:27 -07007702
7703 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007704 ALOGV("Record stopped OK");
7705 return true;
7706 }
Andy Hungce685402018-10-05 17:23:27 -07007707
7708 // don't handle anything - we've been invalidated or restarted and in a different state
7709 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7710 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007711 return false;
7712}
7713
Glenn Kasten0f11b512014-01-31 16:18:54 -08007714bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007715{
7716 return false;
7717}
7718
Glenn Kasten0f11b512014-01-31 16:18:54 -08007719status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007720{
7721#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7722 if (!isValidSyncEvent(event)) {
7723 return BAD_VALUE;
7724 }
7725
Glenn Kastend848eb42016-03-08 13:42:11 -08007726 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007727 status_t ret = NAME_NOT_FOUND;
7728
7729 Mutex::Autolock _l(mLock);
7730
7731 for (size_t i = 0; i < mTracks.size(); i++) {
7732 sp<RecordTrack> track = mTracks[i];
7733 if (eventSession == track->sessionId()) {
7734 (void) track->setSyncEvent(event);
7735 ret = NO_ERROR;
7736 }
7737 }
7738 return ret;
7739#else
7740 return BAD_VALUE;
7741#endif
7742}
7743
jiabin653cc0a2018-01-17 17:54:10 -08007744status_t AudioFlinger::RecordThread::getActiveMicrophones(
7745 std::vector<media::MicrophoneInfo>* activeMicrophones)
7746{
7747 ALOGV("RecordThread::getActiveMicrophones");
7748 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007749 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7750 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007751}
7752
Paul McLean12340082019-03-19 09:35:05 -06007753status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
7754 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007755{
Paul McLean12340082019-03-19 09:35:05 -06007756 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007757 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007758 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007759}
7760
Paul McLean12340082019-03-19 09:35:05 -06007761status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007762{
Paul McLean12340082019-03-19 09:35:05 -06007763 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007764 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007765 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007766}
7767
Kevin Rocard069c2712018-03-29 19:09:14 -07007768void AudioFlinger::RecordThread::updateMetadata_l()
7769{
7770 if (mInput == nullptr || mInput->stream == nullptr ||
7771 !mActiveTracks.readAndClearHasChanged()) {
7772 return;
7773 }
7774 StreamInHalInterface::SinkMetadata metadata;
7775 for (const sp<RecordTrack> &track : mActiveTracks) {
7776 // No track is invalid as this is called after prepareTrack_l in the same critical section
7777 metadata.tracks.push_back({
7778 .source = track->attributes().source,
7779 .gain = 1, // capture tracks do not have volumes
7780 });
7781 }
7782 mInput->stream->updateSinkMetadata(metadata);
7783}
7784
Eric Laurent81784c32012-11-19 14:55:58 -08007785// destroyTrack_l() must be called with ThreadBase::mLock held
7786void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7787{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007788 track->terminate();
7789 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007790 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007791 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007792 removeTrack_l(track);
7793 }
7794}
7795
7796void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7797{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007798 String8 result;
7799 track->appendDump(result, false /* active */);
7800 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7801
Eric Laurent81784c32012-11-19 14:55:58 -08007802 mTracks.remove(track);
7803 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007804 if (track->isFastTrack()) {
7805 ALOG_ASSERT(!mFastTrackAvail);
7806 mFastTrackAvail = true;
7807 }
Eric Laurent81784c32012-11-19 14:55:58 -08007808}
7809
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007810void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007811{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007812 AudioStreamIn *input = mInput;
7813 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7814 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08007815 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007816 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007817 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007818 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007819 }
Andy Hungbfa64962017-06-12 14:43:19 -07007820
7821 if (input != nullptr) {
7822 dprintf(fd, " Hal stream dump:\n");
7823 (void)input->stream->dump(fd);
7824 }
7825
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007826 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007827 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007828
Glenn Kasten2f90c512015-12-02 11:40:09 -08007829 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7830 // while we are dumping it. It may be inconsistent, but it won't mutate!
7831 // This is a large object so we place it on the heap.
7832 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007833 const std::unique_ptr<FastCaptureDumpState> copy =
7834 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007835 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007836}
7837
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007838void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007839{
Eric Laurent81784c32012-11-19 14:55:58 -08007840 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007841 size_t numtracks = mTracks.size();
7842 size_t numactive = mActiveTracks.size();
7843 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007844 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007845 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007846 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007847 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007848 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007849 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007850 for (size_t i = 0; i < numtracks ; ++i) {
7851 sp<RecordTrack> track = mTracks[i];
7852 if (track != 0) {
7853 bool active = mActiveTracks.indexOf(track) >= 0;
7854 if (active) {
7855 numactiveseen++;
7856 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007857 result.append(prefix);
7858 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007859 }
Eric Laurent81784c32012-11-19 14:55:58 -08007860 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007861 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007862 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007863 }
7864
Marco Nelissenb2208842014-02-07 14:00:50 -08007865 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007866 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007867 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007868 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007869 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007870 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007871 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007872 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007873 result.append(prefix);
7874 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007875 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007876 }
Eric Laurent81784c32012-11-19 14:55:58 -08007877
7878 }
7879 write(fd, result.string(), result.size());
7880}
7881
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007882void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7883{
7884 Mutex::Autolock _l(mLock);
7885 for (size_t i = 0; i < mTracks.size() ; i++) {
7886 sp<RecordTrack> track = mTracks[i];
7887 if (track != 0 && track->uid() == uid) {
7888 track->setSilenced(silenced);
7889 }
7890 }
7891}
Andy Hung73c02e42015-03-29 01:13:58 -07007892
7893void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7894{
7895 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7896 RecordThread *recordThread = (RecordThread *) threadBase.get();
7897 mRsmpInFront = recordThread->mRsmpInRear;
7898 mRsmpInUnrel = 0;
7899}
7900
7901void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7902 size_t *framesAvailable, bool *hasOverrun)
7903{
7904 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7905 RecordThread *recordThread = (RecordThread *) threadBase.get();
7906 const int32_t rear = recordThread->mRsmpInRear;
7907 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07007908 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07007909
7910 size_t framesIn;
7911 bool overrun = false;
7912 if (filled < 0) {
7913 // should not happen, but treat like a massive overrun and re-sync
7914 framesIn = 0;
7915 mRsmpInFront = rear;
7916 overrun = true;
7917 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7918 framesIn = (size_t) filled;
7919 } else {
7920 // client is not keeping up with server, but give it latest data
7921 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07007922 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
7923 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07007924 overrun = true;
7925 }
7926 if (framesAvailable != NULL) {
7927 *framesAvailable = framesIn;
7928 }
7929 if (hasOverrun != NULL) {
7930 *hasOverrun = overrun;
7931 }
7932}
7933
Eric Laurent81784c32012-11-19 14:55:58 -08007934// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007935status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007936 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007937{
Andy Hung73c02e42015-03-29 01:13:58 -07007938 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007939 if (threadBase == 0) {
7940 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007941 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007942 return NOT_ENOUGH_DATA;
7943 }
7944 RecordThread *recordThread = (RecordThread *) threadBase.get();
7945 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007946 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07007947 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007948 // FIXME should not be P2 (don't want to increase latency)
7949 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007950 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007951 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007952 front &= recordThread->mRsmpInFramesP2 - 1;
7953 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007954 if (part1 > (size_t) filled) {
7955 part1 = filled;
7956 }
7957 size_t ask = buffer->frameCount;
7958 ALOG_ASSERT(ask > 0);
7959 if (part1 > ask) {
7960 part1 = ask;
7961 }
7962 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007963 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007964 buffer->raw = NULL;
7965 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007966 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007967 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007968 }
7969
Andy Hung57446612015-04-19 23:56:46 -07007970 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007971 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007972 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007973 return NO_ERROR;
7974}
7975
7976// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007977void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7978 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007979{
Hongwei Wang95e37682019-04-12 11:13:36 -07007980 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07007981 if (stepCount == 0) {
7982 return;
7983 }
Andy Hung73c02e42015-03-29 01:13:58 -07007984 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7985 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07007986 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07007987 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007988 buffer->frameCount = 0;
7989}
7990
Eric Laurentd8365c52017-07-16 15:27:05 -07007991void AudioFlinger::RecordThread::checkBtNrec()
7992{
7993 Mutex::Autolock _l(mLock);
7994 checkBtNrec_l();
7995}
7996
7997void AudioFlinger::RecordThread::checkBtNrec_l()
7998{
7999 // disable AEC and NS if the device is a BT SCO headset supporting those
8000 // pre processings
8001 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
8002 mAudioFlinger->btNrecIsOff();
8003 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8004 for (size_t i = 0; i < mEffectChains.size(); i++) {
8005 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8006 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8007 }
8008 }
8009}
8010
Andy Hung97a893e2015-03-29 01:03:07 -07008011
Eric Laurent10351942014-05-08 18:49:52 -07008012bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8013 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008014{
8015 bool reconfig = false;
8016
Eric Laurent10351942014-05-08 18:49:52 -07008017 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008018
Eric Laurent10351942014-05-08 18:49:52 -07008019 audio_format_t reqFormat = mFormat;
8020 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008021 // 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 -07008022 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8023
8024 AudioParameter param = AudioParameter(keyValuePair);
8025 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008026
8027 // scope for AutoPark extends to end of method
8028 AutoPark<FastCapture> park(mFastCapture);
8029
Eric Laurent10351942014-05-08 18:49:52 -07008030 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8031 // channel count change can be requested. Do we mandate the first client defines the
8032 // HAL sampling rate and channel count or do we allow changes on the fly?
8033 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8034 samplingRate = value;
8035 reconfig = true;
8036 }
8037 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008038 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008039 status = BAD_VALUE;
8040 } else {
8041 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008042 reconfig = true;
8043 }
Eric Laurent10351942014-05-08 18:49:52 -07008044 }
8045 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8046 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008047 if (!audio_is_input_channel(mask) ||
8048 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008049 status = BAD_VALUE;
8050 } else {
8051 channelMask = mask;
8052 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008053 }
Eric Laurent10351942014-05-08 18:49:52 -07008054 }
8055 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8056 // do not accept frame count changes if tracks are open as the track buffer
8057 // size depends on frame count and correct behavior would not be guaranteed
8058 // if frame count is changed after track creation
8059 if (mActiveTracks.size() > 0) {
8060 status = INVALID_OPERATION;
8061 } else {
8062 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008063 }
Eric Laurent10351942014-05-08 18:49:52 -07008064 }
8065 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
8066 // forward device change to effects that have requested to be
8067 // aware of attached audio device.
8068 for (size_t i = 0; i < mEffectChains.size(); i++) {
8069 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08008070 }
Eric Laurent81784c32012-11-19 14:55:58 -08008071
Eric Laurent10351942014-05-08 18:49:52 -07008072 // store input device and output device but do not forward output device to audio HAL.
8073 // Note that status is ignored by the caller for output device
8074 // (see AudioFlinger::setParameters()
8075 if (audio_is_output_devices(value)) {
8076 mOutDevice = value;
8077 status = BAD_VALUE;
8078 } else {
8079 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07008080 if (value != AUDIO_DEVICE_NONE) {
8081 mPrevInDevice = value;
8082 }
Eric Laurentd8365c52017-07-16 15:27:05 -07008083 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008084 }
Eric Laurent10351942014-05-08 18:49:52 -07008085 }
8086 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8087 mAudioSource != (audio_source_t)value) {
8088 // forward device change to effects that have requested to be
8089 // aware of attached audio device.
8090 for (size_t i = 0; i < mEffectChains.size(); i++) {
8091 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08008092 }
Eric Laurent10351942014-05-08 18:49:52 -07008093 mAudioSource = (audio_source_t)value;
8094 }
Glenn Kastene198c362013-08-13 09:13:36 -07008095
Eric Laurent10351942014-05-08 18:49:52 -07008096 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008097 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008098 if (status == INVALID_OPERATION) {
8099 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008100 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008101 }
8102 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008103 if (status == BAD_VALUE) {
8104 uint32_t sRate;
8105 audio_channel_mask_t channelMask;
8106 audio_format_t format;
8107 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8108 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8109 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8110 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8111 status = NO_ERROR;
8112 }
Eric Laurent81784c32012-11-19 14:55:58 -08008113 }
Eric Laurent10351942014-05-08 18:49:52 -07008114 if (status == NO_ERROR) {
8115 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008116 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008117 }
8118 }
Eric Laurent81784c32012-11-19 14:55:58 -08008119 }
Eric Laurent10351942014-05-08 18:49:52 -07008120
Eric Laurent81784c32012-11-19 14:55:58 -08008121 return reconfig;
8122}
8123
8124String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8125{
Eric Laurent81784c32012-11-19 14:55:58 -08008126 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008127 if (initCheck() == NO_ERROR) {
8128 String8 out_s8;
8129 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8130 return out_s8;
8131 }
Eric Laurent81784c32012-11-19 14:55:58 -08008132 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008133 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008134}
8135
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008136void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008137 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8138
8139 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008140
8141 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008142 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008143 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008144 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008145 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008146 desc->mChannelMask = mChannelMask;
8147 desc->mSamplingRate = mSampleRate;
8148 desc->mFormat = mFormat;
8149 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008150 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008151 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008152 break;
8153
Eric Laurent73e26b62015-04-27 16:55:58 -07008154 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008155 default:
8156 break;
8157 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008158 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008159}
8160
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008161void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008162{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008163 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8164 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008165 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008166 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8167 if (audio_is_linear_pcm(mFormat)) {
8168 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8169 mChannelCount, FCC_8);
8170 } else {
8171 // Can have more that FCC_8 channels in encoded streams.
8172 ALOGI("HAL format %#x is not linear pcm", mFormat);
8173 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008174 result = mInput->stream->getFrameSize(&mFrameSize);
8175 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8176 result = mInput->stream->getBufferSize(&mBufferSize);
8177 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008178 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008179 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
8180 "mBufferSize=%lld, mFrameCount=%lld",
8181 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
8182 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008183 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008184 // 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 -07008185 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008186 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008187 // A larger value should allow more old data to be read after a track calls start(),
8188 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008189 //
8190 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008191 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008192 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008193 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008194 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008195
8196 // TODO optimize audio capture buffer sizes ...
8197 // Here we calculate the size of the sliding buffer used as a source
8198 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8199 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8200 // be better to have it derived from the pipe depth in the long term.
8201 // The current value is higher than necessary. However it should not add to latency.
8202
Glenn Kasten85948432013-08-19 12:09:05 -07008203 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008204 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8205 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008206 // if posix_memalign fails, will segv here.
8207 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008208
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008209 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8210 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08008211}
8212
Glenn Kasten5f972c02014-01-13 09:59:31 -08008213uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008214{
8215 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008216 uint32_t result;
8217 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8218 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008219 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008220 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008221}
8222
Glenn Kastend848eb42016-03-08 13:42:11 -08008223KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008224{
Glenn Kastend848eb42016-03-08 13:42:11 -08008225 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008226 Mutex::Autolock _l(mLock);
8227 for (size_t j = 0; j < mTracks.size(); ++j) {
8228 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008229 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008230 if (ids.indexOfKey(sessionId) < 0) {
8231 ids.add(sessionId, true);
8232 }
8233 }
8234 return ids;
8235}
8236
8237AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8238{
8239 Mutex::Autolock _l(mLock);
8240 AudioStreamIn *input = mInput;
8241 mInput = NULL;
8242 return input;
8243}
8244
8245// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008246sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008247{
8248 if (mInput == NULL) {
8249 return NULL;
8250 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008251 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008252}
8253
8254status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8255{
8256 // only one chain per input thread
Eric Tan39ec8d62018-07-24 09:49:29 -07008257 if (!mEffectChains.isEmpty()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07008258 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08008259 return INVALID_OPERATION;
8260 }
8261 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008262 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008263 chain->setInBuffer(NULL);
8264 chain->setOutBuffer(NULL);
8265
8266 checkSuspendOnAddEffectChain_l(chain);
8267
Eric Laurent1b928682014-10-02 19:41:47 -07008268 // make sure enabled pre processing effects state is communicated to the HAL as we
8269 // just moved them to a new input stream.
8270 chain->syncHalEffectsState();
8271
Eric Laurent81784c32012-11-19 14:55:58 -08008272 mEffectChains.add(chain);
8273
8274 return NO_ERROR;
8275}
8276
8277size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8278{
8279 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
8280 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008281 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08008282 chain.get(), mEffectChains.size(), this);
8283 if (mEffectChains.size() == 1) {
8284 mEffectChains.removeAt(0);
8285 }
8286 return 0;
8287}
8288
Eric Laurent1c333e22014-05-20 10:48:17 -07008289status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8290 audio_patch_handle_t *handle)
8291{
8292 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008293
8294 // store new device and send to effects
8295 mInDevice = patch->sources[0].ext.device.type;
François Gaffie0c280aa2018-07-25 10:02:15 +02008296 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent296fb132015-05-01 11:38:42 -07008297 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07008298 for (size_t i = 0; i < mEffectChains.size(); i++) {
8299 mEffectChains[i]->setDevice_l(mInDevice);
8300 }
8301
Eric Laurentd8365c52017-07-16 15:27:05 -07008302 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008303
8304 // store new source and send to effects
8305 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8306 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008307 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008308 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008309 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008310 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008311
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008312 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008313 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8314 status = hwDevice->createAudioPatch(patch->num_sources,
8315 patch->sources,
8316 patch->num_sinks,
8317 patch->sinks,
8318 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008319 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008320 char *address;
8321 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8322 address = audio_device_address_to_parameter(
8323 patch->sources[0].ext.device.type,
8324 patch->sources[0].ext.device.address);
8325 } else {
8326 address = (char *)calloc(1, 1);
8327 }
8328 AudioParameter param = AudioParameter(String8(address));
8329 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008330 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008331 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008332 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008333 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008334 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008335 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008336 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008337
François Gaffie0c280aa2018-07-25 10:02:15 +02008338 if ((mInDevice != mPrevInDevice) || (mDeviceId != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008339 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8340 mPrevInDevice = mInDevice;
François Gaffie0c280aa2018-07-25 10:02:15 +02008341 mDeviceId = deviceId;
Eric Laurente8726fe2015-06-26 09:39:24 -07008342 }
Eric Laurent296fb132015-05-01 11:38:42 -07008343
Eric Laurent1c333e22014-05-20 10:48:17 -07008344 return status;
8345}
8346
8347status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8348{
8349 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008350
8351 mInDevice = AUDIO_DEVICE_NONE;
8352
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008353 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008354 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8355 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008356 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008357 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008358 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008359 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008360 }
8361 return status;
8362}
8363
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008364void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008365{
8366 Mutex::Autolock _l(mLock);
8367 mTracks.add(record);
8368}
8369
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008370void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008371{
8372 Mutex::Autolock _l(mLock);
8373 destroyTrack_l(record);
8374}
8375
Mikhail Naganovdc769682018-05-04 15:34:08 -07008376void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008377{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008378 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008379 config->role = AUDIO_PORT_ROLE_SINK;
8380 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8381 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008382 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8383 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8384 config->flags.input = mInput->flags;
8385 }
Eric Laurent83b88082014-06-20 18:31:16 -07008386}
Eric Laurent1c333e22014-05-20 10:48:17 -07008387
Eric Laurent6acd1d42017-01-04 14:23:29 -08008388// ----------------------------------------------------------------------------
8389// Mmap
8390// ----------------------------------------------------------------------------
8391
8392AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8393 : mThread(thread)
8394{
Phil Burk9fabbf82017-08-03 12:02:00 -07008395 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008396}
8397
8398AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8399{
Phil Burk9fabbf82017-08-03 12:02:00 -07008400 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008401}
8402
8403status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8404 struct audio_mmap_buffer_info *info)
8405{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008406 return mThread->createMmapBuffer(minSizeFrames, info);
8407}
8408
8409status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8410{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008411 return mThread->getMmapPosition(position);
8412}
8413
Eric Laurenta54f1282017-07-01 19:39:32 -07008414status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008415 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008416
8417{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008418 return mThread->start(client, handle);
8419}
8420
8421status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8422{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008423 return mThread->stop(handle);
8424}
8425
Eric Laurent18b57012017-02-13 16:23:52 -08008426status_t AudioFlinger::MmapThreadHandle::standby()
8427{
Eric Laurent18b57012017-02-13 16:23:52 -08008428 return mThread->standby();
8429}
8430
Eric Laurent6acd1d42017-01-04 14:23:29 -08008431
8432AudioFlinger::MmapThread::MmapThread(
8433 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8434 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8435 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8436 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008437 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008438 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008439 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008440 mActiveTracks(&this->mLocalLog),
8441 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8442 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008443{
Eric Laurent18b57012017-02-13 16:23:52 -08008444 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008445 readHalParameters_l();
8446}
8447
8448AudioFlinger::MmapThread::~MmapThread()
8449{
Eric Laurent18b57012017-02-13 16:23:52 -08008450 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008451}
8452
8453void AudioFlinger::MmapThread::onFirstRef()
8454{
8455 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8456}
8457
8458void AudioFlinger::MmapThread::disconnect()
8459{
Eric Laurent331679c2018-04-16 17:03:16 -07008460 ActiveTracks<MmapTrack> activeTracks;
8461 {
8462 Mutex::Autolock _l(mLock);
8463 for (const sp<MmapTrack> &t : mActiveTracks) {
8464 activeTracks.add(t);
8465 }
8466 }
8467 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008468 stop(t->portId());
8469 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008470 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008471 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008472 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008473 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008474 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008475 }
8476}
8477
8478
8479void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8480 audio_stream_type_t streamType __unused,
8481 audio_session_t sessionId,
8482 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008483 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008484 audio_port_handle_t portId)
8485{
8486 mAttr = *attr;
8487 mSessionId = sessionId;
8488 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008489 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008490 mPortId = portId;
8491}
8492
8493status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8494 struct audio_mmap_buffer_info *info)
8495{
8496 if (mHalStream == 0) {
8497 return NO_INIT;
8498 }
Eric Laurent18b57012017-02-13 16:23:52 -08008499 mStandby = true;
8500 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008501 return mHalStream->createMmapBuffer(minSizeFrames, info);
8502}
8503
8504status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8505{
8506 if (mHalStream == 0) {
8507 return NO_INIT;
8508 }
8509 return mHalStream->getMmapPosition(position);
8510}
8511
Eric Laurent331679c2018-04-16 17:03:16 -07008512status_t AudioFlinger::MmapThread::exitStandby()
8513{
8514 status_t ret = mHalStream->start();
8515 if (ret != NO_ERROR) {
8516 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8517 return ret;
8518 }
8519 mStandby = false;
8520 return NO_ERROR;
8521}
8522
Eric Laurenta54f1282017-07-01 19:39:32 -07008523status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008524 audio_port_handle_t *handle)
8525{
Eric Laurenta54f1282017-07-01 19:39:32 -07008526 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8527 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008528 if (mHalStream == 0) {
8529 return NO_INIT;
8530 }
8531
8532 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008533
Eric Laurenta54f1282017-07-01 19:39:32 -07008534 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008535 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008536 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008537 }
8538
8539 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8540
8541 audio_io_handle_t io = mId;
8542 if (isOutput()) {
8543 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8544 config.sample_rate = mSampleRate;
8545 config.channel_mask = mChannelMask;
8546 config.format = mFormat;
8547 audio_stream_type_t stream = streamType();
8548 audio_output_flags_t flags =
8549 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008550 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008551 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008552 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8553 mSessionId,
8554 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008555 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008556 client.clientUid,
8557 &config,
8558 flags,
8559 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008560 &portId,
8561 &secondaryOutputs);
8562 ALOGD_IF(!secondaryOutputs.empty(),
8563 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008564 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008565 audio_config_base_t config;
8566 config.sample_rate = mSampleRate;
8567 config.channel_mask = mChannelMask;
8568 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008569 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008570 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8571 mSessionId,
8572 client.clientPid,
8573 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008574 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008575 &config,
8576 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8577 &deviceId,
8578 &portId);
8579 }
8580 // APM should not chose a different input or output stream for the same set of attributes
8581 // and audo configuration
8582 if (ret != NO_ERROR || io != mId) {
8583 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8584 __FUNCTION__, ret, io, mId);
8585 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008586 }
8587
8588 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008589 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008590 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008591 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008592 }
8593
Eric Laurent331679c2018-04-16 17:03:16 -07008594 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008595 // abort if start is rejected by audio policy manager
8596 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008597 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008598 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008599 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008600 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008601 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008602 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008603 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008604 }
Eric Laurent331679c2018-04-16 17:03:16 -07008605 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008606 } else {
8607 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008608 }
8609 return PERMISSION_DENIED;
8610 }
8611
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008612 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8613 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008614 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008615
Eric Laurent4eb58f12018-12-07 16:41:02 -08008616 if (isOutput()) {
8617 // force volume update when a new track is added
8618 mHalVolFloat = -1.0f;
8619 } else if (!track->isSilenced_l()) {
8620 for (const sp<MmapTrack> &t : mActiveTracks) {
8621 if (t->isSilenced_l() && t->uid() != client.clientUid)
8622 t->invalidate();
8623 }
8624 }
8625
8626
Eric Laurent6acd1d42017-01-04 14:23:29 -08008627 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008628 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008629 if (chain != 0) {
8630 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8631 chain->incTrackCnt();
8632 chain->incActiveTrackCnt();
8633 }
8634
8635 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008636 broadcast_l();
8637
Eric Laurenta54f1282017-07-01 19:39:32 -07008638 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008639
8640 return NO_ERROR;
8641}
8642
8643status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8644{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008645 ALOGV("%s handle %d", __FUNCTION__, handle);
8646
8647 if (mHalStream == 0) {
8648 return NO_INIT;
8649 }
8650
Eric Laurenta54f1282017-07-01 19:39:32 -07008651 if (handle == mPortId) {
8652 mHalStream->stop();
8653 return NO_ERROR;
8654 }
8655
Eric Laurent331679c2018-04-16 17:03:16 -07008656 Mutex::Autolock _l(mLock);
8657
Eric Laurent6acd1d42017-01-04 14:23:29 -08008658 sp<MmapTrack> track;
8659 for (const sp<MmapTrack> &t : mActiveTracks) {
8660 if (handle == t->portId()) {
8661 track = t;
8662 break;
8663 }
8664 }
8665 if (track == 0) {
8666 return BAD_VALUE;
8667 }
8668
8669 mActiveTracks.remove(track);
8670
Eric Laurent331679c2018-04-16 17:03:16 -07008671 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008672 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008673 AudioSystem::stopOutput(track->portId());
8674 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008675 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008676 AudioSystem::stopInput(track->portId());
8677 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008678 }
Eric Laurent331679c2018-04-16 17:03:16 -07008679 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008680
8681 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8682 if (chain != 0) {
8683 chain->decActiveTrackCnt();
8684 chain->decTrackCnt();
8685 }
8686
8687 broadcast_l();
8688
Eric Laurent6acd1d42017-01-04 14:23:29 -08008689 return NO_ERROR;
8690}
8691
Eric Laurent18b57012017-02-13 16:23:52 -08008692status_t AudioFlinger::MmapThread::standby()
8693{
8694 ALOGV("%s", __FUNCTION__);
8695
8696 if (mHalStream == 0) {
8697 return NO_INIT;
8698 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008699 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008700 return INVALID_OPERATION;
8701 }
8702 mHalStream->standby();
8703 mStandby = true;
8704 releaseWakeLock();
8705 return NO_ERROR;
8706}
8707
Eric Laurent6acd1d42017-01-04 14:23:29 -08008708
8709void AudioFlinger::MmapThread::readHalParameters_l()
8710{
8711 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8712 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8713 mFormat = mHALFormat;
8714 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8715 result = mHalStream->getFrameSize(&mFrameSize);
8716 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8717 result = mHalStream->getBufferSize(&mBufferSize);
8718 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8719 mFrameCount = mBufferSize / mFrameSize;
8720}
8721
8722bool AudioFlinger::MmapThread::threadLoop()
8723{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008724 checkSilentMode_l();
8725
8726 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8727
8728 while (!exitPending())
8729 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008730 Vector< sp<EffectChain> > effectChains;
8731
Andy Hung13850be2019-03-14 11:33:09 -07008732 { // under Thread lock
8733 Mutex::Autolock _l(mLock);
8734
Eric Laurent6acd1d42017-01-04 14:23:29 -08008735 if (mSignalPending) {
8736 // A signal was raised while we were unlocked
8737 mSignalPending = false;
8738 } else {
8739 if (mConfigEvents.isEmpty()) {
8740 // we're about to wait, flush the binder command buffer
8741 IPCThreadState::self()->flushCommands();
8742
8743 if (exitPending()) {
8744 break;
8745 }
8746
Eric Laurent6acd1d42017-01-04 14:23:29 -08008747 // wait until we have something to do...
8748 ALOGV("%s going to sleep", myName.string());
8749 mWaitWorkCV.wait(mLock);
8750 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008751
8752 checkSilentMode_l();
8753
8754 continue;
8755 }
8756 }
8757
8758 processConfigEvents_l();
8759
8760 processVolume_l();
8761
8762 checkInvalidTracks_l();
8763
8764 mActiveTracks.updatePowerState(this);
8765
Kevin Rocard069c2712018-03-29 19:09:14 -07008766 updateMetadata_l();
8767
Eric Laurent6acd1d42017-01-04 14:23:29 -08008768 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07008769 } // release Thread lock
8770
Eric Laurent6acd1d42017-01-04 14:23:29 -08008771 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07008772 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08008773 }
Andy Hung13850be2019-03-14 11:33:09 -07008774
8775 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008776 unlockEffectChains(effectChains);
8777 // Effect chains will be actually deleted here if they were removed from
8778 // mEffectChains list during mixing or effects processing
8779 }
8780
8781 threadLoop_exit();
8782
8783 if (!mStandby) {
8784 threadLoop_standby();
8785 mStandby = true;
8786 }
8787
Eric Laurent6acd1d42017-01-04 14:23:29 -08008788 ALOGV("Thread %p type %d exiting", this, mType);
8789 return false;
8790}
8791
8792// checkForNewParameter_l() must be called with ThreadBase::mLock held
8793bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8794 status_t& status)
8795{
8796 AudioParameter param = AudioParameter(keyValuePair);
8797 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008798 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008799 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008800 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008801 // forward device change to effects that have requested to be
8802 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008803 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008804 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008805 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008806 }
8807 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008808 if (audio_is_output_devices(device)) {
8809 mOutDevice = device;
8810 if (!isOutput()) {
8811 sendToHal = false;
8812 }
8813 } else {
8814 mInDevice = device;
8815 if (device != AUDIO_DEVICE_NONE) {
8816 mPrevInDevice = value;
8817 }
8818 // TODO: implement and call checkBtNrec_l();
8819 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008820 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008821 if (sendToHal) {
8822 status = mHalStream->setParameters(keyValuePair);
8823 } else {
8824 status = NO_ERROR;
8825 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008826
8827 return false;
8828}
8829
8830String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8831{
8832 Mutex::Autolock _l(mLock);
8833 String8 out_s8;
8834 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8835 return out_s8;
8836 }
8837 return String8();
8838}
8839
8840void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8841 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8842
8843 desc->mIoHandle = mId;
8844
8845 switch (event) {
8846 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008847 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008848 case AUDIO_INPUT_CONFIG_CHANGED:
8849 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008850 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008851 case AUDIO_OUTPUT_CONFIG_CHANGED:
8852 desc->mPatch = mPatch;
8853 desc->mChannelMask = mChannelMask;
8854 desc->mSamplingRate = mSampleRate;
8855 desc->mFormat = mFormat;
8856 desc->mFrameCount = mFrameCount;
8857 desc->mFrameCountHAL = mFrameCount;
8858 desc->mLatency = 0;
8859 break;
8860
8861 case AUDIO_INPUT_CLOSED:
8862 case AUDIO_OUTPUT_CLOSED:
8863 default:
8864 break;
8865 }
8866 mAudioFlinger->ioConfigChanged(event, desc, pid);
8867}
8868
8869status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8870 audio_patch_handle_t *handle)
8871{
8872 status_t status = NO_ERROR;
8873
8874 // store new device and send to effects
8875 audio_devices_t type = AUDIO_DEVICE_NONE;
8876 audio_port_handle_t deviceId;
8877 if (isOutput()) {
8878 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8879 type |= patch->sinks[i].ext.device.type;
8880 }
8881 deviceId = patch->sinks[0].id;
8882 } else {
8883 type = patch->sources[0].ext.device.type;
8884 deviceId = patch->sources[0].id;
8885 }
8886
8887 for (size_t i = 0; i < mEffectChains.size(); i++) {
8888 mEffectChains[i]->setDevice_l(type);
8889 }
8890
8891 if (isOutput()) {
8892 mOutDevice = type;
8893 } else {
8894 mInDevice = type;
8895 // store new source and send to effects
8896 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8897 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8898 for (size_t i = 0; i < mEffectChains.size(); i++) {
8899 mEffectChains[i]->setAudioSource_l(mAudioSource);
8900 }
8901 }
8902 }
8903
8904 if (mAudioHwDev->supportsAudioPatches()) {
8905 status = mHalDevice->createAudioPatch(patch->num_sources,
8906 patch->sources,
8907 patch->num_sinks,
8908 patch->sinks,
8909 handle);
8910 } else {
8911 char *address;
8912 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8913 //FIXME: we only support address on first sink with HAL version < 3.0
8914 address = audio_device_address_to_parameter(
8915 patch->sinks[0].ext.device.type,
8916 patch->sinks[0].ext.device.address);
8917 } else {
8918 address = (char *)calloc(1, 1);
8919 }
8920 AudioParameter param = AudioParameter(String8(address));
8921 free(address);
8922 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8923 if (!isOutput()) {
8924 param.addInt(String8(AudioParameter::keyInputSource),
8925 (int)patch->sinks[0].ext.mix.usecase.source);
8926 }
8927 status = mHalStream->setParameters(param.toString());
8928 *handle = AUDIO_PATCH_HANDLE_NONE;
8929 }
8930
François Gaffie0c280aa2018-07-25 10:02:15 +02008931 if (isOutput() && (mPrevOutDevice != mOutDevice || mDeviceId != deviceId)) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008932 mPrevOutDevice = type;
8933 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008934 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008935 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008936 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008937 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008938 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008939 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008940 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008941 }
François Gaffie0c280aa2018-07-25 10:02:15 +02008942 if (!isOutput() && (mPrevInDevice != mInDevice || mDeviceId != deviceId)) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008943 mPrevInDevice = type;
8944 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008945 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008946 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008947 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008948 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008949 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008950 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008951 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008952 }
8953 return status;
8954}
8955
8956status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8957{
8958 status_t status = NO_ERROR;
8959
8960 mInDevice = AUDIO_DEVICE_NONE;
8961
8962 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8963 supportsAudioPatches : false;
8964
8965 if (supportsAudioPatches) {
8966 status = mHalDevice->releaseAudioPatch(handle);
8967 } else {
8968 AudioParameter param;
8969 param.addInt(String8(AudioParameter::keyRouting), 0);
8970 status = mHalStream->setParameters(param.toString());
8971 }
8972 return status;
8973}
8974
Mikhail Naganovdc769682018-05-04 15:34:08 -07008975void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008976{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008977 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008978 if (isOutput()) {
8979 config->role = AUDIO_PORT_ROLE_SOURCE;
8980 config->ext.mix.hw_module = mAudioHwDev->handle();
8981 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8982 } else {
8983 config->role = AUDIO_PORT_ROLE_SINK;
8984 config->ext.mix.hw_module = mAudioHwDev->handle();
8985 config->ext.mix.usecase.source = mAudioSource;
8986 }
8987}
8988
8989status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8990{
8991 audio_session_t session = chain->sessionId();
8992
8993 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8994 // Attach all tracks with same session ID to this chain.
8995 // indicate all active tracks in the chain
8996 for (const sp<MmapTrack> &track : mActiveTracks) {
8997 if (session == track->sessionId()) {
8998 chain->incTrackCnt();
8999 chain->incActiveTrackCnt();
9000 }
9001 }
9002
9003 chain->setThread(this);
9004 chain->setInBuffer(nullptr);
9005 chain->setOutBuffer(nullptr);
9006 chain->syncHalEffectsState();
9007
9008 mEffectChains.add(chain);
9009 checkSuspendOnAddEffectChain_l(chain);
9010 return NO_ERROR;
9011}
9012
9013size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9014{
9015 audio_session_t session = chain->sessionId();
9016
9017 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9018
9019 for (size_t i = 0; i < mEffectChains.size(); i++) {
9020 if (chain == mEffectChains[i]) {
9021 mEffectChains.removeAt(i);
9022 // detach all active tracks from the chain
9023 // detach all tracks with same session ID from this chain
9024 for (const sp<MmapTrack> &track : mActiveTracks) {
9025 if (session == track->sessionId()) {
9026 chain->decActiveTrackCnt();
9027 chain->decTrackCnt();
9028 }
9029 }
9030 break;
9031 }
9032 }
9033 return mEffectChains.size();
9034}
9035
Eric Laurent6acd1d42017-01-04 14:23:29 -08009036void AudioFlinger::MmapThread::threadLoop_standby()
9037{
9038 mHalStream->standby();
9039}
9040
9041void AudioFlinger::MmapThread::threadLoop_exit()
9042{
Phil Burk7dce7282017-09-27 13:51:41 -07009043 // Do not call callback->onTearDown() because it is redundant for thread exit
9044 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009045}
9046
9047status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9048{
9049 return BAD_VALUE;
9050}
9051
9052bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9053{
9054 return false;
9055}
9056
9057status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9058 const effect_descriptor_t *desc, audio_session_t sessionId)
9059{
9060 // No global effect sessions on mmap threads
9061 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
9062 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
9063 desc->name, mThreadName);
9064 return BAD_VALUE;
9065 }
9066
9067 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9068 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9069 desc->name);
9070 return BAD_VALUE;
9071 }
9072 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009073 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9074 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009075 return BAD_VALUE;
9076 }
9077
9078 // Only allow effects without processing load or latency
9079 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9080 return BAD_VALUE;
9081 }
9082
9083 return NO_ERROR;
9084
9085}
9086
9087void AudioFlinger::MmapThread::checkInvalidTracks_l()
9088{
9089 for (const sp<MmapTrack> &track : mActiveTracks) {
9090 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009091 sp<MmapStreamCallback> callback = mCallback.promote();
9092 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009093 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009094 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009095 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009096 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9097 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9098 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009099 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009100 }
9101 }
9102}
9103
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009104void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009105{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009106 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9107 mAttr.content_type, mAttr.usage, mAttr.source);
9108 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009109 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009110 dprintf(fd, " No active clients\n");
9111 }
9112}
9113
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009114void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009115{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009116 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009117 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009118 dprintf(fd, " %zu Tracks\n", numtracks);
9119 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009120 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009121 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009122 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009123 for (size_t i = 0; i < numtracks ; ++i) {
9124 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009125 result.append(prefix);
9126 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009127 }
9128 } else {
9129 dprintf(fd, "\n");
9130 }
9131 write(fd, result.string(), result.size());
9132}
9133
9134AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9135 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9136 AudioHwDevice *hwDev, AudioStreamOut *output,
9137 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9138 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
9139 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009140 mStreamVolume(1.0),
9141 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009142 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009143{
9144 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9145 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9146 mMasterVolume = audioFlinger->masterVolume_l();
9147 mMasterMute = audioFlinger->masterMute_l();
9148 if (mAudioHwDev) {
9149 if (mAudioHwDev->canSetMasterVolume()) {
9150 mMasterVolume = 1.0;
9151 }
9152
9153 if (mAudioHwDev->canSetMasterMute()) {
9154 mMasterMute = false;
9155 }
9156 }
9157}
9158
9159void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9160 audio_stream_type_t streamType,
9161 audio_session_t sessionId,
9162 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009163 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009164 audio_port_handle_t portId)
9165{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009166 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009167 mStreamType = streamType;
9168}
9169
9170AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9171{
9172 Mutex::Autolock _l(mLock);
9173 AudioStreamOut *output = mOutput;
9174 mOutput = NULL;
9175 return output;
9176}
9177
9178void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9179{
9180 Mutex::Autolock _l(mLock);
9181 // Don't apply master volume in SW if our HAL can do it for us.
9182 if (mAudioHwDev &&
9183 mAudioHwDev->canSetMasterVolume()) {
9184 mMasterVolume = 1.0;
9185 } else {
9186 mMasterVolume = value;
9187 }
9188}
9189
9190void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9191{
9192 Mutex::Autolock _l(mLock);
9193 // Don't apply master mute in SW if our HAL can do it for us.
9194 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9195 mMasterMute = false;
9196 } else {
9197 mMasterMute = muted;
9198 }
9199}
9200
9201void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9202{
9203 Mutex::Autolock _l(mLock);
9204 if (stream == mStreamType) {
9205 mStreamVolume = value;
9206 broadcast_l();
9207 }
9208}
9209
9210float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9211{
9212 Mutex::Autolock _l(mLock);
9213 if (stream == mStreamType) {
9214 return mStreamVolume;
9215 }
9216 return 0.0f;
9217}
9218
9219void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9220{
9221 Mutex::Autolock _l(mLock);
9222 if (stream == mStreamType) {
9223 mStreamMute= muted;
9224 broadcast_l();
9225 }
9226}
9227
9228void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9229{
9230 Mutex::Autolock _l(mLock);
9231 if (streamType == mStreamType) {
9232 for (const sp<MmapTrack> &track : mActiveTracks) {
9233 track->invalidate();
9234 }
9235 broadcast_l();
9236 }
9237}
9238
9239void AudioFlinger::MmapPlaybackThread::processVolume_l()
9240{
9241 float volume;
9242
9243 if (mMasterMute || mStreamMute) {
9244 volume = 0;
9245 } else {
9246 volume = mMasterVolume * mStreamVolume;
9247 }
9248
9249 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009250
9251 // Convert volumes from float to 8.24
9252 uint32_t vol = (uint32_t)(volume * (1 << 24));
9253
9254 // Delegate volume control to effect in track effect chain if needed
9255 // only one effect chain can be present on DirectOutputThread, so if
9256 // there is one, the track is connected to it
9257 if (!mEffectChains.isEmpty()) {
9258 mEffectChains[0]->setVolume_l(&vol, &vol);
9259 volume = (float)vol / (1 << 24);
9260 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009261 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009262 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9263 mHalVolFloat = volume; // HW volume control worked, so update value.
9264 mNoCallbackWarningCount = 0;
9265 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009266 sp<MmapStreamCallback> callback = mCallback.promote();
9267 if (callback != 0) {
9268 int channelCount;
9269 if (isOutput()) {
9270 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9271 } else {
9272 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9273 }
9274 Vector<float> values;
9275 for (int i = 0; i < channelCount; i++) {
9276 values.add(volume);
9277 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009278 mHalVolFloat = volume; // SW volume control worked, so update value.
9279 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009280 mLock.unlock();
9281 callback->onVolumeChanged(mChannelMask, values);
9282 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009283 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009284 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9285 ALOGW("Could not set MMAP stream volume: no volume callback!");
9286 mNoCallbackWarningCount++;
9287 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009288 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009289 }
9290 }
9291}
9292
Kevin Rocard069c2712018-03-29 19:09:14 -07009293void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9294{
9295 if (mOutput == nullptr || mOutput->stream == nullptr ||
9296 !mActiveTracks.readAndClearHasChanged()) {
9297 return;
9298 }
9299 StreamOutHalInterface::SourceMetadata metadata;
9300 for (const sp<MmapTrack> &track : mActiveTracks) {
9301 // No track is invalid as this is called after prepareTrack_l in the same critical section
9302 metadata.tracks.push_back({
9303 .usage = track->attributes().usage,
9304 .content_type = track->attributes().content_type,
9305 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9306 });
9307 }
9308 mOutput->stream->updateSourceMetadata(metadata);
9309}
9310
Eric Laurent6acd1d42017-01-04 14:23:29 -08009311void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9312{
9313 if (!mMasterMute) {
9314 char value[PROPERTY_VALUE_MAX];
9315 if (property_get("ro.audio.silent", value, "0") > 0) {
9316 char *endptr;
9317 unsigned long ul = strtoul(value, &endptr, 0);
9318 if (*endptr == '\0' && ul != 0) {
9319 ALOGD("Silence is golden");
9320 // The setprop command will not allow a property to be changed after
9321 // the first time it is set, so we don't have to worry about un-muting.
9322 setMasterMute_l(true);
9323 }
9324 }
9325 }
9326}
9327
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009328void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9329{
9330 MmapThread::toAudioPortConfig(config);
9331 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9332 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9333 config->flags.output = mOutput->flags;
9334 }
9335}
9336
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009337void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009338{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009339 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009340
Glenn Kastend3bb6452016-12-05 18:14:37 -08009341 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9342 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009343 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9344}
9345
9346AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9347 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9348 AudioHwDevice *hwDev, AudioStreamIn *input,
9349 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9350 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9351 mInput(input)
9352{
9353 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9354 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9355}
9356
Eric Laurent331679c2018-04-16 17:03:16 -07009357status_t AudioFlinger::MmapCaptureThread::exitStandby()
9358{
Phil Burkf054fc32018-12-06 09:45:59 -08009359 {
9360 // mInput might have been cleared by clearInput()
9361 Mutex::Autolock _l(mLock);
9362 if (mInput != nullptr && mInput->stream != nullptr) {
9363 mInput->stream->setGain(1.0f);
9364 }
9365 }
Eric Laurent331679c2018-04-16 17:03:16 -07009366 return MmapThread::exitStandby();
9367}
9368
Eric Laurent6acd1d42017-01-04 14:23:29 -08009369AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9370{
9371 Mutex::Autolock _l(mLock);
9372 AudioStreamIn *input = mInput;
9373 mInput = NULL;
9374 return input;
9375}
Kevin Rocard069c2712018-03-29 19:09:14 -07009376
Eric Laurent331679c2018-04-16 17:03:16 -07009377
9378void AudioFlinger::MmapCaptureThread::processVolume_l()
9379{
9380 bool changed = false;
9381 bool silenced = false;
9382
9383 sp<MmapStreamCallback> callback = mCallback.promote();
9384 if (callback == 0) {
9385 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9386 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9387 mNoCallbackWarningCount++;
9388 }
9389 }
9390
9391 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9392 // track is silenced and unmute otherwise
9393 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9394 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9395 changed = true;
9396 silenced = mActiveTracks[i]->isSilenced_l();
9397 }
9398 }
9399
9400 if (changed) {
9401 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9402 }
9403}
9404
Kevin Rocard069c2712018-03-29 19:09:14 -07009405void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9406{
9407 if (mInput == nullptr || mInput->stream == nullptr ||
9408 !mActiveTracks.readAndClearHasChanged()) {
9409 return;
9410 }
9411 StreamInHalInterface::SinkMetadata metadata;
9412 for (const sp<MmapTrack> &track : mActiveTracks) {
9413 // No track is invalid as this is called after prepareTrack_l in the same critical section
9414 metadata.tracks.push_back({
9415 .source = track->attributes().source,
9416 .gain = 1, // capture tracks do not have volumes
9417 });
9418 }
9419 mInput->stream->updateSinkMetadata(metadata);
9420}
9421
Eric Laurent331679c2018-04-16 17:03:16 -07009422void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9423{
9424 Mutex::Autolock _l(mLock);
9425 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9426 if (mActiveTracks[i]->uid() == uid) {
9427 mActiveTracks[i]->setSilenced_l(silenced);
9428 broadcast_l();
9429 }
9430 }
9431}
9432
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009433void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9434{
9435 MmapThread::toAudioPortConfig(config);
9436 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9437 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9438 config->flags.input = mInput->flags;
9439 }
9440}
9441
Glenn Kasten63238ef2015-03-02 15:50:29 -08009442} // namespace android