blob: b5f61e7416dd2c329ffb241e12a7a670e4d70b66 [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>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080041#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080043#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070044#include <audio_utils/minifloat.h>
Eric Tan1882f162018-08-02 18:05:39 -070045#include <json/json.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070046#include <system/audio_effects/effect_ns.h>
47#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070048#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049
50// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070051#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080052#include <media/nbaio/AudioStreamOutSink.h>
53#include <media/nbaio/MonoPipe.h>
54#include <media/nbaio/MonoPipeReader.h>
55#include <media/nbaio/Pipe.h>
56#include <media/nbaio/PipeReader.h>
57#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080058#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080059
60#include <powermanager/PowerManager.h>
61
Kevin Rocard7588ff42018-01-08 11:11:30 -080062#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070063#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080066#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070067#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070068#include <mediautils/SchedulingPolicyService.h>
69#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080070
Eric Laurent81784c32012-11-19 14:55:58 -080071#ifdef ADD_BATTERY_DATA
72#include <media/IMediaPlayerService.h>
73#include <media/IMediaDeathNotifier.h>
74#endif
75
Eric Laurent81784c32012-11-19 14:55:58 -080076#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070077#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080078#include <cpustats/ThreadCpuUsage.h>
79#endif
80
Glenn Kastenc05b8d72016-03-24 09:48:17 -070081#include "AutoPark.h"
82
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080083#include <pthread.h>
84#include "TypedLogger.h"
85
Eric Laurent81784c32012-11-19 14:55:58 -080086// ----------------------------------------------------------------------------
87
88// Note: the following macro is used for extremely verbose logging message. In
89// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
90// 0; but one side effect of this is to turn all LOGV's as well. Some messages
91// are so verbose that we want to suppress them even when we have ALOG_ASSERT
92// turned on. Do not uncomment the #def below unless you really know what you
93// are doing and want to see all of the extremely verbose messages.
94//#define VERY_VERY_VERBOSE_LOGGING
95#ifdef VERY_VERY_VERBOSE_LOGGING
96#define ALOGVV ALOGV
97#else
98#define ALOGVV(a...) do { } while(0)
99#endif
100
Andy Hung6770c6f2015-04-07 13:43:36 -0700101// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700102#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700103template <typename T>
104static inline T min(const T& a, const T& b)
105{
106 return a < b ? a : b;
107}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700108
Eric Laurent81784c32012-11-19 14:55:58 -0800109namespace android {
110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700119
Eric Laurent51716182016-02-29 18:00:56 -0800120
Eric Laurent81784c32012-11-19 14:55:58 -0800121
122// don't warn about blocked writes or record buffer overflows more often than this
123static const nsecs_t kWarningThrottleNs = seconds(5);
124
125// RecordThread loop sleep time upon application overrun or audio HAL read error
126static const int kRecordThreadSleepUs = 5000;
127
Eric Laurent10351942014-05-08 18:49:52 -0700128// maximum time to wait in sendConfigEvent_l() for a status to be received
129static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800130
131// minimum sleep time for the mixer thread loop when tracks are active but in underrun
132static const uint32_t kMinThreadSleepTimeUs = 5000;
133// maximum divider applied to the active sleep time in the mixer thread loop
134static const uint32_t kMaxThreadSleepTimeShift = 2;
135
Andy Hung09a50072014-02-27 14:30:47 -0800136// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700137// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800138static const uint32_t kMinNormalSinkBufferSizeMs = 20;
139// maximum normal sink buffer size
140static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800141
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700142// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
143// FIXME This should be based on experimentally observed scheduling jitter
144static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
145
Eric Laurent972a1732013-09-04 09:42:59 -0700146// Offloaded output thread standby delay: allows track transition without going to standby
147static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
148
Eric Laurent51716182016-02-29 18:00:56 -0800149// Direct output thread minimum sleep time in idle or active(underrun) state
150static const nsecs_t kDirectMinSleepTimeUs = 10000;
151
Glenn Kasten1b291842016-07-18 14:55:21 -0700152// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
153// balance between power consumption and latency, and allows threads to be scheduled reliably
154// by the CFS scheduler.
155// FIXME Express other hardcoded references to 20ms with references to this constant and move
156// it appropriately.
157#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800158
Eric Laurent81784c32012-11-19 14:55:58 -0800159// Whether to use fast mixer
160static const enum {
161 FastMixer_Never, // never initialize or use: for debugging only
162 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
163 // normal mixer multiplier is 1
164 FastMixer_Static, // initialize if needed, then use all the time if initialized,
165 // multiplier is calculated based on min & max normal mixer buffer size
166 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
167 // multiplier is calculated based on min & max normal mixer buffer size
168 // FIXME for FastMixer_Dynamic:
169 // Supporting this option will require fixing HALs that can't handle large writes.
170 // For example, one HAL implementation returns an error from a large write,
171 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
172 // We could either fix the HAL implementations, or provide a wrapper that breaks
173 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
174} kUseFastMixer = FastMixer_Static;
175
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700176// Whether to use fast capture
177static const enum {
178 FastCapture_Never, // never initialize or use: for debugging only
179 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
180 FastCapture_Static, // initialize if needed, then use all the time if initialized
181} kUseFastCapture = FastCapture_Static;
182
Eric Laurent81784c32012-11-19 14:55:58 -0800183// Priorities for requestPriority
184static const int kPriorityAudioApp = 2;
185static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700186static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800187
Glenn Kastenea38ee72016-04-18 11:08:01 -0700188// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
189// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
190// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700191
192// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800193static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800194
Glenn Kasten03490092014-05-27 12:30:54 -0700195// The minimum and maximum allowed values
196static const int kFastTrackMultiplierMin = 1;
197static const int kFastTrackMultiplierMax = 2;
198
199// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
200static int sFastTrackMultiplier = kFastTrackMultiplier;
201
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700202// See Thread::readOnlyHeap().
203// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
204// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
205// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700206static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700207
Eric Laurent81784c32012-11-19 14:55:58 -0800208// ----------------------------------------------------------------------------
209
Glenn Kasten03490092014-05-27 12:30:54 -0700210static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
211
212static void sFastTrackMultiplierInit()
213{
214 char value[PROPERTY_VALUE_MAX];
215 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
216 char *endptr;
217 unsigned long ul = strtoul(value, &endptr, 0);
218 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
219 sFastTrackMultiplier = (int) ul;
220 }
221 }
222}
223
224// ----------------------------------------------------------------------------
225
Eric Laurent81784c32012-11-19 14:55:58 -0800226#ifdef ADD_BATTERY_DATA
227// To collect the amplifier usage
228static void addBatteryData(uint32_t params) {
229 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
230 if (service == NULL) {
231 // it already logged
232 return;
233 }
234
235 service->addBatteryData(params);
236}
237#endif
238
Andy Hung3f0c9022016-01-15 17:49:46 -0800239// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
240struct {
241 // call when you acquire a partial wakelock
242 void acquire(const sp<IBinder> &wakeLockToken) {
243 pthread_mutex_lock(&mLock);
244 if (wakeLockToken.get() == nullptr) {
245 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
246 } else {
247 if (mCount == 0) {
248 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
249 }
250 ++mCount;
251 }
252 pthread_mutex_unlock(&mLock);
253 }
254
255 // call when you release a partial wakelock.
256 void release(const sp<IBinder> &wakeLockToken) {
257 if (wakeLockToken.get() == nullptr) {
258 return;
259 }
260 pthread_mutex_lock(&mLock);
261 if (--mCount < 0) {
262 ALOGE("negative wakelock count");
263 mCount = 0;
264 }
265 pthread_mutex_unlock(&mLock);
266 }
267
268 // retrieves the boottime timebase offset from monotonic.
269 int64_t getBoottimeOffset() {
270 pthread_mutex_lock(&mLock);
271 int64_t boottimeOffset = mBoottimeOffset;
272 pthread_mutex_unlock(&mLock);
273 return boottimeOffset;
274 }
275
276 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
277 // and the selected timebase.
278 // Currently only TIMEBASE_BOOTTIME is allowed.
279 //
280 // This only needs to be called upon acquiring the first partial wakelock
281 // after all other partial wakelocks are released.
282 //
283 // We do an empirical measurement of the offset rather than parsing
284 // /proc/timer_list since the latter is not a formal kernel ABI.
285 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
286 int clockbase;
287 switch (timebase) {
288 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
289 clockbase = SYSTEM_TIME_BOOTTIME;
290 break;
291 default:
292 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
293 break;
294 }
295 // try three times to get the clock offset, choose the one
296 // with the minimum gap in measurements.
297 const int tries = 3;
298 nsecs_t bestGap, measured;
299 for (int i = 0; i < tries; ++i) {
300 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
301 const nsecs_t tbase = systemTime(clockbase);
302 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
303 const nsecs_t gap = tmono2 - tmono;
304 if (i == 0 || gap < bestGap) {
305 bestGap = gap;
306 measured = tbase - ((tmono + tmono2) >> 1);
307 }
308 }
309
310 // to avoid micro-adjusting, we don't change the timebase
311 // unless it is significantly different.
312 //
313 // Assumption: It probably takes more than toleranceNs to
314 // suspend and resume the device.
315 static int64_t toleranceNs = 10000; // 10 us
316 if (llabs(*offset - measured) > toleranceNs) {
317 ALOGV("Adjusting timebase offset old: %lld new: %lld",
318 (long long)*offset, (long long)measured);
319 *offset = measured;
320 }
321 }
322
323 pthread_mutex_t mLock;
324 int32_t mCount;
325 int64_t mBoottimeOffset;
326} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800327
328// ----------------------------------------------------------------------------
329// CPU Stats
330// ----------------------------------------------------------------------------
331
332class CpuStats {
333public:
334 CpuStats();
335 void sample(const String8 &title);
336#ifdef DEBUG_CPU_USAGE
337private:
338 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700339 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800340
Andy Hung16698b82018-08-01 10:48:38 -0700341 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800342
343 int mCpuNum; // thread's current CPU number
344 int mCpukHz; // frequency of thread's current CPU in kHz
345#endif
346};
347
348CpuStats::CpuStats()
349#ifdef DEBUG_CPU_USAGE
350 : mCpuNum(-1), mCpukHz(-1)
351#endif
352{
353}
354
Glenn Kasten0f11b512014-01-31 16:18:54 -0800355void CpuStats::sample(const String8 &title
356#ifndef DEBUG_CPU_USAGE
357 __unused
358#endif
359 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800360#ifdef DEBUG_CPU_USAGE
361 // get current thread's delta CPU time in wall clock ns
362 double wcNs;
363 bool valid = mCpuUsage.sampleAndEnable(wcNs);
364
365 // record sample for wall clock statistics
366 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700367 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800368 }
369
370 // get the current CPU number
371 int cpuNum = sched_getcpu();
372
373 // get the current CPU frequency in kHz
374 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
375
376 // check if either CPU number or frequency changed
377 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
378 mCpuNum = cpuNum;
379 mCpukHz = cpukHz;
380 // ignore sample for purposes of cycles
381 valid = false;
382 }
383
384 // if no change in CPU number or frequency, then record sample for cycle statistics
385 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700386 const double cycles = wcNs * cpukHz * 0.000001;
387 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800388 }
389
Eric Tan5b13ff82018-07-27 11:20:17 -0700390 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800391 // mCpuUsage.elapsed() is expensive, so don't call it every loop
392 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700393 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800394 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700395 const double perLoop = elapsed / (double) n;
396 const double perLoop100 = perLoop * 0.01;
397 const double perLoop1k = perLoop * 0.001;
398 const double mean = mWcStats.getMean();
399 const double stddev = mWcStats.getStdDev();
400 const double minimum = mWcStats.getMin();
401 const double maximum = mWcStats.getMax();
402 const double meanCycles = mHzStats.getMean();
403 const double stddevCycles = mHzStats.getStdDev();
404 const double minCycles = mHzStats.getMin();
405 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800406 mCpuUsage.resetElapsed();
407 mWcStats.reset();
408 mHzStats.reset();
409 ALOGD("CPU usage for %s over past %.1f secs\n"
410 " (%u mixer loops at %.1f mean ms per loop):\n"
411 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
412 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
413 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
414 title.string(),
415 elapsed * .000000001, n, perLoop * .000001,
416 mean * .001,
417 stddev * .001,
418 minimum * .001,
419 maximum * .001,
420 mean / perLoop100,
421 stddev / perLoop100,
422 minimum / perLoop100,
423 maximum / perLoop100,
424 meanCycles / perLoop1k,
425 stddevCycles / perLoop1k,
426 minCycles / perLoop1k,
427 maxCycles / perLoop1k);
428
429 }
430 }
431#endif
432};
433
434// ----------------------------------------------------------------------------
435// ThreadBase
436// ----------------------------------------------------------------------------
437
Glenn Kasten97b7b752014-09-28 13:04:24 -0700438// static
439const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
440{
441 switch (type) {
442 case MIXER:
443 return "MIXER";
444 case DIRECT:
445 return "DIRECT";
446 case DUPLICATING:
447 return "DUPLICATING";
448 case RECORD:
449 return "RECORD";
450 case OFFLOAD:
451 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800452 case MMAP:
453 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700454 default:
455 return "unknown";
456 }
457}
458
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700461 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800462 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700463 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800464 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700465 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800466 }
467 return result;
468}
469
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700470std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800471{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700472 std::string result;
473 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800474 return result;
475}
476
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700477std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700478{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700479 std::string result;
480 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700481 return result;
482}
483
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800484const char *sourceToString(audio_source_t source)
485{
486 switch (source) {
487 case AUDIO_SOURCE_DEFAULT: return "default";
488 case AUDIO_SOURCE_MIC: return "mic";
489 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
490 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
491 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
492 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
493 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
494 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
495 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800496 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800497 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
498 case AUDIO_SOURCE_HOTWORD: return "hotword";
499 default: return "unknown";
500 }
501}
502
Eric Laurent81784c32012-11-19 14:55:58 -0800503AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700504 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800505 : Thread(false /*canCallJava*/),
506 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700507 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700508 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800509 // are set by PlaybackThread::readOutputParameters_l() or
510 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700511 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800512 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700513 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
514 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800515 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700516 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800517 mSystemReady(systemReady),
518 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800519{
Eric Laurent296fb132015-05-01 11:38:42 -0700520 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800521}
522
523AudioFlinger::ThreadBase::~ThreadBase()
524{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700525 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700526 mConfigEvents.clear();
527
Eric Laurent81784c32012-11-19 14:55:58 -0800528 // do not lock the mutex in destructor
529 releaseWakeLock_l();
530 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800531 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800532 binder->unlinkToDeath(mDeathRecipient);
533 }
534}
535
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700536status_t AudioFlinger::ThreadBase::readyToRun()
537{
538 status_t status = initCheck();
539 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800540 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700541 } else {
542 ALOGE("No working audio driver found.");
543 }
544 return status;
545}
546
Eric Laurent81784c32012-11-19 14:55:58 -0800547void AudioFlinger::ThreadBase::exit()
548{
549 ALOGV("ThreadBase::exit");
550 // do any cleanup required for exit to succeed
551 preExit();
552 {
553 // This lock prevents the following race in thread (uniprocessor for illustration):
554 // if (!exitPending()) {
555 // // context switch from here to exit()
556 // // exit() calls requestExit(), what exitPending() observes
557 // // exit() calls signal(), which is dropped since no waiters
558 // // context switch back from exit() to here
559 // mWaitWorkCV.wait(...);
560 // // now thread is hung
561 // }
562 AutoMutex lock(mLock);
563 requestExit();
564 mWaitWorkCV.broadcast();
565 }
566 // When Thread::requestExitAndWait is made virtual and this method is renamed to
567 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
568 requestExitAndWait();
569}
570
571status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
572{
Eric Laurent81784c32012-11-19 14:55:58 -0800573 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
574 Mutex::Autolock _l(mLock);
575
Eric Laurent10351942014-05-08 18:49:52 -0700576 return sendSetParameterConfigEvent_l(keyValuePairs);
577}
578
579// sendConfigEvent_l() must be called with ThreadBase::mLock held
580// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
581status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
582{
583 status_t status = NO_ERROR;
584
Eric Laurent72e3f392015-05-20 14:43:50 -0700585 if (event->mRequiresSystemReady && !mSystemReady) {
586 event->mWaitStatus = false;
587 mPendingConfigEvents.add(event);
588 return status;
589 }
Eric Laurent10351942014-05-08 18:49:52 -0700590 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700591 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800592 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700593 mLock.unlock();
594 {
595 Mutex::Autolock _l(event->mLock);
596 while (event->mWaitStatus) {
597 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
598 event->mStatus = TIMED_OUT;
599 event->mWaitStatus = false;
600 }
601 }
602 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800603 }
Eric Laurent10351942014-05-08 18:49:52 -0700604 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800605 return status;
606}
607
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700608void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800609{
610 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800612}
613
614// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700615void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800616{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700617 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700618 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800619}
620
Mikhail Naganov83f04272017-02-07 10:45:09 -0800621void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700622{
623 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800624 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700625}
626
Eric Laurent81784c32012-11-19 14:55:58 -0800627// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800628void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
629 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800630{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800631 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700632 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800633}
634
Eric Laurent10351942014-05-08 18:49:52 -0700635// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
636status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800637{
Andy Hung2ddee192015-12-18 17:34:44 -0800638 sp<ConfigEvent> configEvent;
639 AudioParameter param(keyValuePair);
640 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700641 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800642 setMasterMono_l(value != 0);
643 if (param.size() == 1) {
644 return NO_ERROR; // should be a solo parameter - we don't pass down
645 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700646 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800647 configEvent = new SetParameterConfigEvent(param.toString());
648 } else {
649 configEvent = new SetParameterConfigEvent(keyValuePair);
650 }
Eric Laurent10351942014-05-08 18:49:52 -0700651 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700652}
653
Eric Laurent1c333e22014-05-20 10:48:17 -0700654status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
655 const struct audio_patch *patch,
656 audio_patch_handle_t *handle)
657{
658 Mutex::Autolock _l(mLock);
659 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
660 status_t status = sendConfigEvent_l(configEvent);
661 if (status == NO_ERROR) {
662 CreateAudioPatchConfigEventData *data =
663 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
664 *handle = data->mHandle;
665 }
666 return status;
667}
668
669status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
670 const audio_patch_handle_t handle)
671{
672 Mutex::Autolock _l(mLock);
673 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
674 return sendConfigEvent_l(configEvent);
675}
676
677
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700678// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700679void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700680{
Eric Laurent10351942014-05-08 18:49:52 -0700681 bool configChanged = false;
682
Eric Laurent81784c32012-11-19 14:55:58 -0800683 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700684 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700685 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800686 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700687 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700688 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700689 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
690 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800691 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700692 true /*asynchronous*/);
693 if (err != 0) {
694 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700695 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700696 }
697 } break;
698 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700699 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700700 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700701 } break;
702 case CFG_EVENT_SET_PARAMETER: {
703 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
704 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
705 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700706 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
707 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700708 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700709 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700710 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700711 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700712 CreateAudioPatchConfigEventData *data =
713 (CreateAudioPatchConfigEventData *)event->mData.get();
714 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700715 const audio_devices_t newDevice = getDevice();
716 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
717 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
718 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700719 } break;
720 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700721 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700722 ReleaseAudioPatchConfigEventData *data =
723 (ReleaseAudioPatchConfigEventData *)event->mData.get();
724 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700725 const audio_devices_t newDevice = getDevice();
726 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
727 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
728 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700729 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700730 default:
Eric Laurent10351942014-05-08 18:49:52 -0700731 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700732 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800733 }
Eric Laurent10351942014-05-08 18:49:52 -0700734 {
735 Mutex::Autolock _l(event->mLock);
736 if (event->mWaitStatus) {
737 event->mWaitStatus = false;
738 event->mCond.signal();
739 }
740 }
741 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
742 }
743
744 if (configChanged) {
745 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800746 }
Eric Laurent81784c32012-11-19 14:55:58 -0800747}
748
Marco Nelissenb2208842014-02-07 14:00:50 -0800749String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
750 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700751 const audio_channel_representation_t representation =
752 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700753
754 switch (representation) {
755 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
756 if (output) {
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
759 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
761 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
762 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
763 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
764 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
765 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
766 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
770 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
771 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
772 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
773 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
774 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700775 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
776 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700777 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
778 } else {
779 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
780 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
781 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
782 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
783 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
784 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
785 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
786 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
787 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
788 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
789 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
790 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700791 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
792 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
793 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
794 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
795 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
796 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700797 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
798 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
799 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
800 }
801 const int len = s.length();
802 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700803 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700804 s.unlockBuffer(len - 2); // remove trailing ", "
805 }
806 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800807 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700808 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
809 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
810 return s;
811 default:
812 s.appendFormat("unknown mask, representation:%d bits:%#x",
813 representation, audio_channel_mask_get_bits(mask));
814 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800815 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800816}
817
Glenn Kasten0f11b512014-01-31 16:18:54 -0800818void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800819{
820 const size_t SIZE = 256;
821 char buffer[SIZE];
822 String8 result;
823
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800824 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
825 this, mThreadName, getTid(), type(), threadTypeToString(type()));
826
Eric Laurent81784c32012-11-19 14:55:58 -0800827 bool locked = AudioFlinger::dumpTryLock(mLock);
828 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800829 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800830 }
831
Elliott Hughes87cebad2014-05-22 10:14:43 -0700832 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700833 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700834 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700835 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700836 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700837 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700838 dprintf(fd, " Channel count: %u\n", mChannelCount);
839 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800840 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700841 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700842 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700843 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800844 size_t numConfig = mConfigEvents.size();
845 if (numConfig) {
846 for (size_t i = 0; i < numConfig; i++) {
847 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700848 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800849 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700850 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800851 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700852 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800853 }
Andy Hung293558a2017-03-21 12:19:20 -0700854 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700855 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
856 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800857 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800858
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700859 // Dump timestamp statistics for the Thread types that support it.
860 if (mType == RECORD
861 || mType == MIXER
862 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700863 || mType == DIRECT
864 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700865 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700866 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700867 }
868
Eric Laurent81784c32012-11-19 14:55:58 -0800869 if (locked) {
870 mLock.unlock();
871 }
872}
873
874void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
875{
876 const size_t SIZE = 256;
877 char buffer[SIZE];
878 String8 result;
879
Marco Nelissenb2208842014-02-07 14:00:50 -0800880 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000881 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800882 write(fd, buffer, strlen(buffer));
883
Marco Nelissenb2208842014-02-07 14:00:50 -0800884 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800885 sp<EffectChain> chain = mEffectChains[i];
886 if (chain != 0) {
887 chain->dump(fd, args);
888 }
889 }
890}
891
Andy Hungdae27702016-10-31 14:01:16 -0700892void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800893{
894 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700895 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800896}
897
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100898String16 AudioFlinger::ThreadBase::getWakeLockTag()
899{
900 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800901 case MIXER:
902 return String16("AudioMix");
903 case DIRECT:
904 return String16("AudioDirectOut");
905 case DUPLICATING:
906 return String16("AudioDup");
907 case RECORD:
908 return String16("AudioIn");
909 case OFFLOAD:
910 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800911 case MMAP:
912 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800913 default:
914 ALOG_ASSERT(false);
915 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100916 }
917}
918
Andy Hungdae27702016-10-31 14:01:16 -0700919void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800920{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800921 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800922 if (mPowerManager != 0) {
923 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700924 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
925 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700926 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100927 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700928 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700929 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800930 if (status == NO_ERROR) {
931 mWakeLockToken = binder;
932 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800933 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800934 }
Wei Jia3f273d12015-11-24 09:06:49 -0800935
Andy Hung3f0c9022016-01-15 17:49:46 -0800936 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800937 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
938 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800939}
940
941void AudioFlinger::ThreadBase::releaseWakeLock()
942{
943 Mutex::Autolock _l(mLock);
944 releaseWakeLock_l();
945}
946
947void AudioFlinger::ThreadBase::releaseWakeLock_l()
948{
Andy Hung3f0c9022016-01-15 17:49:46 -0800949 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800950 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800951 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800952 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700953 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
954 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800955 }
956 mWakeLockToken.clear();
957 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800958}
959
960void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700961 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800962 // use checkService() to avoid blocking if power service is not up yet
963 sp<IBinder> binder =
964 defaultServiceManager()->checkService(String16("power"));
965 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800966 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800967 } else {
968 mPowerManager = interface_cast<IPowerManager>(binder);
969 binder->linkToDeath(mDeathRecipient);
970 }
971 }
972}
973
Andy Hungd01b0f12016-11-07 16:10:30 -0800974void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800975 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700976
977#if !LOG_NDEBUG
978 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800979 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700980 s << uid << " ";
981 }
982 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
983#endif
984
Andy Hung438e7572015-12-14 15:51:17 -0800985 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
986 if (mSystemReady) {
987 ALOGE("no wake lock to update, but system ready!");
988 } else {
989 ALOGW("no wake lock to update, system not ready yet");
990 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800991 return;
992 }
993 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800994 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
995 status_t status = mPowerManager->updateWakeLockUids(
996 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
997 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800998 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800999 }
1000}
1001
Eric Laurent81784c32012-11-19 14:55:58 -08001002void AudioFlinger::ThreadBase::clearPowerManager()
1003{
1004 Mutex::Autolock _l(mLock);
1005 releaseWakeLock_l();
1006 mPowerManager.clear();
1007}
1008
Glenn Kasten0f11b512014-01-31 16:18:54 -08001009void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001010{
1011 sp<ThreadBase> thread = mThread.promote();
1012 if (thread != 0) {
1013 thread->clearPowerManager();
1014 }
1015 ALOGW("power manager service died !!!");
1016}
1017
Eric Laurent81784c32012-11-19 14:55:58 -08001018void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001019 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001020{
1021 sp<EffectChain> chain = getEffectChain_l(sessionId);
1022 if (chain != 0) {
1023 if (type != NULL) {
1024 chain->setEffectSuspended_l(type, suspend);
1025 } else {
1026 chain->setEffectSuspendedAll_l(suspend);
1027 }
1028 }
1029
1030 updateSuspendedSessions_l(type, suspend, sessionId);
1031}
1032
1033void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1034{
1035 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1036 if (index < 0) {
1037 return;
1038 }
1039
1040 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1041 mSuspendedSessions.valueAt(index);
1042
1043 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001044 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001045 for (int j = 0; j < desc->mRefCount; j++) {
1046 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1047 chain->setEffectSuspendedAll_l(true);
1048 } else {
1049 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1050 desc->mType.timeLow);
1051 chain->setEffectSuspended_l(&desc->mType, true);
1052 }
1053 }
1054 }
1055}
1056
1057void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1058 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001059 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001060{
1061 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1062
1063 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1064
1065 if (suspend) {
1066 if (index >= 0) {
1067 sessionEffects = mSuspendedSessions.valueAt(index);
1068 } else {
1069 mSuspendedSessions.add(sessionId, sessionEffects);
1070 }
1071 } else {
1072 if (index < 0) {
1073 return;
1074 }
1075 sessionEffects = mSuspendedSessions.valueAt(index);
1076 }
1077
1078
1079 int key = EffectChain::kKeyForSuspendAll;
1080 if (type != NULL) {
1081 key = type->timeLow;
1082 }
1083 index = sessionEffects.indexOfKey(key);
1084
1085 sp<SuspendedSessionDesc> desc;
1086 if (suspend) {
1087 if (index >= 0) {
1088 desc = sessionEffects.valueAt(index);
1089 } else {
1090 desc = new SuspendedSessionDesc();
1091 if (type != NULL) {
1092 desc->mType = *type;
1093 }
1094 sessionEffects.add(key, desc);
1095 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1096 }
1097 desc->mRefCount++;
1098 } else {
1099 if (index < 0) {
1100 return;
1101 }
1102 desc = sessionEffects.valueAt(index);
1103 if (--desc->mRefCount == 0) {
1104 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1105 sessionEffects.removeItemsAt(index);
1106 if (sessionEffects.isEmpty()) {
1107 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1108 sessionId);
1109 mSuspendedSessions.removeItem(sessionId);
1110 }
1111 }
1112 }
1113 if (!sessionEffects.isEmpty()) {
1114 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1115 }
1116}
1117
1118void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1119 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001120 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001121{
1122 Mutex::Autolock _l(mLock);
1123 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1124}
1125
1126void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1127 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001128 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001129{
1130 if (mType != RECORD) {
1131 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1132 // another session. This gives the priority to well behaved effect control panels
1133 // and applications not using global effects.
1134 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1135 // global effects
1136 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1137 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1138 }
1139 }
1140
1141 sp<EffectChain> chain = getEffectChain_l(sessionId);
1142 if (chain != 0) {
1143 chain->checkSuspendOnEffectEnabled(effect, enabled);
1144 }
1145}
1146
Eric Laurent4c415062016-06-17 16:14:16 -07001147// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1148status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1149 const effect_descriptor_t *desc, audio_session_t sessionId)
1150{
1151 // No global effect sessions on record threads
1152 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1153 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1154 desc->name, mThreadName);
1155 return BAD_VALUE;
1156 }
1157 // only pre processing effects on record thread
1158 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1159 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1160 desc->name, mThreadName);
1161 return BAD_VALUE;
1162 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001163
1164 // always allow effects without processing load or latency
1165 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1166 return NO_ERROR;
1167 }
1168
Eric Laurent4c415062016-06-17 16:14:16 -07001169 audio_input_flags_t flags = mInput->flags;
1170 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1171 if (flags & AUDIO_INPUT_FLAG_RAW) {
1172 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1173 desc->name, mThreadName);
1174 return BAD_VALUE;
1175 }
1176 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1177 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1178 desc->name, mThreadName);
1179 return BAD_VALUE;
1180 }
1181 }
1182 return NO_ERROR;
1183}
1184
1185// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1186status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1187 const effect_descriptor_t *desc, audio_session_t sessionId)
1188{
1189 // no preprocessing on playback threads
1190 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1191 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1192 " thread %s", desc->name, mThreadName);
1193 return BAD_VALUE;
1194 }
1195
Eric Laurent3e4de772017-07-16 16:55:08 -07001196 // always allow effects without processing load or latency
1197 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1198 return NO_ERROR;
1199 }
1200
Eric Laurent4c415062016-06-17 16:14:16 -07001201 switch (mType) {
1202 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001203#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001204 // Reject any effect on mixer multichannel sinks.
1205 // TODO: fix both format and multichannel issues with effects.
1206 if (mChannelCount != FCC_2) {
1207 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1208 " thread %s", desc->name, mChannelCount, mThreadName);
1209 return BAD_VALUE;
1210 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001211#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001212 audio_output_flags_t flags = mOutput->flags;
1213 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1214 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1215 // global effects are applied only to non fast tracks if they are SW
1216 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1217 break;
1218 }
1219 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1220 // only post processing on output stage session
1221 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1222 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1223 " on output stage session", desc->name);
1224 return BAD_VALUE;
1225 }
1226 } else {
1227 // no restriction on effects applied on non fast tracks
1228 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1229 break;
1230 }
1231 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001232
Eric Laurent4c415062016-06-17 16:14:16 -07001233 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1234 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1235 desc->name);
1236 return BAD_VALUE;
1237 }
1238 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1239 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1240 " in fast mode", desc->name);
1241 return BAD_VALUE;
1242 }
1243 }
1244 } break;
1245 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001246 // nothing actionable on offload threads, if the effect:
1247 // - is offloadable: the effect can be created
1248 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1249 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001250 break;
1251 case DIRECT:
1252 // Reject any effect on Direct output threads for now, since the format of
1253 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1254 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1255 desc->name, mThreadName);
1256 return BAD_VALUE;
1257 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001258#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001259 // Reject any effect on mixer multichannel sinks.
1260 // TODO: fix both format and multichannel issues with effects.
1261 if (mChannelCount != FCC_2) {
1262 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1263 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1264 return BAD_VALUE;
1265 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001266#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001267 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1268 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1269 " thread %s", desc->name, mThreadName);
1270 return BAD_VALUE;
1271 }
1272 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1273 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1274 " DUPLICATING thread %s", desc->name, mThreadName);
1275 return BAD_VALUE;
1276 }
1277 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1278 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1279 " DUPLICATING thread %s", desc->name, mThreadName);
1280 return BAD_VALUE;
1281 }
1282 break;
1283 default:
1284 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1285 }
1286
1287 return NO_ERROR;
1288}
1289
Eric Laurent81784c32012-11-19 14:55:58 -08001290// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1291sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1292 const sp<AudioFlinger::Client>& client,
1293 const sp<IEffectClient>& effectClient,
1294 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001295 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001296 effect_descriptor_t *desc,
1297 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001298 status_t *status,
1299 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001300{
1301 sp<EffectModule> effect;
1302 sp<EffectHandle> handle;
1303 status_t lStatus;
1304 sp<EffectChain> chain;
1305 bool chainCreated = false;
1306 bool effectCreated = false;
1307 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001308 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001309
1310 lStatus = initCheck();
1311 if (lStatus != NO_ERROR) {
1312 ALOGW("createEffect_l() Audio driver not initialized.");
1313 goto Exit;
1314 }
1315
Eric Laurent81784c32012-11-19 14:55:58 -08001316 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1317
1318 { // scope for mLock
1319 Mutex::Autolock _l(mLock);
1320
Eric Laurent4c415062016-06-17 16:14:16 -07001321 lStatus = checkEffectCompatibility_l(desc, sessionId);
1322 if (lStatus != NO_ERROR) {
1323 goto Exit;
1324 }
1325
Eric Laurent81784c32012-11-19 14:55:58 -08001326 // check for existing effect chain with the requested audio session
1327 chain = getEffectChain_l(sessionId);
1328 if (chain == 0) {
1329 // create a new chain for this session
1330 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1331 chain = new EffectChain(this, sessionId);
1332 addEffectChain_l(chain);
1333 chain->setStrategy(getStrategyForSession_l(sessionId));
1334 chainCreated = true;
1335 } else {
1336 effect = chain->getEffectFromDesc_l(desc);
1337 }
1338
1339 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1340
1341 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001342 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001343 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001344 lStatus = AudioSystem::registerEffect(
1345 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001346 if (lStatus != NO_ERROR) {
1347 goto Exit;
1348 }
1349 effectRegistered = true;
1350 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001351 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001352 if (lStatus != NO_ERROR) {
1353 goto Exit;
1354 }
1355 effectCreated = true;
1356
1357 effect->setDevice(mOutDevice);
1358 effect->setDevice(mInDevice);
1359 effect->setMode(mAudioFlinger->getMode());
1360 effect->setAudioSource(mAudioSource);
1361 }
1362 // create effect handle and connect it to effect module
1363 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001364 lStatus = handle->initCheck();
1365 if (lStatus == OK) {
1366 lStatus = effect->addHandle(handle.get());
1367 }
Eric Laurent81784c32012-11-19 14:55:58 -08001368 if (enabled != NULL) {
1369 *enabled = (int)effect->isEnabled();
1370 }
1371 }
1372
1373Exit:
1374 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1375 Mutex::Autolock _l(mLock);
1376 if (effectCreated) {
1377 chain->removeEffect_l(effect);
1378 }
1379 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001380 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001381 }
1382 if (chainCreated) {
1383 removeEffectChain_l(chain);
1384 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001385 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001386 }
1387
Glenn Kasten9156ef32013-08-06 15:39:08 -07001388 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001389 return handle;
1390}
1391
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001392void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1393 bool unpinIfLast)
1394{
1395 bool remove = false;
1396 sp<EffectModule> effect;
1397 {
1398 Mutex::Autolock _l(mLock);
1399
1400 effect = handle->effect().promote();
1401 if (effect == 0) {
1402 return;
1403 }
1404 // restore suspended effects if the disconnected handle was enabled and the last one.
1405 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1406 if (remove) {
1407 removeEffect_l(effect, true);
1408 }
1409 }
1410 if (remove) {
1411 mAudioFlinger->updateOrphanEffectChains(effect);
1412 AudioSystem::unregisterEffect(effect->id());
1413 if (handle->enabled()) {
1414 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1415 }
1416 }
1417}
1418
Glenn Kastend848eb42016-03-08 13:42:11 -08001419sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1420 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001421{
1422 Mutex::Autolock _l(mLock);
1423 return getEffect_l(sessionId, effectId);
1424}
1425
Glenn Kastend848eb42016-03-08 13:42:11 -08001426sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1427 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001428{
1429 sp<EffectChain> chain = getEffectChain_l(sessionId);
1430 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1431}
1432
1433// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1434// PlaybackThread::mLock held
1435status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1436{
1437 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001438 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001439 sp<EffectChain> chain = getEffectChain_l(sessionId);
1440 bool chainCreated = false;
1441
Eric Laurent5baf2af2013-09-12 17:37:00 -07001442 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001443 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001444 this, effect->desc().name, effect->desc().flags);
1445
Eric Laurent81784c32012-11-19 14:55:58 -08001446 if (chain == 0) {
1447 // create a new chain for this session
1448 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1449 chain = new EffectChain(this, sessionId);
1450 addEffectChain_l(chain);
1451 chain->setStrategy(getStrategyForSession_l(sessionId));
1452 chainCreated = true;
1453 }
1454 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1455
1456 if (chain->getEffectFromId_l(effect->id()) != 0) {
1457 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1458 this, effect->desc().name, chain.get());
1459 return BAD_VALUE;
1460 }
1461
Eric Laurent5baf2af2013-09-12 17:37:00 -07001462 effect->setOffloaded(mType == OFFLOAD, mId);
1463
Eric Laurent81784c32012-11-19 14:55:58 -08001464 status_t status = chain->addEffect_l(effect);
1465 if (status != NO_ERROR) {
1466 if (chainCreated) {
1467 removeEffectChain_l(chain);
1468 }
1469 return status;
1470 }
1471
1472 effect->setDevice(mOutDevice);
1473 effect->setDevice(mInDevice);
1474 effect->setMode(mAudioFlinger->getMode());
1475 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001476
Eric Laurent81784c32012-11-19 14:55:58 -08001477 return NO_ERROR;
1478}
1479
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001480void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001481
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001482 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001483 effect_descriptor_t desc = effect->desc();
1484 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1485 detachAuxEffect_l(effect->id());
1486 }
1487
1488 sp<EffectChain> chain = effect->chain().promote();
1489 if (chain != 0) {
1490 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001491 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001492 removeEffectChain_l(chain);
1493 }
1494 } else {
1495 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1496 }
1497}
1498
1499void AudioFlinger::ThreadBase::lockEffectChains_l(
1500 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1501{
1502 effectChains = mEffectChains;
1503 for (size_t i = 0; i < mEffectChains.size(); i++) {
1504 mEffectChains[i]->lock();
1505 }
1506}
1507
1508void AudioFlinger::ThreadBase::unlockEffectChains(
1509 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1510{
1511 for (size_t i = 0; i < effectChains.size(); i++) {
1512 effectChains[i]->unlock();
1513 }
1514}
1515
Glenn Kastend848eb42016-03-08 13:42:11 -08001516sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001517{
1518 Mutex::Autolock _l(mLock);
1519 return getEffectChain_l(sessionId);
1520}
1521
Glenn Kastend848eb42016-03-08 13:42:11 -08001522sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1523 const
Eric Laurent81784c32012-11-19 14:55:58 -08001524{
1525 size_t size = mEffectChains.size();
1526 for (size_t i = 0; i < size; i++) {
1527 if (mEffectChains[i]->sessionId() == sessionId) {
1528 return mEffectChains[i];
1529 }
1530 }
1531 return 0;
1532}
1533
1534void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1535{
1536 Mutex::Autolock _l(mLock);
1537 size_t size = mEffectChains.size();
1538 for (size_t i = 0; i < size; i++) {
1539 mEffectChains[i]->setMode_l(mode);
1540 }
1541}
1542
Mikhail Naganovdc769682018-05-04 15:34:08 -07001543void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001544{
1545 config->type = AUDIO_PORT_TYPE_MIX;
1546 config->ext.mix.handle = mId;
1547 config->sample_rate = mSampleRate;
1548 config->format = mFormat;
1549 config->channel_mask = mChannelMask;
1550 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1551 AUDIO_PORT_CONFIG_FORMAT;
1552}
1553
Eric Laurent72e3f392015-05-20 14:43:50 -07001554void AudioFlinger::ThreadBase::systemReady()
1555{
1556 Mutex::Autolock _l(mLock);
1557 if (mSystemReady) {
1558 return;
1559 }
1560 mSystemReady = true;
1561
1562 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1563 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1564 }
1565 mPendingConfigEvents.clear();
1566}
1567
Andy Hungdae27702016-10-31 14:01:16 -07001568template <typename T>
1569ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1570 ssize_t index = mActiveTracks.indexOf(track);
1571 if (index >= 0) {
1572 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1573 return index;
1574 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001575 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001576 mActiveTracksGeneration++;
1577 mLatestActiveTrack = track;
1578 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001579 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001580 return mActiveTracks.add(track);
1581}
1582
1583template <typename T>
1584ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1585 ssize_t index = mActiveTracks.remove(track);
1586 if (index < 0) {
1587 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1588 return index;
1589 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001590 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001591 mActiveTracksGeneration++;
1592 --mBatteryCounter[track->uid()].second;
1593 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001594 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001595#ifdef TEE_SINK
1596 track->dumpTee(-1 /* fd */, "_REMOVE");
1597#endif
Andy Hungdae27702016-10-31 14:01:16 -07001598 return index;
1599}
1600
1601template <typename T>
1602void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1603 for (const sp<T> &track : mActiveTracks) {
1604 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001605 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001606 }
1607 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001608 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001609 mActiveTracks.clear();
1610 mLatestActiveTrack.clear();
1611 mBatteryCounter.clear();
1612}
1613
1614template <typename T>
1615void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1616 sp<ThreadBase> thread, bool force) {
1617 // Updates ActiveTracks client uids to the thread wakelock.
1618 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1619 thread->updateWakeLockUids_l(getWakeLockUids());
1620 mLastActiveTracksGeneration = mActiveTracksGeneration;
1621 }
1622
1623 // Updates BatteryNotifier uids
1624 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1625 const uid_t uid = it->first;
1626 ssize_t &previous = it->second.first;
1627 ssize_t &current = it->second.second;
1628 if (current > 0) {
1629 if (previous == 0) {
1630 BatteryNotifier::getInstance().noteStartAudio(uid);
1631 }
1632 previous = current;
1633 ++it;
1634 } else if (current == 0) {
1635 if (previous > 0) {
1636 BatteryNotifier::getInstance().noteStopAudio(uid);
1637 }
1638 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1639 } else /* (current < 0) */ {
1640 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1641 }
1642 }
1643}
Eric Laurent83b88082014-06-20 18:31:16 -07001644
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001645template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001646bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1647 const bool hasChanged = mHasChanged;
1648 mHasChanged = false;
1649 return hasChanged;
1650}
1651
1652template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001653void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1654 const char *funcName, const sp<T> &track) const {
1655 if (mLocalLog != nullptr) {
1656 String8 result;
1657 track->appendDump(result, false /* active */);
1658 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1659 }
1660}
1661
Eric Laurent6acd1d42017-01-04 14:23:29 -08001662void AudioFlinger::ThreadBase::broadcast_l()
1663{
1664 // Thread could be blocked waiting for async
1665 // so signal it to handle state changes immediately
1666 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1667 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1668 mSignalPending = true;
1669 mWaitWorkCV.broadcast();
1670}
1671
Eric Laurent81784c32012-11-19 14:55:58 -08001672// ----------------------------------------------------------------------------
1673// Playback
1674// ----------------------------------------------------------------------------
1675
1676AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1677 AudioStreamOut* output,
1678 audio_io_handle_t id,
1679 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001680 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001681 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001682 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001683 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001684 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001685 mMixerBuffer(NULL),
1686 mMixerBufferSize(0),
1687 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1688 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001689 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001690 mEffectBuffer(NULL),
1691 mEffectBufferSize(0),
1692 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1693 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001694 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001695 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001696 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001697 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001698 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001699 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001700 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001701 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001702 mMixerStatus(MIXER_IDLE),
1703 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001704 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001705 mBytesRemaining(0),
1706 mCurrentWriteLength(0),
1707 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001708 mWriteAckSequence(0),
1709 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001710 mScreenState(AudioFlinger::mScreenState),
1711 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001712 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001713 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1714 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001715{
Glenn Kastend7dca052015-03-05 16:05:54 -08001716 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1717 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001718
1719 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1720 // it would be safer to explicitly pass initial masterVolume/masterMute as
1721 // parameter.
1722 //
1723 // If the HAL we are using has support for master volume or master mute,
1724 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1725 // and the mute set to false).
1726 mMasterVolume = audioFlinger->masterVolume_l();
1727 mMasterMute = audioFlinger->masterMute_l();
1728 if (mOutput && mOutput->audioHwDev) {
1729 if (mOutput->audioHwDev->canSetMasterVolume()) {
1730 mMasterVolume = 1.0;
1731 }
1732
1733 if (mOutput->audioHwDev->canSetMasterMute()) {
1734 mMasterMute = false;
1735 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001736 mIsMsdDevice = strcmp(
1737 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001738 }
1739
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001740 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001741
Andy Hungc8fddf32018-08-08 18:32:37 -07001742 // TODO: We may also match on address as well as device type for
1743 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
1744 if (type == MIXER || type == DIRECT) {
1745 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
1746 "audio.timestamp.corrected_output_devices",
1747 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1748 : AUDIO_DEVICE_NONE));
1749 }
1750
Eric Laurent223fd5c2014-11-11 13:43:36 -08001751 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001752 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001753 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001754 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001755 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1756 }
Eric Laurent98e38192018-02-15 18:31:53 -08001757 // Audio patch volume is always max
1758 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1759 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001760}
1761
1762AudioFlinger::PlaybackThread::~PlaybackThread()
1763{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001764 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001765 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001766 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001767 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001768}
1769
1770void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1771{
1772 dumpInternals(fd, args);
1773 dumpTracks(fd, args);
1774 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001775 dprintf(fd, " Local log:\n");
1776 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001777}
1778
Eric Tan1882f162018-08-02 18:05:39 -07001779Json::Value AudioFlinger::PlaybackThread::getJsonDump() const
Eric Tan7b651152018-07-13 10:17:19 -07001780{
Eric Tan1882f162018-08-02 18:05:39 -07001781 return Json::Value(Json::objectValue);
Eric Tan7b651152018-07-13 10:17:19 -07001782}
1783
Glenn Kasten0f11b512014-01-31 16:18:54 -08001784void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001785{
Eric Laurent81784c32012-11-19 14:55:58 -08001786 String8 result;
1787
Marco Nelissenb2208842014-02-07 14:00:50 -08001788 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001789 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1790 const stream_type_t *st = &mStreamTypes[i];
1791 if (i > 0) {
1792 result.appendFormat(", ");
1793 }
1794 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1795 if (st->mute) {
1796 result.append("M");
1797 }
1798 }
1799 result.append("\n");
1800 write(fd, result.string(), result.length());
1801 result.clear();
1802
Eric Laurent81784c32012-11-19 14:55:58 -08001803 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1804 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001805 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001806 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001807
1808 size_t numtracks = mTracks.size();
1809 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001810 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001811 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001812 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001813 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001814 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001815 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001816 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001817 for (size_t i = 0; i < numtracks; ++i) {
1818 sp<Track> track = mTracks[i];
1819 if (track != 0) {
1820 bool active = mActiveTracks.indexOf(track) >= 0;
1821 if (active) {
1822 numactiveseen++;
1823 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001824 result.append(prefix);
1825 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001826 }
1827 }
1828 } else {
1829 result.append("\n");
1830 }
1831 if (numactiveseen != numactive) {
1832 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001833 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001834 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001835 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001836 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001837 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001838 sp<Track> track = mActiveTracks[i];
1839 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001840 result.append(prefix);
1841 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001842 }
1843 }
1844 }
1845
1846 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001847}
1848
1849void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1850{
Glenn Kasten44182c22015-03-05 17:12:23 -08001851 dumpBase(fd, args);
1852
Elliott Hughes87cebad2014-05-22 10:14:43 -07001853 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001854 dprintf(fd, " Last write occurred (msecs): %llu\n",
1855 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001856 dprintf(fd, " Total writes: %d\n", mNumWrites);
1857 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1858 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1859 dprintf(fd, " Suspend count: %d\n", mSuspended);
1860 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1861 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1862 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1863 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001864 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001865 AudioStreamOut *output = mOutput;
1866 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001867 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1868 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001869 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1870 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1871 if (mPipeSink.get() != nullptr) {
1872 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1873 }
1874 if (output != nullptr) {
1875 dprintf(fd, " Hal stream dump:\n");
1876 (void)output->stream->dump(fd);
1877 }
Eric Laurent81784c32012-11-19 14:55:58 -08001878}
1879
1880// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001881
1882void AudioFlinger::PlaybackThread::onFirstRef()
1883{
Glenn Kastend7dca052015-03-05 16:05:54 -08001884 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001885}
1886
1887// ThreadBase virtuals
1888void AudioFlinger::PlaybackThread::preExit()
1889{
1890 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001891 // FIXME this is using hard-coded strings but in the future, this functionality will be
1892 // converted to use audio HAL extensions required to support tunneling
1893 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1894 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001895}
1896
1897// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1898sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1899 const sp<AudioFlinger::Client>& client,
1900 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001901 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001902 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001903 audio_format_t format,
1904 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001905 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001906 size_t *pNotificationFrameCount,
1907 uint32_t notificationsPerBuffer,
1908 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001909 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001910 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001911 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001912 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001913 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001914 status_t *status,
1915 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001916{
Glenn Kasten74935e42013-12-19 08:56:45 -08001917 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001918 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001919 sp<Track> track;
1920 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001921 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001922 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001923 uint32_t sampleRate;
1924
1925 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1926 lStatus = BAD_VALUE;
1927 goto Exit;
1928 }
Eric Laurent21da6472017-11-09 16:29:26 -08001929
1930 if (*pSampleRate == 0) {
1931 *pSampleRate = mSampleRate;
1932 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001933 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001934
1935 // special case for FAST flag considered OK if fast mixer is present
1936 if (hasFastMixer()) {
1937 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1938 }
1939
1940 // Check if requested flags are compatible with output stream flags
1941 if ((*flags & outputFlags) != *flags) {
1942 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1943 *flags, outputFlags);
1944 *flags = (audio_output_flags_t)(*flags & outputFlags);
1945 }
Eric Laurent81784c32012-11-19 14:55:58 -08001946
Eric Laurent81784c32012-11-19 14:55:58 -08001947 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001948 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001949 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001950 // PCM data
1951 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001952 // TODO: extract as a data library function that checks that a computationally
1953 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001954 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001955 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1956 (channelMask == AUDIO_CHANNEL_OUT_MONO
1957 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001958 // hardware sample rate
1959 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001960 // normal mixer has an associated fast mixer
1961 hasFastMixer() &&
1962 // there are sufficient fast track slots available
1963 (mFastTrackAvailMask != 0)
1964 // FIXME test that MixerThread for this fast track has a capable output HAL
1965 // FIXME add a permission test also?
1966 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001967 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1968 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001969 // read the fast track multiplier property the first time it is needed
1970 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1971 if (ok != 0) {
1972 ALOGE("%s pthread_once failed: %d", __func__, ok);
1973 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001974 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001975 }
Eric Laurent4c415062016-06-17 16:14:16 -07001976
1977 // check compatibility with audio effects.
1978 { // scope for mLock
1979 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001980 for (audio_session_t session : {
1981 AUDIO_SESSION_OUTPUT_STAGE,
1982 AUDIO_SESSION_OUTPUT_MIX,
1983 sessionId,
1984 }) {
1985 sp<EffectChain> chain = getEffectChain_l(session);
1986 if (chain.get() != nullptr) {
1987 audio_output_flags_t old = *flags;
1988 chain->checkOutputFlagCompatibility(flags);
1989 if (old != *flags) {
1990 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1991 (int)session, (int)old, (int)*flags);
1992 }
Eric Laurent4c415062016-06-17 16:14:16 -07001993 }
1994 }
1995 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001996 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001997 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1998 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001999 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002000 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2001 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002002 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002003 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002004 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002005 audio_is_linear_pcm(format),
2006 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002007 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002008 }
2009 }
Eric Laurent21da6472017-11-09 16:29:26 -08002010
2011 if (!audio_has_proportional_frames(format)) {
2012 if (sharedBuffer != 0) {
2013 // Same comment as below about ignoring frameCount parameter for set()
2014 frameCount = sharedBuffer->size();
2015 } else if (frameCount == 0) {
2016 frameCount = mNormalFrameCount;
2017 }
2018 if (notificationFrameCount != frameCount) {
2019 notificationFrameCount = frameCount;
2020 }
2021 } else if (sharedBuffer != 0) {
2022 // FIXME: Ensure client side memory buffers need
2023 // not have additional alignment beyond sample
2024 // (e.g. 16 bit stereo accessed as 32 bit frame).
2025 size_t alignment = audio_bytes_per_sample(format);
2026 if (alignment & 1) {
2027 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2028 alignment = 1;
2029 }
2030 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2031 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2032 if (channelCount > 1) {
2033 // More than 2 channels does not require stronger alignment than stereo
2034 alignment <<= 1;
2035 }
2036 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2037 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2038 sharedBuffer->pointer(), channelCount);
2039 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002040 goto Exit;
2041 }
Eric Laurent21da6472017-11-09 16:29:26 -08002042
2043 // When initializing a shared buffer AudioTrack via constructors,
2044 // there's no frameCount parameter.
2045 // But when initializing a shared buffer AudioTrack via set(),
2046 // there _is_ a frameCount parameter. We silently ignore it.
2047 frameCount = sharedBuffer->size() / frameSize;
2048 } else {
2049 size_t minFrameCount = 0;
2050 // For fast tracks we try to respect the application's request for notifications per buffer.
2051 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2052 if (notificationsPerBuffer > 0) {
2053 // Avoid possible arithmetic overflow during multiplication.
2054 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2055 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2056 notificationsPerBuffer, mFrameCount);
2057 } else {
2058 minFrameCount = mFrameCount * notificationsPerBuffer;
2059 }
2060 }
2061 } else {
2062 // For normal PCM streaming tracks, update minimum frame count.
2063 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2064 // cover audio hardware latency.
2065 // This is probably too conservative, but legacy application code may depend on it.
2066 // If you change this calculation, also review the start threshold which is related.
2067 uint32_t latencyMs = latency_l();
2068 if (latencyMs == 0) {
2069 ALOGE("Error when retrieving output stream latency");
2070 lStatus = UNKNOWN_ERROR;
2071 goto Exit;
2072 }
2073
2074 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2075 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2076
Eric Laurent81784c32012-11-19 14:55:58 -08002077 }
Eric Laurent21da6472017-11-09 16:29:26 -08002078 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002079 frameCount = minFrameCount;
2080 }
Eric Laurent81784c32012-11-19 14:55:58 -08002081 }
Eric Laurent21da6472017-11-09 16:29:26 -08002082
2083 // Make sure that application is notified with sufficient margin before underrun.
2084 // The client can divide the AudioTrack buffer into sub-buffers,
2085 // and expresses its desire to server as the notification frame count.
2086 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2087 size_t maxNotificationFrames;
2088 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2089 // notify every HAL buffer, regardless of the size of the track buffer
2090 maxNotificationFrames = mFrameCount;
2091 } else {
2092 // For normal tracks, use at least double-buffering if no sample rate conversion,
2093 // or at least triple-buffering if there is sample rate conversion
2094 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2095 maxNotificationFrames = frameCount / nBuffering;
2096 // If client requested a fast track but this was denied, then use the smaller maximum.
2097 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2098 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2099 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2100 maxNotificationFrames = maxNotificationFramesFastDenied;
2101 }
2102 }
2103 }
2104 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2105 if (notificationFrameCount == 0) {
2106 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2107 maxNotificationFrames, frameCount);
2108 } else {
2109 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2110 notificationFrameCount, maxNotificationFrames, frameCount);
2111 }
2112 notificationFrameCount = maxNotificationFrames;
2113 }
2114 }
2115
Glenn Kasten74935e42013-12-19 08:56:45 -08002116 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002117 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002118
Glenn Kastenc3df8382014-03-13 15:05:25 -07002119 switch (mType) {
2120
2121 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002122 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002123 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002124 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2125 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002126 sampleRate, format, channelMask, mOutput, mFormat);
2127 lStatus = BAD_VALUE;
2128 goto Exit;
2129 }
2130 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002131 break;
2132
2133 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002134 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002135 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2136 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002137 sampleRate, format, channelMask, mOutput, mFormat);
2138 lStatus = BAD_VALUE;
2139 goto Exit;
2140 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002141 break;
2142
2143 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002144 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002145 ALOGE("createTrack_l() Bad parameter: format %#x \""
2146 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002147 format, mOutput, mFormat);
2148 lStatus = BAD_VALUE;
2149 goto Exit;
2150 }
Andy Hungcd044842014-08-07 11:04:34 -07002151 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002152 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2153 lStatus = BAD_VALUE;
2154 goto Exit;
2155 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002156 break;
2157
Eric Laurent81784c32012-11-19 14:55:58 -08002158 }
2159
2160 lStatus = initCheck();
2161 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002162 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002163 goto Exit;
2164 }
2165
2166 { // scope for mLock
2167 Mutex::Autolock _l(mLock);
2168
2169 // all tracks in same audio session must share the same routing strategy otherwise
2170 // conflicts will happen when tracks are moved from one output to another by audio policy
2171 // manager
2172 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2173 for (size_t i = 0; i < mTracks.size(); ++i) {
2174 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002175 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002176 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2177 if (sessionId == t->sessionId() && strategy != actual) {
2178 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2179 strategy, actual);
2180 lStatus = BAD_VALUE;
2181 goto Exit;
2182 }
2183 }
2184 }
2185
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002186 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002187 channelMask, frameCount,
2188 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002189 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002190
Glenn Kasten03003332013-08-06 15:40:54 -07002191 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2192 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002193 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002194 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002195 goto Exit;
2196 }
2197 mTracks.add(track);
2198
2199 sp<EffectChain> chain = getEffectChain_l(sessionId);
2200 if (chain != 0) {
2201 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2202 track->setMainBuffer(chain->inBuffer());
2203 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2204 chain->incTrackCnt();
2205 }
2206
Eric Laurent05067782016-06-01 18:27:28 -07002207 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002208 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2209 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2210 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002211 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002212 }
2213 }
2214
2215 lStatus = NO_ERROR;
2216
2217Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002218 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002219 return track;
2220}
2221
Andy Hung1bc088a2018-02-09 15:57:31 -08002222template<typename T>
2223ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track)
2224{
2225 const ssize_t index = mTracks.add(track);
2226 if (index >= 0) {
2227 // set name for track when adding.
2228 int name;
2229 if (mUnusedTrackNames.empty()) {
2230 name = mTracks.size() - 1; // new name {0 ... size-1}.
2231 } else {
2232 // reuse smallest name for deleted track.
2233 auto it = mUnusedTrackNames.begin();
2234 name = *it;
2235 (void)mUnusedTrackNames.erase(it);
2236 }
2237 track->setName(name);
2238 } else {
2239 LOG_ALWAYS_FATAL("cannot add track");
2240 }
2241 return index;
2242}
2243
2244template<typename T>
2245ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2246{
2247 const int name = track->name();
2248 const ssize_t index = mTracks.remove(track);
2249 if (index >= 0) {
2250 // invalidate name when removing from mTracks.
2251 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name);
2252
2253 if (mSaveDeletedTrackNames) {
2254 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2255 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update,
2256 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2257 mDeletedTrackNames.emplace(name);
2258 }
2259
2260 mUnusedTrackNames.emplace(name);
2261 track->setName(T::TRACK_NAME_PENDING);
2262 } else {
2263 LOG_ALWAYS_FATAL_IF(name >= 0,
2264 "valid name %d for track not in mTracks (returned %zd)", name, index);
2265 }
2266 return index;
2267}
2268
Eric Laurent81784c32012-11-19 14:55:58 -08002269uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2270{
2271 return latency;
2272}
2273
2274uint32_t AudioFlinger::PlaybackThread::latency() const
2275{
2276 Mutex::Autolock _l(mLock);
2277 return latency_l();
2278}
2279uint32_t AudioFlinger::PlaybackThread::latency_l() const
2280{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002281 uint32_t latency;
2282 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2283 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002284 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002285 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002286}
2287
2288void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2289{
2290 Mutex::Autolock _l(mLock);
2291 // Don't apply master volume in SW if our HAL can do it for us.
2292 if (mOutput && mOutput->audioHwDev &&
2293 mOutput->audioHwDev->canSetMasterVolume()) {
2294 mMasterVolume = 1.0;
2295 } else {
2296 mMasterVolume = value;
2297 }
2298}
2299
2300void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2301{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002302 if (isDuplicating()) {
2303 return;
2304 }
Eric Laurent81784c32012-11-19 14:55:58 -08002305 Mutex::Autolock _l(mLock);
2306 // Don't apply master mute in SW if our HAL can do it for us.
2307 if (mOutput && mOutput->audioHwDev &&
2308 mOutput->audioHwDev->canSetMasterMute()) {
2309 mMasterMute = false;
2310 } else {
2311 mMasterMute = muted;
2312 }
2313}
2314
2315void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2316{
2317 Mutex::Autolock _l(mLock);
2318 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002319 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002320}
2321
2322void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2323{
2324 Mutex::Autolock _l(mLock);
2325 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002326 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002327}
2328
2329float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2330{
2331 Mutex::Autolock _l(mLock);
2332 return mStreamTypes[stream].volume;
2333}
2334
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002335void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2336{
2337 mOutput->stream->setVolume(left, right);
2338}
2339
Eric Laurent81784c32012-11-19 14:55:58 -08002340// addTrack_l() must be called with ThreadBase::mLock held
2341status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2342{
2343 status_t status = ALREADY_EXISTS;
2344
Eric Laurent81784c32012-11-19 14:55:58 -08002345 if (mActiveTracks.indexOf(track) < 0) {
2346 // the track is newly added, make sure it fills up all its
2347 // buffers before playing. This is to ensure the client will
2348 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002349 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002350 TrackBase::track_state state = track->mState;
2351 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002352 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002353 mLock.lock();
2354 // abort track was stopped/paused while we released the lock
2355 if (state != track->mState) {
2356 if (status == NO_ERROR) {
2357 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002358 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002359 mLock.lock();
2360 }
2361 return INVALID_OPERATION;
2362 }
2363 // abort if start is rejected by audio policy manager
2364 if (status != NO_ERROR) {
2365 return PERMISSION_DENIED;
2366 }
2367#ifdef ADD_BATTERY_DATA
2368 // to track the speaker usage
2369 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2370#endif
2371 }
2372
Eric Laurent51716182016-02-29 18:00:56 -08002373 // set retry count for buffer fill
2374 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002375 if (track->isStopping_1()) {
2376 track->mRetryCount = kMaxTrackStopRetriesOffload;
2377 } else {
2378 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2379 }
2380 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002381 } else {
2382 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002383 track->mFillingUpStatus =
2384 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002385 }
2386
Eric Laurent81784c32012-11-19 14:55:58 -08002387 track->mResetDone = false;
2388 track->mPresentationCompleteFrames = 0;
2389 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002390 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2391 if (chain != 0) {
2392 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2393 track->sessionId());
2394 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002395 }
2396
2397 status = NO_ERROR;
2398 }
2399
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002400 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002401 return status;
2402}
2403
Eric Laurentbfb1b832013-01-07 09:53:42 -08002404bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002405{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002406 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002407 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002408 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2409 track->mState = TrackBase::STOPPED;
2410 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002411 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002412 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002413 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002414 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002415
2416 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002417}
2418
2419void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2420{
2421 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002422
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002423 String8 result;
2424 track->appendDump(result, false /* active */);
2425 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002426
Eric Laurent81784c32012-11-19 14:55:58 -08002427 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002428 if (track->isFastTrack()) {
2429 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002430 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002431 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2432 mFastTrackAvailMask |= 1 << index;
2433 // redundant as track is about to be destroyed, for dumpsys only
2434 track->mFastIndex = -1;
2435 }
2436 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2437 if (chain != 0) {
2438 chain->decTrackCnt();
2439 }
2440}
2441
2442String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2443{
Eric Laurent81784c32012-11-19 14:55:58 -08002444 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002445 String8 out_s8;
2446 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2447 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002448 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002449 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002450}
2451
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002452void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002453 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2454 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002455
Eric Laurent73e26b62015-04-27 16:55:58 -07002456 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002457
2458 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002459 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002460 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002461 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002462 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002463 desc->mChannelMask = mChannelMask;
2464 desc->mSamplingRate = mSampleRate;
2465 desc->mFormat = mFormat;
2466 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002467 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002468 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002469 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002470 break;
2471
Eric Laurent73e26b62015-04-27 16:55:58 -07002472 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002473 default:
2474 break;
2475 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002476 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002477}
2478
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002479void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002480{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002481 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002482}
2483
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002484void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002485{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002486 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002487}
2488
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002489void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002490{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002491 mCallbackThread->setAsyncError();
2492}
2493
Eric Laurent3b4529e2013-09-05 18:09:19 -07002494void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495{
2496 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002497 // reject out of sequence requests
2498 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2499 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002500 mWaitWorkCV.signal();
2501 }
2502}
2503
Eric Laurent3b4529e2013-09-05 18:09:19 -07002504void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002505{
2506 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002507 // reject out of sequence requests
2508 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002509 // Register discontinuity when HW drain is completed because that can cause
2510 // the timestamp frame position to reset to 0 for direct and offload threads.
2511 // (Out of sequence requests are ignored, since the discontinuity would be handled
2512 // elsewhere, e.g. in flush).
2513 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002514 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002515 mWaitWorkCV.signal();
2516 }
2517}
2518
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002519void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002520{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002521 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002522 mSampleRate = mOutput->getSampleRate();
2523 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002524 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002525 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002526 }
Andy Hung9a592762014-07-21 21:56:01 -07002527 if ((mType == MIXER || mType == DUPLICATING)
2528 && !isValidPcmSinkChannelMask(mChannelMask)) {
2529 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2530 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002531 }
Andy Hunge5412692014-05-16 11:25:07 -07002532 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002533
2534 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002535 status_t result = mOutput->stream->getFormat(&mHALFormat);
2536 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002537 // Get format from the shim, which will be different than the HAL format
2538 // if playing compressed audio over HDMI passthrough.
2539 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002540 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002541 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002542 }
Andy Hung6146c082014-03-18 11:56:15 -07002543 if ((mType == MIXER || mType == DUPLICATING)
2544 && !isValidPcmSinkFormat(mFormat)) {
2545 LOG_FATAL("HAL format %#x not supported for mixed output",
2546 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002547 }
Phil Burk062e67a2015-02-11 13:40:50 -08002548 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002549 result = mOutput->stream->getBufferSize(&mBufferSize);
2550 LOG_ALWAYS_FATAL_IF(result != OK,
2551 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002552 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002553 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002554 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002555 mFrameCount);
2556 }
2557
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002558 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2559 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002561 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002562 }
2563 }
2564
Eric Laurentd1f69b02014-12-15 14:33:13 -08002565 mHwSupportsPause = false;
2566 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002567 bool supportsPause = false, supportsResume = false;
2568 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2569 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002570 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002571 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002572 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002573 } else if (supportsResume) {
2574 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002575 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002576 }
2577 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002578 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2579 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2580 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002581
Andy Hungfbfc3952015-01-15 13:33:51 -08002582 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2583 // For best precision, we use float instead of the associated output
2584 // device format (typically PCM 16 bit).
2585
2586 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2587 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2588 mBufferSize = mFrameSize * mFrameCount;
2589
2590 // TODO: We currently use the associated output device channel mask and sample rate.
2591 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2592 // (if a valid mask) to avoid premature downmix.
2593 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2594 // instead of the output device sample rate to avoid loss of high frequency information.
2595 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2596 }
2597
Andy Hung09a50072014-02-27 14:30:47 -08002598 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002599 double multiplier = 1.0;
2600 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2601 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002602 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2603 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002604
Eric Laurent81784c32012-11-19 14:55:58 -08002605 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2606 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2607 maxNormalFrameCount = maxNormalFrameCount & ~15;
2608 if (maxNormalFrameCount < minNormalFrameCount) {
2609 maxNormalFrameCount = minNormalFrameCount;
2610 }
2611 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2612 if (multiplier <= 1.0) {
2613 multiplier = 1.0;
2614 } else if (multiplier <= 2.0) {
2615 if (2 * mFrameCount <= maxNormalFrameCount) {
2616 multiplier = 2.0;
2617 } else {
2618 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2619 }
2620 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002621 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002622 }
2623 }
2624 mNormalFrameCount = multiplier * mFrameCount;
2625 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002626 if (mType == MIXER || mType == DUPLICATING) {
2627 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2628 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002629 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002630 mNormalFrameCount);
2631
Andy Hung08fb1742015-05-31 23:22:10 -07002632 // Check if we want to throttle the processing to no more than 2x normal rate
2633 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002634 mThreadThrottleTimeMs = 0;
2635 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002636 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2637
Andy Hung010a1a12014-03-13 13:57:33 -07002638 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2639 // Originally this was int16_t[] array, need to remove legacy implications.
2640 free(mSinkBuffer);
2641 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002642 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2643 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2644 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002645 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002646
Andy Hung69aed5f2014-02-25 17:24:40 -08002647 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2648 // drives the output.
2649 free(mMixerBuffer);
2650 mMixerBuffer = NULL;
2651 if (mMixerBufferEnabled) {
2652 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2653 mMixerBufferSize = mNormalFrameCount * mChannelCount
2654 * audio_bytes_per_sample(mMixerBufferFormat);
2655 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2656 }
Andy Hung98ef9782014-03-04 14:46:50 -08002657 free(mEffectBuffer);
2658 mEffectBuffer = NULL;
2659 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002660 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002661 mEffectBufferSize = mNormalFrameCount * mChannelCount
2662 * audio_bytes_per_sample(mEffectBufferFormat);
2663 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2664 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002665
Eric Laurent81784c32012-11-19 14:55:58 -08002666 // force reconfiguration of effect chains and engines to take new buffer size and audio
2667 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002668 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002669 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2670 // matter.
2671 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2672 Vector< sp<EffectChain> > effectChains = mEffectChains;
2673 for (size_t i = 0; i < effectChains.size(); i ++) {
2674 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2675 }
2676}
2677
Kevin Rocard069c2712018-03-29 19:09:14 -07002678void AudioFlinger::PlaybackThread::updateMetadata_l()
2679{
Kevin Rocard12381092018-04-11 09:19:59 -07002680 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2681 return; // That should not happen
2682 }
2683 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2684 for (const sp<Track> &track : mActiveTracks) {
2685 // Do not short-circuit as all hasChanged states must be reset
2686 // as all the metadata are going to be sent
2687 hasChanged |= track->readAndClearHasChanged();
2688 }
2689 if (!hasChanged) {
2690 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002691 }
2692 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002693 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002694 for (const sp<Track> &track : mActiveTracks) {
2695 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002696 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002697 }
Kevin Rocard12381092018-04-11 09:19:59 -07002698 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002699}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002700
Kevin Rocard12381092018-04-11 09:19:59 -07002701void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2702 const StreamOutHalInterface::SourceMetadata& metadata)
2703{
2704 mOutput->stream->updateSourceMetadata(metadata);
2705};
2706
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002707status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002708{
2709 if (halFrames == NULL || dspFrames == NULL) {
2710 return BAD_VALUE;
2711 }
2712 Mutex::Autolock _l(mLock);
2713 if (initCheck() != NO_ERROR) {
2714 return INVALID_OPERATION;
2715 }
Andy Hung818e7a32016-02-16 18:08:07 -08002716 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002717 *halFrames = framesWritten;
2718
2719 if (isSuspended()) {
2720 // return an estimation of rendered frames when the output is suspended
2721 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002722 *dspFrames = (uint32_t)
2723 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002724 return NO_ERROR;
2725 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002726 status_t status;
2727 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002728 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002729 *dspFrames = (size_t)frames;
2730 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002731 }
2732}
2733
Eric Laurent4c415062016-06-17 16:14:16 -07002734// hasAudioSession_l() must be called with ThreadBase::mLock held
2735uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002736{
Eric Laurent81784c32012-11-19 14:55:58 -08002737 uint32_t result = 0;
2738 if (getEffectChain_l(sessionId) != 0) {
2739 result = EFFECT_SESSION;
2740 }
2741
2742 for (size_t i = 0; i < mTracks.size(); ++i) {
2743 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002744 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002745 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002746 if (track->isFastTrack()) {
2747 result |= FAST_SESSION;
2748 }
Eric Laurent81784c32012-11-19 14:55:58 -08002749 break;
2750 }
2751 }
2752
2753 return result;
2754}
2755
Glenn Kastend848eb42016-03-08 13:42:11 -08002756uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002757{
2758 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2759 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2760 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2761 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2762 }
2763 for (size_t i = 0; i < mTracks.size(); i++) {
2764 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002765 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002766 return AudioSystem::getStrategyForStream(track->streamType());
2767 }
2768 }
2769 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2770}
2771
2772
Phil Burk062e67a2015-02-11 13:40:50 -08002773AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002774{
2775 Mutex::Autolock _l(mLock);
2776 return mOutput;
2777}
2778
Phil Burk062e67a2015-02-11 13:40:50 -08002779AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002780{
2781 Mutex::Autolock _l(mLock);
2782 AudioStreamOut *output = mOutput;
2783 mOutput = NULL;
2784 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2785 // must push a NULL and wait for ack
2786 mOutputSink.clear();
2787 mPipeSink.clear();
2788 mNormalSink.clear();
2789 return output;
2790}
2791
2792// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002793sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002794{
2795 if (mOutput == NULL) {
2796 return NULL;
2797 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002798 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002799}
2800
2801uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2802{
2803 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2804}
2805
2806status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2807{
2808 if (!isValidSyncEvent(event)) {
2809 return BAD_VALUE;
2810 }
2811
2812 Mutex::Autolock _l(mLock);
2813
2814 for (size_t i = 0; i < mTracks.size(); ++i) {
2815 sp<Track> track = mTracks[i];
2816 if (event->triggerSession() == track->sessionId()) {
2817 (void) track->setSyncEvent(event);
2818 return NO_ERROR;
2819 }
2820 }
2821
2822 return NAME_NOT_FOUND;
2823}
2824
2825bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2826{
2827 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2828}
2829
2830void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2831 const Vector< sp<Track> >& tracksToRemove)
2832{
2833 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002834 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002835 for (size_t i = 0 ; i < count ; i++) {
2836 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002837 if (track->isExternalTrack()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07002838 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002839#ifdef ADD_BATTERY_DATA
2840 // to track the speaker usage
2841 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2842#endif
2843 if (track->isTerminated()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07002844 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002845 }
Eric Laurent81784c32012-11-19 14:55:58 -08002846 }
2847 }
2848 }
Eric Laurent81784c32012-11-19 14:55:58 -08002849}
2850
2851void AudioFlinger::PlaybackThread::checkSilentMode_l()
2852{
2853 if (!mMasterMute) {
2854 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002855 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2856 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2857 return;
2858 }
Eric Laurent81784c32012-11-19 14:55:58 -08002859 if (property_get("ro.audio.silent", value, "0") > 0) {
2860 char *endptr;
2861 unsigned long ul = strtoul(value, &endptr, 0);
2862 if (*endptr == '\0' && ul != 0) {
2863 ALOGD("Silence is golden");
2864 // The setprop command will not allow a property to be changed after
2865 // the first time it is set, so we don't have to worry about un-muting.
2866 setMasterMute_l(true);
2867 }
2868 }
2869 }
2870}
2871
2872// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002873ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002874{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002875 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002876 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002877 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002878 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002879
2880 // If an NBAIO sink is present, use it to write the normal mixer's submix
2881 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002882
Andy Hung010a1a12014-03-13 13:57:33 -07002883 const size_t count = mBytesRemaining / mFrameSize;
2884
Simon Wilson2d590962012-11-29 15:18:50 -08002885 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002886 // update the setpoint when AudioFlinger::mScreenState changes
2887 uint32_t screenState = AudioFlinger::mScreenState;
2888 if (screenState != mScreenState) {
2889 mScreenState = screenState;
2890 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2891 if (pipe != NULL) {
2892 pipe->setAvgFrames((mScreenState & 1) ?
2893 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2894 }
2895 }
Andy Hung010a1a12014-03-13 13:57:33 -07002896 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002897 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002898 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002899 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002900#ifdef TEE_SINK
2901 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2902#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002903 } else {
2904 bytesWritten = framesWritten;
2905 }
2906 // otherwise use the HAL / AudioStreamOut directly
2907 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002909
Eric Laurentbfb1b832013-01-07 09:53:42 -08002910 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002911 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2912 mWriteAckSequence += 2;
2913 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002915 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002916 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002917 // FIXME We should have an implementation of timestamps for direct output threads.
2918 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002919 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002920
Eric Laurentbfb1b832013-01-07 09:53:42 -08002921 if (mUseAsyncWrite &&
2922 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2923 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002924 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002925 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002926 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002927 }
Eric Laurent81784c32012-11-19 14:55:58 -08002928 }
2929
Eric Laurent81784c32012-11-19 14:55:58 -08002930 mNumWrites++;
2931 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002932 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002933 return bytesWritten;
2934}
2935
2936void AudioFlinger::PlaybackThread::threadLoop_drain()
2937{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002938 bool supportsDrain = false;
2939 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002940 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2941 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002942 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2943 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002944 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002945 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002946 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002947 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002948 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002949 }
2950}
2951
2952void AudioFlinger::PlaybackThread::threadLoop_exit()
2953{
Eric Laurent275e8e92014-11-30 15:14:47 -08002954 {
2955 Mutex::Autolock _l(mLock);
2956 for (size_t i = 0; i < mTracks.size(); i++) {
2957 sp<Track> track = mTracks[i];
2958 track->invalidate();
2959 }
Andy Hungdae27702016-10-31 14:01:16 -07002960 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2961 // After we exit there are no more track changes sent to BatteryNotifier
2962 // because that requires an active threadLoop.
2963 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2964 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002965 }
Eric Laurent81784c32012-11-19 14:55:58 -08002966}
2967
2968/*
2969The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002970 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002971 - mActiveSleepTimeUs from activeSleepTimeUs()
2972 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002973 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2974 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002975 - maxPeriod from frame count and sample rate (MIXER only)
2976
2977The parameters that affect these derived values are:
2978 - frame count
2979 - frame size
2980 - sample rate
2981 - device type: A2DP or not
2982 - device latency
2983 - format: PCM or not
2984 - active sleep time
2985 - idle sleep time
2986*/
2987
2988void AudioFlinger::PlaybackThread::cacheParameters_l()
2989{
Andy Hung25c2dac2014-02-27 14:56:00 -08002990 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002991 mActiveSleepTimeUs = activeSleepTimeUs();
2992 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002993
2994 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2995 // truncating audio when going to standby.
2996 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2997 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2998 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2999 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3000 }
3001 }
Eric Laurent81784c32012-11-19 14:55:58 -08003002}
3003
Eric Laurent13084622016-05-17 10:51:49 -07003004bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003005{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003006 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003007 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003008 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003009 size_t size = mTracks.size();
3010 for (size_t i = 0; i < size; i++) {
3011 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003012 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003013 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003014 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003015 }
3016 }
Eric Laurent13084622016-05-17 10:51:49 -07003017 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003018}
3019
Haynes Mathew George05317d22016-05-03 16:34:26 -07003020void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3021{
3022 Mutex::Autolock _l(mLock);
3023 invalidateTracks_l(streamType);
3024}
3025
Eric Laurent81784c32012-11-19 14:55:58 -08003026status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3027{
Glenn Kastend848eb42016-03-08 13:42:11 -08003028 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003029 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003030 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003031 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3032 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3033 &halInBuffer);
3034 if (result != OK) return result;
3035 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003036 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003037 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003038 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003039 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003040 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003041 if (mType != DIRECT) {
3042 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003043 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003044 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003045 &halInBuffer);
3046 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003047#ifdef FLOAT_EFFECT_CHAIN
3048 buffer = halInBuffer->audioBuffer()->f32;
3049#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003050 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003051#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003052 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3053 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003054 }
3055
3056 // Attach all tracks with same session ID to this chain.
3057 for (size_t i = 0; i < mTracks.size(); ++i) {
3058 sp<Track> track = mTracks[i];
3059 if (session == track->sessionId()) {
3060 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3061 buffer);
3062 track->setMainBuffer(buffer);
3063 chain->incTrackCnt();
3064 }
3065 }
3066
3067 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003068 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003069 if (session == track->sessionId()) {
3070 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3071 chain->incActiveTrackCnt();
3072 }
3073 }
3074 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003075 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003076 chain->setInBuffer(halInBuffer);
3077 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003078 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003079 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003080 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3081 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003082 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003083 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003084 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003085 // Effect chain for other sessions are inserted at beginning of effect
3086 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003087 // sessions is not important.
3088 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3089 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3090 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003091 size_t size = mEffectChains.size();
3092 size_t i = 0;
3093 for (i = 0; i < size; i++) {
3094 if (mEffectChains[i]->sessionId() < session) {
3095 break;
3096 }
3097 }
3098 mEffectChains.insertAt(chain, i);
3099 checkSuspendOnAddEffectChain_l(chain);
3100
3101 return NO_ERROR;
3102}
3103
3104size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3105{
Glenn Kastend848eb42016-03-08 13:42:11 -08003106 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003107
3108 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3109
3110 for (size_t i = 0; i < mEffectChains.size(); i++) {
3111 if (chain == mEffectChains[i]) {
3112 mEffectChains.removeAt(i);
3113 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003114 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003115 if (session == track->sessionId()) {
3116 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3117 chain.get(), session);
3118 chain->decActiveTrackCnt();
3119 }
3120 }
3121
3122 // detach all tracks with same session ID from this chain
3123 for (size_t i = 0; i < mTracks.size(); ++i) {
3124 sp<Track> track = mTracks[i];
3125 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003126 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003127 chain->decTrackCnt();
3128 }
3129 }
3130 break;
3131 }
3132 }
3133 return mEffectChains.size();
3134}
3135
3136status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003137 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003138{
3139 Mutex::Autolock _l(mLock);
3140 return attachAuxEffect_l(track, EffectId);
3141}
3142
3143status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003144 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003145{
3146 status_t status = NO_ERROR;
3147
3148 if (EffectId == 0) {
3149 track->setAuxBuffer(0, NULL);
3150 } else {
3151 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3152 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3153 if (effect != 0) {
3154 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3155 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3156 } else {
3157 status = INVALID_OPERATION;
3158 }
3159 } else {
3160 status = BAD_VALUE;
3161 }
3162 }
3163 return status;
3164}
3165
3166void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3167{
3168 for (size_t i = 0; i < mTracks.size(); ++i) {
3169 sp<Track> track = mTracks[i];
3170 if (track->auxEffectId() == effectId) {
3171 attachAuxEffect_l(track, 0);
3172 }
3173 }
3174}
3175
3176bool AudioFlinger::PlaybackThread::threadLoop()
3177{
Glenn Kasten388d5712017-04-07 14:38:41 -07003178 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003179
Eric Laurent81784c32012-11-19 14:55:58 -08003180 Vector< sp<Track> > tracksToRemove;
3181
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003182 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003183 nsecs_t lastWriteFinished = -1; // time last server write completed
3184 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003185
3186 // MIXER
3187 nsecs_t lastWarning = 0;
3188
3189 // DUPLICATING
3190 // FIXME could this be made local to while loop?
3191 writeFrames = 0;
3192
3193 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003194 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003195
3196 if (mType == MIXER) {
3197 sleepTimeShift = 0;
3198 }
3199
3200 CpuStats cpuStats;
3201 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3202
3203 acquireWakeLock();
3204
Glenn Kasteneef598c2017-04-03 14:41:13 -07003205 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3206 // thread associated with this PlaybackThread.
3207 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3208 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003209 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3210 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003211 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003212 const char *logString = NULL;
3213
rago1bb90822017-05-02 18:31:48 -07003214 // Estimated time for next buffer to be written to hal. This is used only on
3215 // suspended mode (for now) to help schedule the wait time until next iteration.
3216 nsecs_t timeLoopNextNs = 0;
3217
Eric Laurent664539d2013-09-23 18:24:31 -07003218 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003219
Andy Hungf3234512018-07-03 14:51:47 -07003220 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3221 // TODO: add confirmation checks:
3222 // 1) DIRECT threads and linear PCM format really resets to 0?
3223 // 2) Is frame count really valid if not linear pcm?
3224 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3225 if (mType == OFFLOAD || mType == DIRECT) {
3226 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3227 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003228 audio_utils::Statistics<double> downstreamLatencyStatMs(0.999 /* alpha */);
3229 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003230
Eric Laurent81784c32012-11-19 14:55:58 -08003231 while (!exitPending())
3232 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003233 // Log merge requests are performed during AudioFlinger binder transactions, but
3234 // that does not cover audio playback. It's requested here for that reason.
3235 mAudioFlinger->requestLogMerge();
3236
Eric Laurent81784c32012-11-19 14:55:58 -08003237 cpuStats.sample(myName);
3238
3239 Vector< sp<EffectChain> > effectChains;
3240
Andy Hung2dbffc22018-08-08 18:50:41 -07003241 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3242 //
3243 // Note: we access outDevice() outside of mLock.
3244 if (isMsdDevice() && (outDevice() & AUDIO_DEVICE_OUT_BUS) != 0) {
3245 // Here, we try for the AF lock, but do not block on it as the latency
3246 // is more informational.
3247 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3248 std::vector<PatchPanel::SoftwarePatch> swPatches;
3249 double latencyMs;
3250 status_t status = INVALID_OPERATION;
3251 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3252 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3253 && swPatches.size() > 0) {
3254 status = swPatches[0].getLatencyMs_l(&latencyMs);
3255 downstreamPatchHandle = swPatches[0].getPatchHandle();
3256 }
3257 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
3258 downstreamLatencyStatMs.reset();
3259 lastDownstreamPatchHandle = downstreamPatchHandle;
3260 }
3261 if (status == OK) {
3262 // verify downstream latency (we assume a max reasonable
3263 // latency of 1 second).
3264 if (latencyMs >= 0. && latencyMs <= 1000.) {
3265 ALOGV("new downstream latency %lf ms", latencyMs);
3266 downstreamLatencyStatMs.add(latencyMs);
3267 } else {
3268 ALOGD("out of range downstream latency %lf ms", latencyMs);
3269 }
3270 }
3271 mAudioFlinger->mLock.unlock();
3272 }
3273 } else {
3274 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3275 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
3276 downstreamLatencyStatMs.reset();
3277 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3278 }
3279 }
3280
Eric Laurent81784c32012-11-19 14:55:58 -08003281 { // scope for mLock
3282
3283 Mutex::Autolock _l(mLock);
3284
Eric Laurent021cf962014-05-13 10:18:14 -07003285 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003286
Glenn Kasteneef598c2017-04-03 14:41:13 -07003287 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003288 if (logString != NULL) {
3289 mNBLogWriter->logTimestamp();
3290 mNBLogWriter->log(logString);
3291 logString = NULL;
3292 }
3293
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003294 // Collect timestamp statistics for the Playback Thread types that support it.
3295 if (mType == MIXER
3296 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003297 || mType == DIRECT
3298 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003299 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003300 // and associate with the sink frames written out. We need
3301 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003302 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003303 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003304 if (mStandby) {
3305 mTimestampVerifier.discontinuity();
3306 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3307 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3308 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3309 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003310
3311 if (isTimestampCorrectionEnabled()) {
3312 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3313 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3314 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3315 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3316 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3317 = correctedTimestamp.mFrames;
3318 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3319 = correctedTimestamp.mTimeNs;
3320 ALOGV("TS_AFTER: %d %lld %lld", id(),
3321 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3322 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003323
3324 // Note: Downstream latency only added if timestamp correction enabled.
3325 if (downstreamLatencyStatMs.getN() > 0) { // we have latency info.
3326 const int64_t newPosition =
3327 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3328 - int64_t(downstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3329 // prevent retrograde
3330 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3331 newPosition,
3332 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3333 - mSuspendedFrames));
3334 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003335 }
3336
Andy Hung818e7a32016-02-16 18:08:07 -08003337 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003338 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003339
3340 // We keep track of the last valid kernel position in case we are in underrun
3341 // and the normal mixer period is the same as the fast mixer period, or there
3342 // is some error from the HAL.
3343 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3344 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3345 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3346 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3347 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3348
3349 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3350 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3351 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3352 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003353 }
3354
3355 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3356 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003357 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003358 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003359 }
3360
Andy Hung818e7a32016-02-16 18:08:07 -08003361 // copy over kernel info
3362 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003363 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3364 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003365 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3366 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003367 } else {
3368 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003369 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003370
Andy Hungc54b1ff2016-02-23 14:07:07 -08003371 // mFramesWritten for non-offloaded tracks are contiguous
3372 // even after standby() is called. This is useful for the track frame
3373 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003374 bool serverLocationUpdate = false;
3375 if (mFramesWritten != lastFramesWritten) {
3376 serverLocationUpdate = true;
3377 lastFramesWritten = mFramesWritten;
3378 }
3379 // Only update timestamps if there is a meaningful change.
3380 // Either the kernel timestamp must be valid or we have written something.
3381 if (kernelLocationUpdate || serverLocationUpdate) {
3382 if (serverLocationUpdate) {
3383 // use the time before we called the HAL write - it is a bit more accurate
3384 // to when the server last read data than the current time here.
3385 //
3386 // If we haven't written anything, mLastWriteTime will be -1
3387 // and we use systemTime().
3388 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3389 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3390 ? systemTime() : mLastWriteTime;
3391 }
Andy Hungdae27702016-10-31 14:01:16 -07003392
3393 for (const sp<Track> &t : mActiveTracks) {
3394 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003395 t->updateTrackFrameInfo(
3396 t->mAudioTrackServerProxy->framesReleased(),
3397 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003398 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003399 mTimestamp);
3400 }
Andy Hunge10393e2015-06-12 13:59:33 -07003401 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003402 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003403 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003404#if 0
3405 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003406 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003407 timespec ts;
3408 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003409 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003410 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003411 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003412 }
3413 ++z;
3414#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003415 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003416 if (mSignalPending) {
3417 // A signal was raised while we were unlocked
3418 mSignalPending = false;
3419 } else if (waitingAsyncCallback_l()) {
3420 if (exitPending()) {
3421 break;
3422 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003423 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003424 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003425 releaseWakeLock_l();
3426 released = true;
3427 }
Andy Hung10cbff12017-02-21 17:30:14 -08003428
3429 const int64_t waitNs = computeWaitTimeNs_l();
3430 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3431 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3432 if (status == TIMED_OUT) {
3433 mSignalPending = true; // if timeout recheck everything
3434 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003435 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003436 if (released) {
3437 acquireWakeLock_l();
3438 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003439 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3440 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003441
3442 continue;
3443 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003444 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003445 isSuspended()) {
3446 // put audio hardware into standby after short delay
3447 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003448
3449 threadLoop_standby();
3450
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003451 // This is where we go into standby
3452 if (!mStandby) {
3453 LOG_AUDIO_STATE();
3454 }
Eric Laurent81784c32012-11-19 14:55:58 -08003455 mStandby = true;
3456 }
3457
Eric Tan39ec8d62018-07-24 09:49:29 -07003458 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003459 // we're about to wait, flush the binder command buffer
3460 IPCThreadState::self()->flushCommands();
3461
3462 clearOutputTracks();
3463
3464 if (exitPending()) {
3465 break;
3466 }
3467
3468 releaseWakeLock_l();
3469 // wait until we have something to do...
3470 ALOGV("%s going to sleep", myName.string());
3471 mWaitWorkCV.wait(mLock);
3472 ALOGV("%s waking up", myName.string());
3473 acquireWakeLock_l();
3474
3475 mMixerStatus = MIXER_IDLE;
3476 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3477 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003478 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003479 checkSilentMode_l();
3480
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003481 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3482 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003483 if (mType == MIXER) {
3484 sleepTimeShift = 0;
3485 }
3486
3487 continue;
3488 }
3489 }
Eric Laurent81784c32012-11-19 14:55:58 -08003490 // mMixerStatusIgnoringFastTracks is also updated internally
3491 mMixerStatus = prepareTracks_l(&tracksToRemove);
3492
Andy Hungdae27702016-10-31 14:01:16 -07003493 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003494
Kevin Rocard069c2712018-03-29 19:09:14 -07003495 updateMetadata_l();
3496
Eric Laurent81784c32012-11-19 14:55:58 -08003497 // prevent any changes in effect chain list and in each effect chain
3498 // during mixing and effect process as the audio buffers could be deleted
3499 // or modified if an effect is created or deleted
3500 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003501 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003502
Eric Laurentbfb1b832013-01-07 09:53:42 -08003503 if (mBytesRemaining == 0) {
3504 mCurrentWriteLength = 0;
3505 if (mMixerStatus == MIXER_TRACKS_READY) {
3506 // threadLoop_mix() sets mCurrentWriteLength
3507 threadLoop_mix();
3508 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3509 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003510 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003511 // must be written to HAL
3512 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003513 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003514 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003515 }
3516 }
Andy Hung98ef9782014-03-04 14:46:50 -08003517 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003518 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003519 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3520 // or mSinkBuffer (if there are no effects).
3521 //
3522 // This is done pre-effects computation; if effects change to
3523 // support higher precision, this needs to move.
3524 //
3525 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003526 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003527 if (mMixerBufferValid) {
3528 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3529 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3530
Andy Hung2ddee192015-12-18 17:34:44 -08003531 // mono blend occurs for mixer threads only (not direct or offloaded)
3532 // and is handled here if we're going directly to the sink.
3533 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003534 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3535 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003536 }
3537
Andy Hung98ef9782014-03-04 14:46:50 -08003538 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3539 mNormalFrameCount * mChannelCount);
3540 }
3541
Eric Laurentbfb1b832013-01-07 09:53:42 -08003542 mBytesRemaining = mCurrentWriteLength;
3543 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003544 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3545 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3546 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3547 mBytesWritten += mBytesRemaining;
3548 mFramesWritten += framesRemaining;
3549 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003550 mBytesRemaining = 0;
3551 }
Eric Laurent81784c32012-11-19 14:55:58 -08003552
Eric Laurentbfb1b832013-01-07 09:53:42 -08003553 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003554 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003555 for (size_t i = 0; i < effectChains.size(); i ++) {
3556 effectChains[i]->process_l();
3557 }
Eric Laurent81784c32012-11-19 14:55:58 -08003558 }
3559 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003560 // Process effect chains for offloaded thread even if no audio
3561 // was read from audio track: process only updates effect state
3562 // and thus does have to be synchronized with audio writes but may have
3563 // to be called while waiting for async write callback
3564 if (mType == OFFLOAD) {
3565 for (size_t i = 0; i < effectChains.size(); i ++) {
3566 effectChains[i]->process_l();
3567 }
3568 }
Eric Laurent81784c32012-11-19 14:55:58 -08003569
Andy Hung98ef9782014-03-04 14:46:50 -08003570 // Only if the Effects buffer is enabled and there is data in the
3571 // Effects buffer (buffer valid), we need to
3572 // copy into the sink buffer.
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 (mEffectBufferValid) {
3575 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003576
3577 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003578 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3579 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003580 }
3581
Andy Hung98ef9782014-03-04 14:46:50 -08003582 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3583 mNormalFrameCount * mChannelCount);
3584 }
3585
Eric Laurent81784c32012-11-19 14:55:58 -08003586 // enable changes in effect chain
3587 unlockEffectChains(effectChains);
3588
Eric Laurentbfb1b832013-01-07 09:53:42 -08003589 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003590 // mSleepTimeUs == 0 means we must write to audio hardware
3591 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003592 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003593 // We save lastWriteFinished here, as previousLastWriteFinished,
3594 // for throttling. On thread start, previousLastWriteFinished will be
3595 // set to -1, which properly results in no throttling after the first write.
3596 nsecs_t previousLastWriteFinished = lastWriteFinished;
3597 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003598 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003599 // FIXME rewrite to reduce number of system calls
3600 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003601 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003602 lastWriteFinished = systemTime();
3603 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003604 if (ret < 0) {
3605 mBytesRemaining = 0;
3606 } else {
3607 mBytesWritten += ret;
3608 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003609 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003610 }
3611 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3612 (mMixerStatus == MIXER_DRAIN_ALL)) {
3613 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003614 }
Andy Hung08fb1742015-05-31 23:22:10 -07003615 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003616 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003617 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003618 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003619 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003620 ATRACE_NAME("underrun");
3621 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003622 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003623 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003624 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003625 }
Andy Hung08fb1742015-05-31 23:22:10 -07003626
3627 if (mThreadThrottle
3628 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3629 && ret > 0) { // we wrote something
3630 // Limit MixerThread data processing to no more than twice the
3631 // expected processing rate.
3632 //
3633 // This helps prevent underruns with NuPlayer and other applications
3634 // which may set up buffers that are close to the minimum size, or use
3635 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3636 //
3637 // The throttle smooths out sudden large data drains from the device,
3638 // e.g. when it comes out of standby, which often causes problems with
3639 // (1) mixer threads without a fast mixer (which has its own warm-up)
3640 // (2) minimum buffer sized tracks (even if the track is full,
3641 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003642 //
3643 // Total time spent in last processing cycle equals time spent in
3644 // 1. threadLoop_write, as well as time spent in
3645 // 2. threadLoop_mix (significant for heavy mixing, especially
3646 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003647
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003648 // it's OK if deltaMs (and deltaNs) is an overestimate.
3649 nsecs_t deltaNs;
3650 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3651 __builtin_sub_overflow(
3652 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3653 const int32_t deltaMs = deltaNs / 1000000;
3654
Ivan Lozanoea04d392017-11-07 14:37:07 -08003655 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003656 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3657 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003658 // notify of throttle start on verbose log
3659 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3660 "mixer(%p) throttle begin:"
3661 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003662 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003663 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003664 // Throttle must be attributed to the previous mixer loop's write time
3665 // to allow back-to-back throttling.
3666 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003667 } else {
3668 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3669 if (diff > 0) {
3670 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003671 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003672 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3673 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003674 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003675 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3676 }
Andy Hung08fb1742015-05-31 23:22:10 -07003677 }
3678 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003679 }
Eric Laurent81784c32012-11-19 14:55:58 -08003680
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003682 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003683 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003684 // suspended requires accurate metering of sleep time.
3685 if (isSuspended()) {
3686 // advance by expected sleepTime
3687 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3688 const nsecs_t nowNs = systemTime();
3689
3690 // compute expected next time vs current time.
3691 // (negative deltas are treated as delays).
3692 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3693 if (deltaNs < -kMaxNextBufferDelayNs) {
3694 // Delays longer than the max allowed trigger a reset.
3695 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3696 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3697 timeLoopNextNs = nowNs + deltaNs;
3698 } else if (deltaNs < 0) {
3699 // Delays within the max delay allowed: zero the delta/sleepTime
3700 // to help the system catch up in the next iteration(s)
3701 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3702 deltaNs = 0;
3703 }
3704 // update sleep time (which is >= 0)
3705 mSleepTimeUs = deltaNs / 1000;
3706 }
Eric Laurente93cc032016-05-05 10:15:10 -07003707 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3708 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003709 }
Glenn Kastene7754022014-10-31 12:11:26 -07003710 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003711 }
Eric Laurent81784c32012-11-19 14:55:58 -08003712 }
3713
3714 // Finally let go of removed track(s), without the lock held
3715 // since we can't guarantee the destructors won't acquire that
3716 // same lock. This will also mutate and push a new fast mixer state.
3717 threadLoop_removeTracks(tracksToRemove);
3718 tracksToRemove.clear();
3719
3720 // FIXME I don't understand the need for this here;
3721 // it was in the original code but maybe the
3722 // assignment in saveOutputTracks() makes this unnecessary?
3723 clearOutputTracks();
3724
3725 // Effect chains will be actually deleted here if they were removed from
3726 // mEffectChains list during mixing or effects processing
3727 effectChains.clear();
3728
3729 // FIXME Note that the above .clear() is no longer necessary since effectChains
3730 // is now local to this block, but will keep it for now (at least until merge done).
3731 }
3732
Eric Laurentbfb1b832013-01-07 09:53:42 -08003733 threadLoop_exit();
3734
Eric Laurentcf817a22014-08-04 20:36:31 -07003735 if (!mStandby) {
3736 threadLoop_standby();
3737 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003738 }
3739
3740 releaseWakeLock();
3741
3742 ALOGV("Thread %p type %d exiting", this, mType);
3743 return false;
3744}
3745
Eric Laurentbfb1b832013-01-07 09:53:42 -08003746// removeTracks_l() must be called with ThreadBase::mLock held
3747void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3748{
3749 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003750 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003751 for (size_t i=0 ; i<count ; i++) {
3752 const sp<Track>& track = tracksToRemove.itemAt(i);
3753 mActiveTracks.remove(track);
3754 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3755 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3756 if (chain != 0) {
3757 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3758 track->sessionId());
3759 chain->decActiveTrackCnt();
3760 }
3761 if (track->isTerminated()) {
3762 removeTrack_l(track);
3763 }
3764 }
3765 }
3766
3767}
Eric Laurent81784c32012-11-19 14:55:58 -08003768
Eric Laurentaccc1472013-09-20 09:36:34 -07003769status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3770{
3771 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003772 ExtendedTimestamp ets;
3773 status_t status = mNormalSink->getTimestamp(ets);
3774 if (status == NO_ERROR) {
3775 status = ets.getBestTimestamp(&timestamp);
3776 }
3777 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003778 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003779 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003780 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003781 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003782 timestamp.mPosition = (uint32_t)position64;
3783 return NO_ERROR;
3784 }
3785 }
3786 return INVALID_OPERATION;
3787}
Eric Laurent1c333e22014-05-20 10:48:17 -07003788
Eric Laurent054d9d32015-04-24 08:48:48 -07003789status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3790 audio_patch_handle_t *handle)
3791{
Andy Hungf60abce2016-08-26 11:37:54 -07003792 status_t status;
3793 if (property_get_bool("af.patch_park", false /* default_value */)) {
3794 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3795 // or if HAL does not properly lock against access.
3796 AutoPark<FastMixer> park(mFastMixer);
3797 status = PlaybackThread::createAudioPatch_l(patch, handle);
3798 } else {
3799 status = PlaybackThread::createAudioPatch_l(patch, handle);
3800 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003801 return status;
3802}
3803
Eric Laurent1c333e22014-05-20 10:48:17 -07003804status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3805 audio_patch_handle_t *handle)
3806{
3807 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003808
3809 // store new device and send to effects
3810 audio_devices_t type = AUDIO_DEVICE_NONE;
3811 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3812 type |= patch->sinks[i].ext.device.type;
3813 }
3814
3815#ifdef ADD_BATTERY_DATA
3816 // when changing the audio output device, call addBatteryData to notify
3817 // the change
3818 if (mOutDevice != type) {
3819 uint32_t params = 0;
3820 // check whether speaker is on
3821 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3822 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003823 }
3824
Eric Laurent054d9d32015-04-24 08:48:48 -07003825 audio_devices_t deviceWithoutSpeaker
3826 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3827 // check if any other device (except speaker) is on
3828 if (type & deviceWithoutSpeaker) {
3829 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3830 }
3831
3832 if (params != 0) {
3833 addBatteryData(params);
3834 }
3835 }
3836#endif
3837
3838 for (size_t i = 0; i < mEffectChains.size(); i++) {
3839 mEffectChains[i]->setDevice_l(type);
3840 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003841
3842 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3843 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3844 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003845 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003846 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003847
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003848 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003849 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3850 status = hwDevice->createAudioPatch(patch->num_sources,
3851 patch->sources,
3852 patch->num_sinks,
3853 patch->sinks,
3854 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003855 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003856 char *address;
3857 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3858 //FIXME: we only support address on first sink with HAL version < 3.0
3859 address = audio_device_address_to_parameter(
3860 patch->sinks[0].ext.device.type,
3861 patch->sinks[0].ext.device.address);
3862 } else {
3863 address = (char *)calloc(1, 1);
3864 }
3865 AudioParameter param = AudioParameter(String8(address));
3866 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003867 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003868 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003869 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003870 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003871 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003872 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003873 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3874 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003875 return status;
3876}
3877
Eric Laurent054d9d32015-04-24 08:48:48 -07003878status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3879{
Andy Hungf60abce2016-08-26 11:37:54 -07003880 status_t status;
3881 if (property_get_bool("af.patch_park", false /* default_value */)) {
3882 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3883 // or if HAL does not properly lock against access.
3884 AutoPark<FastMixer> park(mFastMixer);
3885 status = PlaybackThread::releaseAudioPatch_l(handle);
3886 } else {
3887 status = PlaybackThread::releaseAudioPatch_l(handle);
3888 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003889 return status;
3890}
3891
Eric Laurent1c333e22014-05-20 10:48:17 -07003892status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3893{
3894 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003895
3896 mOutDevice = AUDIO_DEVICE_NONE;
3897
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003898 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003899 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3900 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003901 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003902 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003903 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003904 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003905 }
3906 return status;
3907}
3908
Eric Laurent83b88082014-06-20 18:31:16 -07003909void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3910{
3911 Mutex::Autolock _l(mLock);
3912 mTracks.add(track);
3913}
3914
3915void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3916{
3917 Mutex::Autolock _l(mLock);
3918 destroyTrack_l(track);
3919}
3920
Mikhail Naganovdc769682018-05-04 15:34:08 -07003921void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003922{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003923 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003924 config->role = AUDIO_PORT_ROLE_SOURCE;
3925 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3926 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003927 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3928 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3929 config->flags.output = mOutput->flags;
3930 }
Eric Laurent83b88082014-06-20 18:31:16 -07003931}
3932
Eric Laurent81784c32012-11-19 14:55:58 -08003933// ----------------------------------------------------------------------------
3934
3935AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003936 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3937 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003938 // mAudioMixer below
3939 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003940 mFastMixerFutex(0),
3941 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003942 // mOutputSink below
3943 // mPipeSink below
3944 // mNormalSink below
3945{
3946 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003947 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003948 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003949 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3950 mNormalFrameCount);
3951 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3952
Andy Hungfbfc3952015-01-15 13:33:51 -08003953 if (type == DUPLICATING) {
3954 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3955 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3956 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3957 return;
3958 }
Eric Laurent81784c32012-11-19 14:55:58 -08003959 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003960 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003961 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003962 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003963#if !LOG_NDEBUG
3964 ssize_t index =
3965#else
3966 (void)
3967#endif
3968 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003969 ALOG_ASSERT(index == 0);
3970
3971 // initialize fast mixer depending on configuration
3972 bool initFastMixer;
3973 switch (kUseFastMixer) {
3974 case FastMixer_Never:
3975 initFastMixer = false;
3976 break;
3977 case FastMixer_Always:
3978 initFastMixer = true;
3979 break;
3980 case FastMixer_Static:
3981 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003982 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3983 // where the period is less than an experimentally determined threshold that can be
3984 // scheduled reliably with CFS. However, the BT A2DP HAL is
3985 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3986 initFastMixer = mFrameCount < mNormalFrameCount
3987 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003988 break;
3989 }
Andy Hungfda69402017-02-15 14:33:12 -08003990 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3991 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3992 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003993 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003994 audio_format_t fastMixerFormat;
3995 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3996 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3997 } else {
3998 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3999 }
4000 if (mFormat != fastMixerFormat) {
4001 // change our Sink format to accept our intermediate precision
4002 mFormat = fastMixerFormat;
4003 free(mSinkBuffer);
4004 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
4005 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4006 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4007 }
Eric Laurent81784c32012-11-19 14:55:58 -08004008
4009 // create a MonoPipe to connect our submix to FastMixer
4010 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004011
Andy Hung1258c1a2014-05-23 21:22:17 -07004012 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004013 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004014 format.mFormat = fastMixerFormat;
4015 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4016
Eric Laurent81784c32012-11-19 14:55:58 -08004017 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4018 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4019 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4020 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4021 const NBAIO_Format offers[1] = {format};
4022 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004023#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004024 ssize_t index =
4025#else
4026 (void)
4027#endif
4028 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004029 ALOG_ASSERT(index == 0);
4030 monoPipe->setAvgFrames((mScreenState & 1) ?
4031 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4032 mPipeSink = monoPipe;
4033
Eric Laurent81784c32012-11-19 14:55:58 -08004034 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004035 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004036 FastMixerStateQueue *sq = mFastMixer->sq();
4037#ifdef STATE_QUEUE_DUMP
4038 sq->setObserverDump(&mStateQueueObserverDump);
4039 sq->setMutatorDump(&mStateQueueMutatorDump);
4040#endif
4041 FastMixerState *state = sq->begin();
4042 FastTrack *fastTrack = &state->mFastTracks[0];
4043 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4044 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4045 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004046 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
4047 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08004048 fastTrack->mGeneration++;
4049 state->mFastTracksGen++;
4050 state->mTrackMask = 1;
4051 // fast mixer will use the HAL output sink
4052 state->mOutputSink = mOutputSink.get();
4053 state->mOutputSinkGen++;
4054 state->mFrameCount = mFrameCount;
4055 state->mCommand = FastMixerState::COLD_IDLE;
4056 // already done in constructor initialization list
4057 //mFastMixerFutex = 0;
4058 state->mColdFutexAddr = &mFastMixerFutex;
4059 state->mColdGen++;
4060 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004061 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4062 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004063 sq->end();
4064 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4065
4066 // start the fast mixer
4067 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4068 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004069 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004070 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004071
4072#ifdef AUDIO_WATCHDOG
4073 // create and start the watchdog
4074 mAudioWatchdog = new AudioWatchdog();
4075 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4076 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4077 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004078 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004079#endif
Andy Hung8946a282018-04-19 20:04:56 -07004080 } else {
4081#ifdef TEE_SINK
4082 // Only use the MixerThread tee if there is no FastMixer.
4083 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4084 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4085#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004086 }
4087
4088 switch (kUseFastMixer) {
4089 case FastMixer_Never:
4090 case FastMixer_Dynamic:
4091 mNormalSink = mOutputSink;
4092 break;
4093 case FastMixer_Always:
4094 mNormalSink = mPipeSink;
4095 break;
4096 case FastMixer_Static:
4097 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4098 break;
4099 }
4100}
4101
4102AudioFlinger::MixerThread::~MixerThread()
4103{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004104 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004105 FastMixerStateQueue *sq = mFastMixer->sq();
4106 FastMixerState *state = sq->begin();
4107 if (state->mCommand == FastMixerState::COLD_IDLE) {
4108 int32_t old = android_atomic_inc(&mFastMixerFutex);
4109 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004110 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004111 }
4112 }
4113 state->mCommand = FastMixerState::EXIT;
4114 sq->end();
4115 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4116 mFastMixer->join();
4117 // Though the fast mixer thread has exited, it's state queue is still valid.
4118 // We'll use that extract the final state which contains one remaining fast track
4119 // corresponding to our sub-mix.
4120 state = sq->begin();
4121 ALOG_ASSERT(state->mTrackMask == 1);
4122 FastTrack *fastTrack = &state->mFastTracks[0];
4123 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4124 delete fastTrack->mBufferProvider;
4125 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004126 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004127#ifdef AUDIO_WATCHDOG
4128 if (mAudioWatchdog != 0) {
4129 mAudioWatchdog->requestExit();
4130 mAudioWatchdog->requestExitAndWait();
4131 mAudioWatchdog.clear();
4132 }
4133#endif
4134 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004135 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004136 delete mAudioMixer;
4137}
4138
4139
4140uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4141{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004142 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004143 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4144 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4145 }
4146 return latency;
4147}
4148
4149
4150void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4151{
4152 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4153}
4154
Eric Laurentbfb1b832013-01-07 09:53:42 -08004155ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004156{
4157 // FIXME we should only do one push per cycle; confirm this is true
4158 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004159 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004160 FastMixerStateQueue *sq = mFastMixer->sq();
4161 FastMixerState *state = sq->begin();
4162 if (state->mCommand != FastMixerState::MIX_WRITE &&
4163 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4164 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004165
4166 // FIXME workaround for first HAL write being CPU bound on some devices
4167 ATRACE_BEGIN("write");
4168 mOutput->write((char *)mSinkBuffer, 0);
4169 ATRACE_END();
4170
Eric Laurent81784c32012-11-19 14:55:58 -08004171 int32_t old = android_atomic_inc(&mFastMixerFutex);
4172 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004173 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004174 }
4175#ifdef AUDIO_WATCHDOG
4176 if (mAudioWatchdog != 0) {
4177 mAudioWatchdog->resume();
4178 }
4179#endif
4180 }
4181 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004182#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004183 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004184 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004185#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004186 sq->end();
4187 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4188 if (kUseFastMixer == FastMixer_Dynamic) {
4189 mNormalSink = mPipeSink;
4190 }
4191 } else {
4192 sq->end(false /*didModify*/);
4193 }
4194 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004195 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004196}
4197
4198void AudioFlinger::MixerThread::threadLoop_standby()
4199{
4200 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004201 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004202 FastMixerStateQueue *sq = mFastMixer->sq();
4203 FastMixerState *state = sq->begin();
4204 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004205 // Report any frames trapped in the Monopipe
4206 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4207 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4208 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4209 "monoPipeWritten:%lld monoPipeLeft:%lld",
4210 (long long)mFramesWritten, (long long)mSuspendedFrames,
4211 (long long)mPipeSink->framesWritten(), pipeFrames);
4212 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4213
Eric Laurent81784c32012-11-19 14:55:58 -08004214 state->mCommand = FastMixerState::COLD_IDLE;
4215 state->mColdFutexAddr = &mFastMixerFutex;
4216 state->mColdGen++;
4217 mFastMixerFutex = 0;
4218 sq->end();
4219 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4220 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4221 if (kUseFastMixer == FastMixer_Dynamic) {
4222 mNormalSink = mOutputSink;
4223 }
4224#ifdef AUDIO_WATCHDOG
4225 if (mAudioWatchdog != 0) {
4226 mAudioWatchdog->pause();
4227 }
4228#endif
4229 } else {
4230 sq->end(false /*didModify*/);
4231 }
4232 }
4233 PlaybackThread::threadLoop_standby();
4234}
4235
Eric Laurentbfb1b832013-01-07 09:53:42 -08004236bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4237{
4238 return false;
4239}
4240
4241bool AudioFlinger::PlaybackThread::shouldStandby_l()
4242{
4243 return !mStandby;
4244}
4245
4246bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4247{
4248 Mutex::Autolock _l(mLock);
4249 return waitingAsyncCallback_l();
4250}
4251
Eric Laurent81784c32012-11-19 14:55:58 -08004252// shared by MIXER and DIRECT, overridden by DUPLICATING
4253void AudioFlinger::PlaybackThread::threadLoop_standby()
4254{
4255 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004256 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004257 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004258 // discard any pending drain or write ack by incrementing sequence
4259 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4260 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004261 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004262 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4263 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004264 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004265 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004266}
4267
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004268void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4269{
4270 ALOGV("signal playback thread");
4271 broadcast_l();
4272}
4273
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004274void AudioFlinger::PlaybackThread::onAsyncError()
4275{
4276 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4277 invalidateTracks((audio_stream_type_t)i);
4278 }
4279}
4280
Eric Laurent81784c32012-11-19 14:55:58 -08004281void AudioFlinger::MixerThread::threadLoop_mix()
4282{
Eric Laurent81784c32012-11-19 14:55:58 -08004283 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004284 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004285 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004286 // increase sleep time progressively when application underrun condition clears.
4287 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4288 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4289 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004290 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004291 sleepTimeShift--;
4292 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004293 mSleepTimeUs = 0;
4294 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004295 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004296
Eric Laurent81784c32012-11-19 14:55:58 -08004297}
4298
4299void AudioFlinger::MixerThread::threadLoop_sleepTime()
4300{
4301 // If no tracks are ready, sleep once for the duration of an output
4302 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004303 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004304 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004305 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4306 // Using the Monopipe availableToWrite, we estimate the
4307 // sleep time to retry for more data (before we underrun).
4308 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4309 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4310 const size_t pipeFrames = monoPipe->maxFrames();
4311 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4312 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4313 const size_t framesDelay = std::min(
4314 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4315 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4316 pipeFrames, framesLeft, framesDelay);
4317 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4318 } else {
4319 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4320 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4321 mSleepTimeUs = kMinThreadSleepTimeUs;
4322 }
4323 // reduce sleep time in case of consecutive application underruns to avoid
4324 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4325 // duration we would end up writing less data than needed by the audio HAL if
4326 // the condition persists.
4327 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4328 sleepTimeShift++;
4329 }
Eric Laurent81784c32012-11-19 14:55:58 -08004330 }
4331 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004332 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004333 }
4334 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004335 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4336 // before effects processing or output.
4337 if (mMixerBufferValid) {
4338 memset(mMixerBuffer, 0, mMixerBufferSize);
4339 } else {
4340 memset(mSinkBuffer, 0, mSinkBufferSize);
4341 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004342 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004343 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4344 "anticipated start");
4345 }
4346 // TODO add standby time extension fct of effect tail
4347}
4348
4349// prepareTracks_l() must be called with ThreadBase::mLock held
4350AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4351 Vector< sp<Track> > *tracksToRemove)
4352{
Andy Hung1bc088a2018-02-09 15:57:31 -08004353 // clean up deleted track names in AudioMixer before allocating new tracks
4354 (void)mTracks.processDeletedTrackNames([this](int name) {
4355 // for each name, destroy it in the AudioMixer
4356 if (mAudioMixer->exists(name)) {
4357 mAudioMixer->destroy(name);
4358 }
4359 });
4360 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004361
4362 mixer_state mixerStatus = MIXER_IDLE;
4363 // find out which tracks need to be processed
4364 size_t count = mActiveTracks.size();
4365 size_t mixedTracks = 0;
4366 size_t tracksWithEffect = 0;
4367 // counts only _active_ fast tracks
4368 size_t fastTracks = 0;
4369 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4370
4371 float masterVolume = mMasterVolume;
4372 bool masterMute = mMasterMute;
4373
4374 if (masterMute) {
4375 masterVolume = 0;
4376 }
4377 // Delegate master volume control to effect in output mix effect chain if needed
4378 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4379 if (chain != 0) {
4380 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4381 chain->setVolume_l(&v, &v);
4382 masterVolume = (float)((v + (1 << 23)) >> 24);
4383 chain.clear();
4384 }
4385
4386 // prepare a new state to push
4387 FastMixerStateQueue *sq = NULL;
4388 FastMixerState *state = NULL;
4389 bool didModify = false;
4390 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004391 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004392 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004393 sq = mFastMixer->sq();
4394 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004395 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004396 }
4397
Andy Hung69aed5f2014-02-25 17:24:40 -08004398 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004399 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004400
Andy Hungbd3b2b02018-05-21 10:53:11 -07004401 // DeferredOperations handles statistics after setting mixerStatus.
4402 class DeferredOperations {
4403 public:
4404 DeferredOperations(mixer_state *mixerStatus)
4405 : mMixerStatus(mixerStatus) { }
4406
4407 // when leaving scope, tally frames properly.
4408 ~DeferredOperations() {
4409 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4410 // because that is when the underrun occurs.
4411 // We do not distinguish between FastTracks and NormalTracks here.
4412 if (*mMixerStatus == MIXER_TRACKS_READY) {
4413 for (const auto &underrun : mUnderrunFrames) {
4414 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4415 underrun.second);
4416 }
4417 }
4418 }
4419
4420 // tallyUnderrunFrames() is called to update the track counters
4421 // with the number of underrun frames for a particular mixer period.
4422 // We defer tallying until we know the final mixer status.
4423 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4424 mUnderrunFrames.emplace_back(track, underrunFrames);
4425 }
4426
4427 private:
4428 const mixer_state * const mMixerStatus;
4429 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4430 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4431
Eric Laurent81784c32012-11-19 14:55:58 -08004432 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004433 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004434
4435 // this const just means the local variable doesn't change
4436 Track* const track = t.get();
4437
4438 // process fast tracks
4439 if (track->isFastTrack()) {
4440
4441 // It's theoretically possible (though unlikely) for a fast track to be created
4442 // and then removed within the same normal mix cycle. This is not a problem, as
4443 // the track never becomes active so it's fast mixer slot is never touched.
4444 // The converse, of removing an (active) track and then creating a new track
4445 // at the identical fast mixer slot within the same normal mix cycle,
4446 // is impossible because the slot isn't marked available until the end of each cycle.
4447 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004448 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004449 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4450 FastTrack *fastTrack = &state->mFastTracks[j];
4451
4452 // Determine whether the track is currently in underrun condition,
4453 // and whether it had a recent underrun.
4454 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4455 FastTrackUnderruns underruns = ftDump->mUnderruns;
4456 uint32_t recentFull = (underruns.mBitFields.mFull -
4457 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4458 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4459 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4460 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4461 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4462 uint32_t recentUnderruns = recentPartial + recentEmpty;
4463 track->mObservedUnderruns = underruns;
4464 // don't count underruns that occur while stopping or pausing
4465 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004466 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004467 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4468 recentUnderruns > 0) {
4469 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004470 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004471 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004472 // Immediately account for FastTrack underruns.
4473 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004474
4475 // This is similar to the state machine for normal tracks,
4476 // with a few modifications for fast tracks.
4477 bool isActive = true;
4478 switch (track->mState) {
4479 case TrackBase::STOPPING_1:
4480 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004481 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004482 track->mState = TrackBase::STOPPING_2;
4483 }
4484 break;
4485 case TrackBase::PAUSING:
4486 // ramp down is not yet implemented
4487 track->setPaused();
4488 break;
4489 case TrackBase::RESUMING:
4490 // ramp up is not yet implemented
4491 track->mState = TrackBase::ACTIVE;
4492 break;
4493 case TrackBase::ACTIVE:
4494 if (recentFull > 0 || recentPartial > 0) {
4495 // track has provided at least some frames recently: reset retry count
4496 track->mRetryCount = kMaxTrackRetries;
4497 }
4498 if (recentUnderruns == 0) {
4499 // no recent underruns: stay active
4500 break;
4501 }
4502 // there has recently been an underrun of some kind
4503 if (track->sharedBuffer() == 0) {
4504 // were any of the recent underruns "empty" (no frames available)?
4505 if (recentEmpty == 0) {
4506 // no, then ignore the partial underruns as they are allowed indefinitely
4507 break;
4508 }
4509 // there has recently been an "empty" underrun: decrement the retry counter
4510 if (--(track->mRetryCount) > 0) {
4511 break;
4512 }
4513 // indicate to client process that the track was disabled because of underrun;
4514 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004515 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004516 // remove from active list, but state remains ACTIVE [confusing but true]
4517 isActive = false;
4518 break;
4519 }
4520 // fall through
4521 case TrackBase::STOPPING_2:
4522 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004523 case TrackBase::STOPPED:
4524 case TrackBase::FLUSHED: // flush() while active
4525 // Check for presentation complete if track is inactive
4526 // We have consumed all the buffers of this track.
4527 // This would be incomplete if we auto-paused on underrun
4528 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004529 uint32_t latency = 0;
4530 status_t result = mOutput->stream->getLatency(&latency);
4531 ALOGE_IF(result != OK,
4532 "Error when retrieving output stream latency: %d", result);
4533 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004534 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004535 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4536 // track stays in active list until presentation is complete
4537 break;
4538 }
4539 }
4540 if (track->isStopping_2()) {
4541 track->mState = TrackBase::STOPPED;
4542 }
4543 if (track->isStopped()) {
4544 // Can't reset directly, as fast mixer is still polling this track
4545 // track->reset();
4546 // So instead mark this track as needing to be reset after push with ack
4547 resetMask |= 1 << i;
4548 }
4549 isActive = false;
4550 break;
4551 case TrackBase::IDLE:
4552 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004553 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004554 }
4555
4556 if (isActive) {
4557 // was it previously inactive?
4558 if (!(state->mTrackMask & (1 << j))) {
4559 ExtendedAudioBufferProvider *eabp = track;
4560 VolumeProvider *vp = track;
4561 fastTrack->mBufferProvider = eabp;
4562 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004563 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004564 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004565 fastTrack->mGeneration++;
4566 state->mTrackMask |= 1 << j;
4567 didModify = true;
4568 // no acknowledgement required for newly active tracks
4569 }
Kevin Rocard12381092018-04-11 09:19:59 -07004570 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004571 // cache the combined master volume and stream type volume for fast mixer; this
4572 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004573 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004574 proxy->framesReleased()).first;
4575 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004576 * mStreamTypes[track->streamType()].volume
4577 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004578 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004579 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4580 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4581 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4582 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004583 ++fastTracks;
4584 } else {
4585 // was it previously active?
4586 if (state->mTrackMask & (1 << j)) {
4587 fastTrack->mBufferProvider = NULL;
4588 fastTrack->mGeneration++;
4589 state->mTrackMask &= ~(1 << j);
4590 didModify = true;
4591 // If any fast tracks were removed, we must wait for acknowledgement
4592 // because we're about to decrement the last sp<> on those tracks.
4593 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4594 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004595 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4596 // AudioTrack may start (which may not be with a start() but with a write()
4597 // after underrun) and immediately paused or released. In that case the
4598 // FastTrack state hasn't had time to update.
4599 // TODO Remove the ALOGW when this theory is confirmed.
4600 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004601 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4602 j, track->mState, state->mTrackMask, recentUnderruns,
4603 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004604 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004605 }
4606 tracksToRemove->add(track);
4607 // Avoids a misleading display in dumpsys
4608 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4609 }
4610 continue;
4611 }
4612
4613 { // local variable scope to avoid goto warning
4614
4615 audio_track_cblk_t* cblk = track->cblk();
4616
4617 // The first time a track is added we wait
4618 // for all its buffers to be filled before processing it
4619 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004620
4621 // if an active track doesn't exist in the AudioMixer, create it.
4622 if (!mAudioMixer->exists(name)) {
4623 status_t status = mAudioMixer->create(
4624 name,
4625 track->mChannelMask,
4626 track->mFormat,
4627 track->mSessionId);
4628 if (status != OK) {
4629 ALOGW("%s: cannot create track name"
4630 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4631 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4632 tracksToRemove->add(track);
4633 track->invalidate(); // consider it dead.
4634 continue;
4635 }
4636 }
4637
Eric Laurent81784c32012-11-19 14:55:58 -08004638 // make sure that we have enough frames to mix one full buffer.
4639 // enforce this condition only once to enable draining the buffer in case the client
4640 // app does not call stop() and relies on underrun to stop:
4641 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4642 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004643 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004644 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004645 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004646
4647 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004648 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004649 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4650 // add frames already consumed but not yet released by the resampler
4651 // because mAudioTrackServerProxy->framesReady() will include these frames
4652 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4653
Eric Laurent81784c32012-11-19 14:55:58 -08004654 uint32_t minFrames = 1;
4655 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4656 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004657 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004658 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004659
4660 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004661 if (ATRACE_ENABLED()) {
4662 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004663 std::string traceName("nRdy");
4664 traceName += std::to_string(track->name());
4665 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004666 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004667 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004668 !track->isPaused() && !track->isTerminated())
4669 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004670 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004671
4672 mixedTracks++;
4673
Andy Hung69aed5f2014-02-25 17:24:40 -08004674 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4675 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004676 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004677 if (track->mainBuffer() != mSinkBuffer &&
4678 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004679 if (mEffectBufferEnabled) {
4680 mEffectBufferValid = true; // Later can set directly.
4681 }
Eric Laurent81784c32012-11-19 14:55:58 -08004682 chain = getEffectChain_l(track->sessionId());
4683 // Delegate volume control to effect in track effect chain if needed
4684 if (chain != 0) {
4685 tracksWithEffect++;
4686 } else {
4687 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4688 "session %d",
4689 name, track->sessionId());
4690 }
4691 }
4692
4693
4694 int param = AudioMixer::VOLUME;
4695 if (track->mFillingUpStatus == Track::FS_FILLED) {
4696 // no ramp for the first volume setting
4697 track->mFillingUpStatus = Track::FS_ACTIVE;
4698 if (track->mState == TrackBase::RESUMING) {
4699 track->mState = TrackBase::ACTIVE;
4700 param = AudioMixer::RAMP_VOLUME;
4701 }
4702 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004703 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004704 // FIXME should not make a decision based on mServer
4705 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004706 // If the track is stopped before the first frame was mixed,
4707 // do not apply ramp
4708 param = AudioMixer::RAMP_VOLUME;
4709 }
4710
4711 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004712 uint32_t vl, vr; // in U8.24 integer format
4713 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004714 // read original volumes with volume control
4715 float typeVolume = mStreamTypes[track->streamType()].volume;
4716 float v = masterVolume * typeVolume;
4717
Glenn Kastene4756fe2012-11-29 13:38:14 -08004718 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004719 vl = vr = 0;
4720 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004721 if (track->isPausing()) {
4722 track->setPaused();
4723 }
4724 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004725 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004726 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004727 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4728 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004729 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004730 if (vlf > GAIN_FLOAT_UNITY) {
4731 ALOGV("Track left volume out of range: %.3g", vlf);
4732 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004733 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004734 if (vrf > GAIN_FLOAT_UNITY) {
4735 ALOGV("Track right volume out of range: %.3g", vrf);
4736 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004737 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004738 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004739 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004740 // now apply the master volume and stream type volume and shaper volume
4741 vlf *= v * vh;
4742 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004743 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004744 // then derive vl and vr as U8.24 versions for the effect chain
4745 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4746 vl = (uint32_t) (scaleto8_24 * vlf);
4747 vr = (uint32_t) (scaleto8_24 * vrf);
4748 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004749 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004750 // send level comes from shared memory and so may be corrupt
4751 if (sendLevel > MAX_GAIN_INT) {
4752 ALOGV("Track send level out of range: %04X", sendLevel);
4753 sendLevel = MAX_GAIN_INT;
4754 }
Andy Hung6be49402014-05-30 10:42:03 -07004755 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4756 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004757 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004758
Kevin Rocard12381092018-04-11 09:19:59 -07004759 track->setFinalVolume((vrf + vlf) / 2.f);
4760
Eric Laurent81784c32012-11-19 14:55:58 -08004761 // Delegate volume control to effect in track effect chain if needed
4762 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4763 // Do not ramp volume if volume is controlled by effect
4764 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004765 // Update remaining floating point volume levels
4766 vlf = (float)vl / (1 << 24);
4767 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004768 track->mHasVolumeController = true;
4769 } else {
4770 // force no volume ramp when volume controller was just disabled or removed
4771 // from effect chain to avoid volume spike
4772 if (track->mHasVolumeController) {
4773 param = AudioMixer::VOLUME;
4774 }
4775 track->mHasVolumeController = false;
4776 }
4777
Eric Laurent7c29ec92017-09-20 17:54:22 -07004778 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4779 // still applied by the mixer.
4780 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4781 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4782 if (v != mLeftVolFloat) {
4783 status_t result = mOutput->stream->setVolume(v, v);
4784 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4785 if (result == OK) {
4786 mLeftVolFloat = v;
4787 }
4788 }
4789 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4790 // remove stream volume contribution from software volume.
4791 if (v != 0.0f && mLeftVolFloat == v) {
4792 vlf = min(1.0f, vlf / v);
4793 vrf = min(1.0f, vrf / v);
4794 vaf = min(1.0f, vaf / v);
4795 }
4796 }
Eric Laurent81784c32012-11-19 14:55:58 -08004797 // XXX: these things DON'T need to be done each time
4798 mAudioMixer->setBufferProvider(name, track);
4799 mAudioMixer->enable(name);
4800
Andy Hung6be49402014-05-30 10:42:03 -07004801 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4802 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4803 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004804 mAudioMixer->setParameter(
4805 name,
4806 AudioMixer::TRACK,
4807 AudioMixer::FORMAT, (void *)track->format());
4808 mAudioMixer->setParameter(
4809 name,
4810 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004811 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004812 mAudioMixer->setParameter(
4813 name,
4814 AudioMixer::TRACK,
4815 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004816 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004817 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004818 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004819 if (reqSampleRate == 0) {
4820 reqSampleRate = mSampleRate;
4821 } else if (reqSampleRate > maxSampleRate) {
4822 reqSampleRate = maxSampleRate;
4823 }
Eric Laurent81784c32012-11-19 14:55:58 -08004824 mAudioMixer->setParameter(
4825 name,
4826 AudioMixer::RESAMPLE,
4827 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004828 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004829
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004830 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004831 mAudioMixer->setParameter(
4832 name,
4833 AudioMixer::TIMESTRETCH,
4834 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004835 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004836
Andy Hung69aed5f2014-02-25 17:24:40 -08004837 /*
4838 * Select the appropriate output buffer for the track.
4839 *
Andy Hung98ef9782014-03-04 14:46:50 -08004840 * Tracks with effects go into their own effects chain buffer
4841 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004842 *
4843 * Other tracks can use mMixerBuffer for higher precision
4844 * channel accumulation. If this buffer is enabled
4845 * (mMixerBufferEnabled true), then selected tracks will accumulate
4846 * into it.
4847 *
4848 */
4849 if (mMixerBufferEnabled
4850 && (track->mainBuffer() == mSinkBuffer
4851 || track->mainBuffer() == mMixerBuffer)) {
4852 mAudioMixer->setParameter(
4853 name,
4854 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004855 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004856 mAudioMixer->setParameter(
4857 name,
4858 AudioMixer::TRACK,
4859 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4860 // TODO: override track->mainBuffer()?
4861 mMixerBufferValid = true;
4862 } else {
4863 mAudioMixer->setParameter(
4864 name,
4865 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004866 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004867 mAudioMixer->setParameter(
4868 name,
4869 AudioMixer::TRACK,
4870 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4871 }
Eric Laurent81784c32012-11-19 14:55:58 -08004872 mAudioMixer->setParameter(
4873 name,
4874 AudioMixer::TRACK,
4875 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4876
4877 // reset retry count
4878 track->mRetryCount = kMaxTrackRetries;
4879
4880 // If one track is ready, set the mixer ready if:
4881 // - the mixer was not ready during previous round OR
4882 // - no other track is not ready
4883 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4884 mixerStatus != MIXER_TRACKS_ENABLED) {
4885 mixerStatus = MIXER_TRACKS_READY;
4886 }
4887 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004888 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004889 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004890 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4891 track, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004892 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004893 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004894 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004895
Eric Laurent81784c32012-11-19 14:55:58 -08004896 // clear effect chain input buffer if an active track underruns to avoid sending
4897 // previous audio buffer again to effects
4898 chain = getEffectChain_l(track->sessionId());
4899 if (chain != 0) {
4900 chain->clearInputBuffer();
4901 }
4902
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004903 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004904 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4905 track->isStopped() || track->isPaused()) {
4906 // We have consumed all the buffers of this track.
4907 // Remove it from the list of active tracks.
4908 // TODO: use actual buffer filling status instead of latency when available from
4909 // audio HAL
4910 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004911 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004912 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4913 if (track->isStopped()) {
4914 track->reset();
4915 }
4916 tracksToRemove->add(track);
4917 }
4918 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004919 // No buffers for this track. Give it a few chances to
4920 // fill a buffer, then remove it from active list.
4921 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004922 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004923 tracksToRemove->add(track);
4924 // indicate to client process that the track was disabled because of underrun;
4925 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004926 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004927 // If one track is not ready, mark the mixer also not ready if:
4928 // - the mixer was ready during previous round OR
4929 // - no other track is ready
4930 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4931 mixerStatus != MIXER_TRACKS_READY) {
4932 mixerStatus = MIXER_TRACKS_ENABLED;
4933 }
4934 }
4935 mAudioMixer->disable(name);
4936 }
4937
4938 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004939
4940 }
4941
4942 // Push the new FastMixer state if necessary
4943 bool pauseAudioWatchdog = false;
4944 if (didModify) {
4945 state->mFastTracksGen++;
4946 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4947 if (kUseFastMixer == FastMixer_Dynamic &&
4948 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4949 state->mCommand = FastMixerState::COLD_IDLE;
4950 state->mColdFutexAddr = &mFastMixerFutex;
4951 state->mColdGen++;
4952 mFastMixerFutex = 0;
4953 if (kUseFastMixer == FastMixer_Dynamic) {
4954 mNormalSink = mOutputSink;
4955 }
4956 // If we go into cold idle, need to wait for acknowledgement
4957 // so that fast mixer stops doing I/O.
4958 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4959 pauseAudioWatchdog = true;
4960 }
Eric Laurent81784c32012-11-19 14:55:58 -08004961 }
4962 if (sq != NULL) {
4963 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004964 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4965 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4966 // when bringing the output sink into standby.)
4967 //
4968 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4969 //
4970 // This occurs with BT suspend when we idle the FastMixer with
4971 // active tracks, which may be added or removed.
4972 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004973 }
4974#ifdef AUDIO_WATCHDOG
4975 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4976 mAudioWatchdog->pause();
4977 }
4978#endif
4979
4980 // Now perform the deferred reset on fast tracks that have stopped
4981 while (resetMask != 0) {
4982 size_t i = __builtin_ctz(resetMask);
4983 ALOG_ASSERT(i < count);
4984 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004985 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004986 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4987 track->reset();
4988 }
4989
Andy Hung80d03d22018-04-10 10:32:11 -07004990 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4991 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4992 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4993 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4994 // See also the implementation of destroyTrack_l().
4995 for (const auto &track : *tracksToRemove) {
4996 const int name = track->name();
4997 if (mAudioMixer->exists(name)) { // Normal tracks here, fast tracks in FastMixer.
4998 mAudioMixer->setBufferProvider(name, nullptr /* bufferProvider */);
4999 }
5000 }
5001
Eric Laurent81784c32012-11-19 14:55:58 -08005002 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005003 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005004
Eric Laurent97d547d2014-09-02 14:45:53 -07005005 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5006 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005007 }
5008
5009 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005010 // as long as there are effects we should clear the effects buffer, to avoid
5011 // passing a non-clean buffer to the effect chain
5012 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005013 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005014 // sink or mix buffer must be cleared if all tracks are connected to an
5015 // effect chain as in this case the mixer will not write to the sink or mix buffer
5016 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005017 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5018 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005019 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005020 if (mMixerBufferValid) {
5021 memset(mMixerBuffer, 0, mMixerBufferSize);
5022 // TODO: In testing, mSinkBuffer below need not be cleared because
5023 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5024 // after mixing.
5025 //
5026 // To enforce this guarantee:
5027 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5028 // (mixedTracks == 0 && fastTracks > 0))
5029 // must imply MIXER_TRACKS_READY.
5030 // Later, we may clear buffers regardless, and skip much of this logic.
5031 }
Andy Hung98ef9782014-03-04 14:46:50 -08005032 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005033 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005034 }
5035
5036 // if any fast tracks, then status is ready
5037 mMixerStatusIgnoringFastTracks = mixerStatus;
5038 if (fastTracks > 0) {
5039 mixerStatus = MIXER_TRACKS_READY;
5040 }
5041 return mixerStatus;
5042}
5043
Eric Laurentad7dd962016-09-22 12:38:37 -07005044// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005045uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005046{
5047 uint32_t trackCount = 0;
5048 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005049 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005050 trackCount++;
5051 }
5052 }
5053 return trackCount;
5054}
5055
Andy Hung1bc088a2018-02-09 15:57:31 -08005056// isTrackAllowed_l() must be called with ThreadBase::mLock held
5057bool AudioFlinger::MixerThread::isTrackAllowed_l(
5058 audio_channel_mask_t channelMask, audio_format_t format,
5059 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005060{
Andy Hung1bc088a2018-02-09 15:57:31 -08005061 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5062 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005063 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005064 // Check validity as we don't call AudioMixer::create() here.
5065 if (!AudioMixer::isValidFormat(format)) {
5066 ALOGW("%s: invalid format: %#x", __func__, format);
5067 return false;
5068 }
5069 if (!AudioMixer::isValidChannelMask(channelMask)) {
5070 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5071 return false;
5072 }
5073 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005074}
5075
Eric Laurent10351942014-05-08 18:49:52 -07005076// checkForNewParameter_l() must be called with ThreadBase::mLock held
5077bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5078 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005079{
Eric Laurent81784c32012-11-19 14:55:58 -08005080 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005081 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005082
Eric Laurent10351942014-05-08 18:49:52 -07005083 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005084
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005085 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005086
Eric Laurent10351942014-05-08 18:49:52 -07005087 AudioParameter param = AudioParameter(keyValuePair);
5088 int value;
5089 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5090 reconfig = true;
5091 }
5092 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005093 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005094 status = BAD_VALUE;
5095 } else {
5096 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005097 reconfig = true;
5098 }
Eric Laurent10351942014-05-08 18:49:52 -07005099 }
5100 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005101 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005102 status = BAD_VALUE;
5103 } else {
5104 // no need to save value, since it's constant
5105 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005106 }
Eric Laurent10351942014-05-08 18:49:52 -07005107 }
5108 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5109 // do not accept frame count changes if tracks are open as the track buffer
5110 // size depends on frame count and correct behavior would not be guaranteed
5111 // if frame count is changed after track creation
5112 if (!mTracks.isEmpty()) {
5113 status = INVALID_OPERATION;
5114 } else {
5115 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005116 }
Eric Laurent10351942014-05-08 18:49:52 -07005117 }
5118 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005119#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005120 // when changing the audio output device, call addBatteryData to notify
5121 // the change
5122 if (mOutDevice != value) {
5123 uint32_t params = 0;
5124 // check whether speaker is on
5125 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5126 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005127 }
Eric Laurent10351942014-05-08 18:49:52 -07005128
5129 audio_devices_t deviceWithoutSpeaker
5130 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5131 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005132 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005133 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5134 }
5135
5136 if (params != 0) {
5137 addBatteryData(params);
5138 }
5139 }
Eric Laurent81784c32012-11-19 14:55:58 -08005140#endif
5141
Eric Laurent10351942014-05-08 18:49:52 -07005142 // forward device change to effects that have requested to be
5143 // aware of attached audio device.
5144 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005145 a2dpDeviceChanged =
5146 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005147 mOutDevice = value;
5148 for (size_t i = 0; i < mEffectChains.size(); i++) {
5149 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005150 }
5151 }
Eric Laurent10351942014-05-08 18:49:52 -07005152 }
Eric Laurent81784c32012-11-19 14:55:58 -08005153
Eric Laurent10351942014-05-08 18:49:52 -07005154 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005155 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005156 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005157 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005158 mStandby = true;
5159 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005160 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005161 }
Eric Laurent10351942014-05-08 18:49:52 -07005162 if (status == NO_ERROR && reconfig) {
5163 readOutputParameters_l();
5164 delete mAudioMixer;
5165 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005166 for (const auto &track : mTracks) {
5167 const int name = track->name();
5168 status_t status = mAudioMixer->create(
5169 name,
5170 track->mChannelMask,
5171 track->mFormat,
5172 track->mSessionId);
5173 ALOGW_IF(status != NO_ERROR,
5174 "%s: cannot create track name"
5175 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
5176 __func__,
5177 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005178 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005179 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005180 }
Eric Laurent81784c32012-11-19 14:55:58 -08005181 }
5182
Eric Laurent42537be2016-01-08 17:16:42 -08005183 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005184}
5185
5186
5187void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5188{
Eric Laurent81784c32012-11-19 14:55:58 -08005189 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005190 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005191 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005192 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005193 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005194 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005195 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005196 } else {
5197 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005198 }
Eric Laurent81784c32012-11-19 14:55:58 -08005199
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005200 if (hasFastMixer()) {
5201 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5202
5203 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5204 // while we are dumping it. It may be inconsistent, but it won't mutate!
5205 // This is a large object so we place it on the heap.
5206 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan7b651152018-07-13 10:17:19 -07005207 const std::unique_ptr<FastMixerDumpState> copy(new FastMixerDumpState(mFastMixerDumpState));
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005208 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005209
5210#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005211 // Similar for state queue
5212 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5213 observerCopy.dump(fd);
5214 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5215 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005216#endif
5217
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005218#ifdef AUDIO_WATCHDOG
5219 if (mAudioWatchdog != 0) {
5220 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5221 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5222 wdCopy.dump(fd);
5223 }
5224#endif
5225
5226 } else {
5227 dprintf(fd, " No FastMixer\n");
5228 }
Eric Laurent81784c32012-11-19 14:55:58 -08005229}
5230
Eric Tan1882f162018-08-02 18:05:39 -07005231Json::Value AudioFlinger::MixerThread::getJsonDump() const
Eric Tan7b651152018-07-13 10:17:19 -07005232{
Eric Tan1882f162018-08-02 18:05:39 -07005233 Json::Value root;
5234 if (hasFastMixer()) {
5235 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5236 // while we are dumping it. It may be inconsistent, but it won't mutate!
5237 // This is a large object so we place it on the heap.
5238 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5239 const std::unique_ptr<FastMixerDumpState> copy(new FastMixerDumpState(mFastMixerDumpState));
5240 root["fastmixer_stats"] = copy->getJsonDump();
5241 } else {
5242 root["fastmixer_stats"] = "no_fastmixer";
5243 }
5244 return root;
Eric Tan7b651152018-07-13 10:17:19 -07005245}
5246
Eric Laurent81784c32012-11-19 14:55:58 -08005247uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5248{
5249 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5250}
5251
5252uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5253{
5254 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5255}
5256
5257void AudioFlinger::MixerThread::cacheParameters_l()
5258{
5259 PlaybackThread::cacheParameters_l();
5260
5261 // FIXME: Relaxed timing because of a certain device that can't meet latency
5262 // Should be reduced to 2x after the vendor fixes the driver issue
5263 // increase threshold again due to low power audio mode. The way this warning
5264 // threshold is calculated and its usefulness should be reconsidered anyway.
5265 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5266}
5267
5268// ----------------------------------------------------------------------------
5269
5270AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005271 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5272 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005273{
5274}
5275
Eric Laurentbfb1b832013-01-07 09:53:42 -08005276AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5277 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005278 ThreadBase::type_t type, bool systemReady)
5279 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005280 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005281{
5282}
5283
Eric Laurent81784c32012-11-19 14:55:58 -08005284AudioFlinger::DirectOutputThread::~DirectOutputThread()
5285{
5286}
5287
Eric Laurent5850c4c2016-11-10 13:04:31 -08005288void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005289{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005290 float left, right;
5291
5292 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5293 left = right = 0;
5294 } else {
5295 float typeVolume = mStreamTypes[track->streamType()].volume;
5296 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005297 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005298
Andy Hung10cbff12017-02-21 17:30:14 -08005299 // Get volumeshaper scaling
5300 std::pair<float /* volume */, bool /* active */>
5301 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005302 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005303 v *= vh.first;
5304 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005305
Glenn Kastenc56f3422014-03-21 17:53:17 -07005306 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5307 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5308 if (left > GAIN_FLOAT_UNITY) {
5309 left = GAIN_FLOAT_UNITY;
5310 }
5311 left *= v;
5312 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5313 if (right > GAIN_FLOAT_UNITY) {
5314 right = GAIN_FLOAT_UNITY;
5315 }
5316 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005317 }
5318
5319 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005320 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005321 if (left != mLeftVolFloat || right != mRightVolFloat) {
5322 mLeftVolFloat = left;
5323 mRightVolFloat = right;
5324
Eric Laurentbfb1b832013-01-07 09:53:42 -08005325 // Delegate volume control to effect in track effect chain if needed
5326 // only one effect chain can be present on DirectOutputThread, so if
5327 // there is one, the track is connected to it
5328 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005329 // if effect chain exists, volume is handled by it.
5330 // Convert volumes from float to 8.24
5331 uint32_t vl = (uint32_t)(left * (1 << 24));
5332 uint32_t vr = (uint32_t)(right * (1 << 24));
5333 // Direct/Offload effect chains set output volume in setVolume_l().
5334 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5335 } else {
5336 // otherwise we directly set the volume.
5337 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005338 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005339 }
5340 }
5341}
5342
Phil Burk43b4dcc2015-06-09 16:53:44 -07005343void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5344{
5345 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005346 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005347
Eric Laurent0f0631e2015-07-06 18:01:25 -07005348 if (previousTrack != 0 && latestTrack != 0) {
5349 if (mType == DIRECT) {
5350 if (previousTrack.get() != latestTrack.get()) {
5351 mFlushPending = true;
5352 }
5353 } else /* mType == OFFLOAD */ {
5354 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5355 mFlushPending = true;
5356 }
5357 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005358 }
5359 PlaybackThread::onAddNewTrack_l();
5360}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005361
Eric Laurent81784c32012-11-19 14:55:58 -08005362AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5363 Vector< sp<Track> > *tracksToRemove
5364)
5365{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005366 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005367 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005368 bool doHwPause = false;
5369 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005370
5371 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005372 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005373 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005374 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005375 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005376 continue;
5377 }
5378
Eric Laurent5850c4c2016-11-10 13:04:31 -08005379 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005380#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005381 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005382#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005383 // Only consider last track started for volume and mixer state control.
5384 // In theory an older track could underrun and restart after the new one starts
5385 // but as we only care about the transition phase between two tracks on a
5386 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005387 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005388 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005389
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005390 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005391 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005392 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005393 doHwPause = true;
5394 mHwPaused = true;
5395 }
5396 tracksToRemove->add(track);
5397 } else if (track->isFlushPending()) {
5398 track->flushAck();
5399 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005400 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005401 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005402 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005403 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005404 if (last) {
5405 mLeftVolFloat = mRightVolFloat = -1.0;
5406 if (mHwPaused) {
5407 doHwResume = true;
5408 mHwPaused = false;
5409 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005410 }
5411 }
5412
Eric Laurent81784c32012-11-19 14:55:58 -08005413 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005414 // for all its buffers to be filled before processing it.
5415 // Allow draining the buffer in case the client
5416 // app does not call stop() and relies on underrun to stop:
5417 // hence the test on (track->mRetryCount > 1).
5418 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005419 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005420 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005421 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005422 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005423 minFrames = mNormalFrameCount;
5424 } else {
5425 minFrames = 1;
5426 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005427
Eric Laurentab5cdba2014-06-09 17:22:27 -07005428 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5429 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005430 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005431 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005432
5433 if (track->mFillingUpStatus == Track::FS_FILLED) {
5434 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005435 if (last) {
5436 // make sure processVolume_l() will apply new volume even if 0
5437 mLeftVolFloat = mRightVolFloat = -1.0;
5438 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005439 if (!mHwSupportsPause) {
5440 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005441 }
5442 }
5443
5444 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005445 processVolume_l(track, last);
5446 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005447 sp<Track> previousTrack = mPreviousTrack.promote();
5448 if (previousTrack != 0) {
5449 if (track != previousTrack.get()) {
5450 // Flush any data still being written from last track
5451 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005452 // Invalidate previous track to force a seek when resuming.
5453 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005454 }
5455 }
5456 mPreviousTrack = track;
5457
Eric Laurentd595b7c2013-04-03 17:27:56 -07005458 // reset retry count
5459 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005460 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005461 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005462 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005463 doHwResume = true;
5464 mHwPaused = false;
5465 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005466 }
Eric Laurent81784c32012-11-19 14:55:58 -08005467 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005468 // clear effect chain input buffer if the last active track started underruns
5469 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005470 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005471 mEffectChains[0]->clearInputBuffer();
5472 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005473 if (track->isStopping_1()) {
5474 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005475 if (last && mHwPaused) {
5476 doHwResume = true;
5477 mHwPaused = false;
5478 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005479 }
5480 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5481 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005482 // We have consumed all the buffers of this track.
5483 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005484 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005485 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005486 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5487 } else {
5488 audioHALFrames = 0;
5489 }
5490
Andy Hung818e7a32016-02-16 18:08:07 -08005491 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005492 if (mStandby || !last ||
5493 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005494 if (track->isStopping_2()) {
5495 track->mState = TrackBase::STOPPED;
5496 }
Eric Laurent81784c32012-11-19 14:55:58 -08005497 if (track->isStopped()) {
5498 track->reset();
5499 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005500 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005501 }
5502 } else {
5503 // No buffers for this track. Give it a few chances to
5504 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005505 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005506 if (--(track->mRetryCount) <= 0) {
5507 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005508 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005509 // indicate to client process that the track was disabled because of underrun;
5510 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005511 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005512 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005513 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5514 "minFrames = %u, mFormat = %#x",
5515 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005516 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005517 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005518 doHwPause = true;
5519 mHwPaused = true;
5520 }
Eric Laurent81784c32012-11-19 14:55:58 -08005521 }
5522 }
5523 }
5524 }
5525
Eric Laurentd1f69b02014-12-15 14:33:13 -08005526 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005527 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005528 for (size_t i = 0; i < mTracks.size(); i++) {
5529 if (mTracks[i]->isFlushPending()) {
5530 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005531 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005532 }
5533 }
5534 }
5535
5536 // make sure the pause/flush/resume sequence is executed in the right order.
5537 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5538 // before flush and then resume HW. This can happen in case of pause/flush/resume
5539 // if resume is received before pause is executed.
5540 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005541 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005542 status_t result = mOutput->stream->pause();
5543 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005544 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005545 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005546 flushHw_l();
5547 }
5548 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005549 status_t result = mOutput->stream->resume();
5550 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005551 }
Eric Laurent81784c32012-11-19 14:55:58 -08005552 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005553 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005554
5555 return mixerStatus;
5556}
5557
5558void AudioFlinger::DirectOutputThread::threadLoop_mix()
5559{
Eric Laurent81784c32012-11-19 14:55:58 -08005560 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005561 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005562 // output audio to hardware
5563 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005564 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005565 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005566 status_t status = mActiveTrack->getNextBuffer(&buffer);
5567 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005568 // no need to pad with 0 for compressed audio
5569 if (audio_has_proportional_frames(mFormat)) {
5570 memset(curBuf, 0, frameCount * mFrameSize);
5571 }
Eric Laurent81784c32012-11-19 14:55:58 -08005572 break;
5573 }
5574 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5575 frameCount -= buffer.frameCount;
5576 curBuf += buffer.frameCount * mFrameSize;
5577 mActiveTrack->releaseBuffer(&buffer);
5578 }
Andy Hung2098f272014-02-27 14:00:06 -08005579 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005580 mSleepTimeUs = 0;
5581 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005582 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005583}
5584
5585void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5586{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005587 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005588 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005589 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005590 return;
5591 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005592 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005593 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005594 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005595 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005596 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005597 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005598 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005599 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005600 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005601 }
5602}
5603
Eric Laurentd1f69b02014-12-15 14:33:13 -08005604void AudioFlinger::DirectOutputThread::threadLoop_exit()
5605{
5606 {
5607 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005608 for (size_t i = 0; i < mTracks.size(); i++) {
5609 if (mTracks[i]->isFlushPending()) {
5610 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005611 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005612 }
5613 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005614 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005615 flushHw_l();
5616 }
5617 }
5618 PlaybackThread::threadLoop_exit();
5619}
5620
5621// must be called with thread mutex locked
5622bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5623{
5624 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005625 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005626
vivek mehta9cd7ad12016-03-17 00:18:29 -07005627 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5628 return !mStandby;
5629 }
5630
Eric Laurentd1f69b02014-12-15 14:33:13 -08005631 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5632 // after a timeout and we will enter standby then.
5633 if (mTracks.size() > 0) {
5634 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005635 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5636 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005637 }
5638
Eric Laurent5cff4032015-05-26 13:49:58 -07005639 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005640}
5641
Eric Laurent10351942014-05-08 18:49:52 -07005642// checkForNewParameter_l() must be called with ThreadBase::mLock held
5643bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5644 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005645{
5646 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005647 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005648
Eric Laurent10351942014-05-08 18:49:52 -07005649 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005650
Eric Laurent10351942014-05-08 18:49:52 -07005651 AudioParameter param = AudioParameter(keyValuePair);
5652 int value;
5653 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5654 // forward device change to effects that have requested to be
5655 // aware of attached audio device.
5656 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005657 a2dpDeviceChanged =
5658 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005659 mOutDevice = value;
5660 for (size_t i = 0; i < mEffectChains.size(); i++) {
5661 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005662 }
5663 }
Eric Laurent81784c32012-11-19 14:55:58 -08005664 }
Eric Laurent10351942014-05-08 18:49:52 -07005665 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5666 // do not accept frame count changes if tracks are open as the track buffer
5667 // size depends on frame count and correct behavior would not be garantied
5668 // if frame count is changed after track creation
5669 if (!mTracks.isEmpty()) {
5670 status = INVALID_OPERATION;
5671 } else {
5672 reconfig = true;
5673 }
5674 }
5675 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005676 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005677 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005678 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005679 mStandby = true;
5680 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005681 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005682 }
5683 if (status == NO_ERROR && reconfig) {
5684 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005685 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005686 }
5687 }
5688
Eric Laurent42537be2016-01-08 17:16:42 -08005689 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005690}
5691
5692uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5693{
5694 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005695 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005696 time = PlaybackThread::activeSleepTimeUs();
5697 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005698 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005699 }
5700 return time;
5701}
5702
5703uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5704{
5705 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005706 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005707 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5708 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005709 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005710 }
5711 return time;
5712}
5713
5714uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5715{
5716 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005717 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005718 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5719 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005720 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005721 }
5722 return time;
5723}
5724
5725void AudioFlinger::DirectOutputThread::cacheParameters_l()
5726{
5727 PlaybackThread::cacheParameters_l();
5728
5729 // use shorter standby delay as on normal output to release
5730 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005731 // no delay on outputs with HW A/V sync
5732 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005733 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005734 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005735 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005736 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005737 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005738 }
Eric Laurent81784c32012-11-19 14:55:58 -08005739}
5740
Eric Laurente659ef42014-09-29 13:06:46 -07005741void AudioFlinger::DirectOutputThread::flushHw_l()
5742{
Phil Burk062e67a2015-02-11 13:40:50 -08005743 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005744 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005745 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005746 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005747}
5748
Andy Hung10cbff12017-02-21 17:30:14 -08005749int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5750 // If a VolumeShaper is active, we must wake up periodically to update volume.
5751 const int64_t NS_PER_MS = 1000000;
5752 return mVolumeShaperActive ?
5753 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5754}
5755
Eric Laurent81784c32012-11-19 14:55:58 -08005756// ----------------------------------------------------------------------------
5757
Eric Laurentbfb1b832013-01-07 09:53:42 -08005758AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005759 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005760 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005761 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005762 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005763 mDrainSequence(0),
5764 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005765{
5766}
5767
5768AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5769{
5770}
5771
5772void AudioFlinger::AsyncCallbackThread::onFirstRef()
5773{
5774 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5775}
5776
5777bool AudioFlinger::AsyncCallbackThread::threadLoop()
5778{
5779 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005780 uint32_t writeAckSequence;
5781 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005782 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005783
5784 {
5785 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005786 while (!((mWriteAckSequence & 1) ||
5787 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005788 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005789 exitPending())) {
5790 mWaitWorkCV.wait(mLock);
5791 }
5792
Eric Laurentbfb1b832013-01-07 09:53:42 -08005793 if (exitPending()) {
5794 break;
5795 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005796 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5797 mWriteAckSequence, mDrainSequence);
5798 writeAckSequence = mWriteAckSequence;
5799 mWriteAckSequence &= ~1;
5800 drainSequence = mDrainSequence;
5801 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005802 asyncError = mAsyncError;
5803 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005804 }
5805 {
Eric Laurent4de95592013-09-26 15:28:21 -07005806 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5807 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005808 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005809 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005810 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005811 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005812 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005813 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005814 if (asyncError) {
5815 playbackThread->onAsyncError();
5816 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005817 }
5818 }
5819 }
5820 return false;
5821}
5822
5823void AudioFlinger::AsyncCallbackThread::exit()
5824{
5825 ALOGV("AsyncCallbackThread::exit");
5826 Mutex::Autolock _l(mLock);
5827 requestExit();
5828 mWaitWorkCV.broadcast();
5829}
5830
Eric Laurent3b4529e2013-09-05 18:09:19 -07005831void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005832{
5833 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005834 // bit 0 is cleared
5835 mWriteAckSequence = sequence << 1;
5836}
5837
5838void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5839{
5840 Mutex::Autolock _l(mLock);
5841 // ignore unexpected callbacks
5842 if (mWriteAckSequence & 2) {
5843 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005844 mWaitWorkCV.signal();
5845 }
5846}
5847
Eric Laurent3b4529e2013-09-05 18:09:19 -07005848void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005849{
5850 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005851 // bit 0 is cleared
5852 mDrainSequence = sequence << 1;
5853}
5854
5855void AudioFlinger::AsyncCallbackThread::resetDraining()
5856{
5857 Mutex::Autolock _l(mLock);
5858 // ignore unexpected callbacks
5859 if (mDrainSequence & 2) {
5860 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005861 mWaitWorkCV.signal();
5862 }
5863}
5864
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005865void AudioFlinger::AsyncCallbackThread::setAsyncError()
5866{
5867 Mutex::Autolock _l(mLock);
5868 mAsyncError = true;
5869 mWaitWorkCV.signal();
5870}
5871
Eric Laurentbfb1b832013-01-07 09:53:42 -08005872
5873// ----------------------------------------------------------------------------
5874AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005875 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5876 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005877 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5878 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005879{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005880 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005881 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005882 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005883}
5884
Eric Laurentbfb1b832013-01-07 09:53:42 -08005885void AudioFlinger::OffloadThread::threadLoop_exit()
5886{
5887 if (mFlushPending || mHwPaused) {
5888 // If a flush is pending or track was paused, just discard buffered data
5889 flushHw_l();
5890 } else {
5891 mMixerStatus = MIXER_DRAIN_ALL;
5892 threadLoop_drain();
5893 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005894 if (mUseAsyncWrite) {
5895 ALOG_ASSERT(mCallbackThread != 0);
5896 mCallbackThread->exit();
5897 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005898 PlaybackThread::threadLoop_exit();
5899}
5900
5901AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5902 Vector< sp<Track> > *tracksToRemove
5903)
5904{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005905 size_t count = mActiveTracks.size();
5906
5907 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005908 bool doHwPause = false;
5909 bool doHwResume = false;
5910
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005911 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005912
Eric Laurentbfb1b832013-01-07 09:53:42 -08005913 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005914 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005915 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005916#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005917 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005918#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005919 // Only consider last track started for volume and mixer state control.
5920 // In theory an older track could underrun and restart after the new one starts
5921 // but as we only care about the transition phase between two tracks on a
5922 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005923 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005924 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005925
Haynes Mathew George7844f672014-01-15 12:32:55 -08005926 if (track->isInvalid()) {
5927 ALOGW("An invalidated track shouldn't be in active list");
5928 tracksToRemove->add(track);
5929 continue;
5930 }
5931
5932 if (track->mState == TrackBase::IDLE) {
5933 ALOGW("An idle track shouldn't be in active list");
5934 continue;
5935 }
5936
Eric Laurentbfb1b832013-01-07 09:53:42 -08005937 if (track->isPausing()) {
5938 track->setPaused();
5939 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005940 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005941 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005942 mHwPaused = true;
5943 }
5944 // If we were part way through writing the mixbuffer to
5945 // the HAL we must save this until we resume
5946 // BUG - this will be wrong if a different track is made active,
5947 // in that case we want to discard the pending data in the
5948 // mixbuffer and tell the client to present it again when the
5949 // track is resumed
5950 mPausedWriteLength = mCurrentWriteLength;
5951 mPausedBytesRemaining = mBytesRemaining;
5952 mBytesRemaining = 0; // stop writing
5953 }
5954 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005955 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005956 if (track->isStopping_1()) {
5957 track->mRetryCount = kMaxTrackStopRetriesOffload;
5958 } else {
5959 track->mRetryCount = kMaxTrackRetriesOffload;
5960 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005961 track->flushAck();
5962 if (last) {
5963 mFlushPending = true;
5964 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005965 } else if (track->isResumePending()){
5966 track->resumeAck();
5967 if (last) {
5968 if (mPausedBytesRemaining) {
5969 // Need to continue write that was interrupted
5970 mCurrentWriteLength = mPausedWriteLength;
5971 mBytesRemaining = mPausedBytesRemaining;
5972 mPausedBytesRemaining = 0;
5973 }
5974 if (mHwPaused) {
5975 doHwResume = true;
5976 mHwPaused = false;
5977 // threadLoop_mix() will handle the case that we need to
5978 // resume an interrupted write
5979 }
5980 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005981 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005982
Eric Laurent3df841a2016-07-15 15:15:40 -07005983 mLeftVolFloat = mRightVolFloat = -1.0;
5984
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005985 // Do not handle new data in this iteration even if track->framesReady()
5986 mixerStatus = MIXER_TRACKS_ENABLED;
5987 }
5988 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005989 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005990 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005991 if (track->mFillingUpStatus == Track::FS_FILLED) {
5992 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005993 if (last) {
5994 // make sure processVolume_l() will apply new volume even if 0
5995 mLeftVolFloat = mRightVolFloat = -1.0;
5996 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005997 }
5998
5999 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006000 sp<Track> previousTrack = mPreviousTrack.promote();
6001 if (previousTrack != 0) {
6002 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006003 // Flush any data still being written from last track
6004 mBytesRemaining = 0;
6005 if (mPausedBytesRemaining) {
6006 // Last track was paused so we also need to flush saved
6007 // mixbuffer state and invalidate track so that it will
6008 // re-submit that unwritten data when it is next resumed
6009 mPausedBytesRemaining = 0;
6010 // Invalidate is a bit drastic - would be more efficient
6011 // to have a flag to tell client that some of the
6012 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006013 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006014 }
6015 // flush data already sent to the DSP if changing audio session as audio
6016 // comes from a different source. Also invalidate previous track to force a
6017 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006018 if (previousTrack->sessionId() != track->sessionId()) {
6019 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006020 }
6021 }
6022 }
6023 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006024 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006025 if (track->isStopping_1()) {
6026 track->mRetryCount = kMaxTrackStopRetriesOffload;
6027 } else {
6028 track->mRetryCount = kMaxTrackRetriesOffload;
6029 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006030 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006031 mixerStatus = MIXER_TRACKS_READY;
6032 }
6033 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07006034 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006035 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006036 if (--(track->mRetryCount) <= 0) {
6037 // Hardware buffer can hold a large amount of audio so we must
6038 // wait for all current track's data to drain before we say
6039 // that the track is stopped.
6040 if (mBytesRemaining == 0) {
6041 // Only start draining when all data in mixbuffer
6042 // has been written
6043 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6044 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6045 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6046 if (last && !mStandby) {
6047 // do not modify drain sequence if we are already draining. This happens
6048 // when resuming from pause after drain.
6049 if ((mDrainSequence & 1) == 0) {
6050 mSleepTimeUs = 0;
6051 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6052 mixerStatus = MIXER_DRAIN_TRACK;
6053 mDrainSequence += 2;
6054 }
6055 if (mHwPaused) {
6056 // It is possible to move from PAUSED to STOPPING_1 without
6057 // a resume so we must ensure hardware is running
6058 doHwResume = true;
6059 mHwPaused = false;
6060 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006061 }
6062 }
Eric Laurente93cc032016-05-05 10:15:10 -07006063 } else if (last) {
6064 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6065 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006066 }
6067 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006068 // Drain has completed or we are in standby, signal presentation complete
6069 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006070 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006071 uint32_t latency = 0;
6072 status_t result = mOutput->stream->getLatency(&latency);
6073 ALOGE_IF(result != OK,
6074 "Error when retrieving output stream latency: %d", result);
6075 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006076 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006077 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006078 track->presentationComplete(framesWritten, audioHALFrames);
6079 track->reset();
6080 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006081 // DIRECT and OFFLOADED stop resets frame counts.
6082 if (!mUseAsyncWrite) {
6083 // If we don't get explicit drain notification we must
6084 // register discontinuity regardless of whether this is
6085 // the previous (!last) or the upcoming (last) track
6086 // to avoid skipping the discontinuity.
6087 mTimestampVerifier.discontinuity();
6088 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006089 }
6090 } else {
6091 // No buffers for this track. Give it a few chances to
6092 // fill a buffer, then remove it from active list.
6093 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006094 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006095 uint64_t position = 0;
6096 struct timespec unused;
6097 // The running check restarts the retry counter at least once.
6098 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6099 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6100 running = true;
6101 mOffloadUnderrunPosition = position;
6102 }
6103 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006104 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6105 (long long)position, (long long)mOffloadUnderrunPosition);
6106 }
6107 if (running) { // still running, give us more time.
6108 track->mRetryCount = kMaxTrackRetriesOffload;
6109 } else {
6110 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
6111 track->name());
6112 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006113 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006114 // it will then automatically call start() when data is available
6115 track->disable();
6116 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006117 } else if (last){
6118 mixerStatus = MIXER_TRACKS_ENABLED;
6119 }
6120 }
6121 }
6122 // compute volume for this track
6123 processVolume_l(track, last);
6124 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006125
Eric Laurentea0fade2013-10-04 16:23:48 -07006126 // make sure the pause/flush/resume sequence is executed in the right order.
6127 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6128 // before flush and then resume HW. This can happen in case of pause/flush/resume
6129 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006130 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006131 status_t result = mOutput->stream->pause();
6132 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006133 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006134 if (mFlushPending) {
6135 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006136 }
Eric Laurentfd477972013-10-25 18:10:40 -07006137 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006138 status_t result = mOutput->stream->resume();
6139 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006140 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006141
Eric Laurentbfb1b832013-01-07 09:53:42 -08006142 // remove all the tracks that need to be...
6143 removeTracks_l(*tracksToRemove);
6144
6145 return mixerStatus;
6146}
6147
Eric Laurentbfb1b832013-01-07 09:53:42 -08006148// must be called with thread mutex locked
6149bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6150{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006151 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6152 mWriteAckSequence, mDrainSequence);
6153 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006154 return true;
6155 }
6156 return false;
6157}
6158
Eric Laurentbfb1b832013-01-07 09:53:42 -08006159bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6160{
6161 Mutex::Autolock _l(mLock);
6162 return waitingAsyncCallback_l();
6163}
6164
6165void AudioFlinger::OffloadThread::flushHw_l()
6166{
Eric Laurente659ef42014-09-29 13:06:46 -07006167 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006168 // Flush anything still waiting in the mixbuffer
6169 mCurrentWriteLength = 0;
6170 mBytesRemaining = 0;
6171 mPausedWriteLength = 0;
6172 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006173 // reset bytes written count to reflect that DSP buffers are empty after flush.
6174 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006175 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006176
Eric Laurentbfb1b832013-01-07 09:53:42 -08006177 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006178 // discard any pending drain or write ack by incrementing sequence
6179 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6180 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006181 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006182 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6183 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006184 }
6185}
6186
Haynes Mathew George05317d22016-05-03 16:34:26 -07006187void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6188{
6189 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006190 if (PlaybackThread::invalidateTracks_l(streamType)) {
6191 mFlushPending = true;
6192 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006193}
6194
Eric Laurentbfb1b832013-01-07 09:53:42 -08006195// ----------------------------------------------------------------------------
6196
Eric Laurent81784c32012-11-19 14:55:58 -08006197AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006198 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006199 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006200 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006201 mWaitTimeMs(UINT_MAX)
6202{
6203 addOutputTrack(mainThread);
6204}
6205
6206AudioFlinger::DuplicatingThread::~DuplicatingThread()
6207{
6208 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6209 mOutputTracks[i]->destroy();
6210 }
6211}
6212
6213void AudioFlinger::DuplicatingThread::threadLoop_mix()
6214{
6215 // mix buffers...
6216 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006217 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006218 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006219 if (mMixerBufferValid) {
6220 memset(mMixerBuffer, 0, mMixerBufferSize);
6221 } else {
6222 memset(mSinkBuffer, 0, mSinkBufferSize);
6223 }
Eric Laurent81784c32012-11-19 14:55:58 -08006224 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006225 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006226 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006227 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006228 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006229}
6230
6231void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6232{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006233 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006234 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006235 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006236 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006237 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006238 }
6239 } else if (mBytesWritten != 0) {
6240 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6241 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006242 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006243 } else {
6244 // flush remaining overflow buffers in output tracks
6245 writeFrames = 0;
6246 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006247 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006248 }
6249}
6250
Eric Laurentbfb1b832013-01-07 09:53:42 -08006251ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006252{
6253 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006254 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6255
6256 // Consider the first OutputTrack for timestamp and frame counting.
6257
6258 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6259 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6260 // we always claim success.
6261 if (i == 0) {
6262 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6263 ALOGD_IF(correction != 0 && writeFrames != 0,
6264 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6265 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6266 mFramesWritten -= correction;
6267 }
6268
6269 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006270 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006271 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006272 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006273}
6274
6275void AudioFlinger::DuplicatingThread::threadLoop_standby()
6276{
6277 // DuplicatingThread implements standby by stopping all tracks
6278 for (size_t i = 0; i < outputTracks.size(); i++) {
6279 outputTracks[i]->stop();
6280 }
6281}
6282
Andy Hung1bc088a2018-02-09 15:57:31 -08006283void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6284{
6285 MixerThread::dumpInternals(fd, args);
6286
6287 std::stringstream ss;
6288 const size_t numTracks = mOutputTracks.size();
6289 ss << " " << numTracks << " OutputTracks";
6290 if (numTracks > 0) {
6291 ss << ":";
6292 for (const auto &track : mOutputTracks) {
6293 const sp<ThreadBase> thread = track->thread().promote();
6294 ss << " (" << track->name() << " : ";
6295 if (thread.get() != nullptr) {
6296 ss << thread.get() << ", " << thread->id();
6297 } else {
6298 ss << "null";
6299 }
6300 ss << ")";
6301 }
6302 }
6303 ss << "\n";
6304 std::string result = ss.str();
6305 write(fd, result.c_str(), result.size());
6306}
6307
Eric Laurent81784c32012-11-19 14:55:58 -08006308void AudioFlinger::DuplicatingThread::saveOutputTracks()
6309{
6310 outputTracks = mOutputTracks;
6311}
6312
6313void AudioFlinger::DuplicatingThread::clearOutputTracks()
6314{
6315 outputTracks.clear();
6316}
6317
6318void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6319{
6320 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006321 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6322 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6323 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6324 const size_t frameCount =
6325 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6326 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6327 // from different OutputTracks and their associated MixerThreads (e.g. one may
6328 // nearly empty and the other may be dropping data).
6329
6330 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006331 this,
6332 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006333 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006334 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006335 frameCount,
6336 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006337 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6338 if (status != NO_ERROR) {
6339 ALOGE("addOutputTrack() initCheck failed %d", status);
6340 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006341 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006342 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6343 mOutputTracks.add(outputTrack);
6344 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6345 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006346}
6347
6348void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6349{
6350 Mutex::Autolock _l(mLock);
6351 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6352 if (mOutputTracks[i]->thread() == thread) {
6353 mOutputTracks[i]->destroy();
6354 mOutputTracks.removeAt(i);
6355 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006356 if (thread->getOutput() == mOutput) {
6357 mOutput = NULL;
6358 }
Eric Laurent81784c32012-11-19 14:55:58 -08006359 return;
6360 }
6361 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006362 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006363}
6364
6365// caller must hold mLock
6366void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6367{
6368 mWaitTimeMs = UINT_MAX;
6369 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6370 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6371 if (strong != 0) {
6372 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6373 if (waitTimeMs < mWaitTimeMs) {
6374 mWaitTimeMs = waitTimeMs;
6375 }
6376 }
6377 }
6378}
6379
6380
6381bool AudioFlinger::DuplicatingThread::outputsReady(
6382 const SortedVector< sp<OutputTrack> > &outputTracks)
6383{
6384 for (size_t i = 0; i < outputTracks.size(); i++) {
6385 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6386 if (thread == 0) {
6387 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6388 outputTracks[i].get());
6389 return false;
6390 }
6391 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6392 // see note at standby() declaration
6393 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6394 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6395 thread.get());
6396 return false;
6397 }
6398 }
6399 return true;
6400}
6401
Kevin Rocard12381092018-04-11 09:19:59 -07006402void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6403 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006404{
Kevin Rocard12381092018-04-11 09:19:59 -07006405 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6406 outputTrack->setMetadatas(metadata.tracks);
6407 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006408}
6409
Eric Laurent81784c32012-11-19 14:55:58 -08006410uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6411{
6412 return (mWaitTimeMs * 1000) / 2;
6413}
6414
6415void AudioFlinger::DuplicatingThread::cacheParameters_l()
6416{
6417 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6418 updateWaitTime_l();
6419
6420 MixerThread::cacheParameters_l();
6421}
6422
Eric Laurent6acd1d42017-01-04 14:23:29 -08006423
Eric Laurent81784c32012-11-19 14:55:58 -08006424// ----------------------------------------------------------------------------
6425// Record
6426// ----------------------------------------------------------------------------
6427
6428AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6429 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006430 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006431 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006432 audio_devices_t inDevice,
6433 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006434 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006435 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006436 mInput(input),
6437 mActiveTracks(&this->mLocalLog),
6438 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006439 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006440 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006441 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6442 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006443 // mFastCapture below
6444 , mFastCaptureFutex(0)
6445 // mInputSource
6446 // mPipeSink
6447 // mPipeSource
6448 , mPipeFramesP2(0)
6449 // mPipeMemory
6450 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006451 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006452 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006453{
Glenn Kastend7dca052015-03-05 16:05:54 -08006454 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6455 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006456
Andy Hungc8fddf32018-08-08 18:32:37 -07006457 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6458 mIsMsdDevice = strcmp(
6459 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6460 }
6461
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006462 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006463
Andy Hungc8fddf32018-08-08 18:32:37 -07006464 // TODO: We may also match on address as well as device type for
6465 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
6466 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
6467 "audio.timestamp.corrected_input_devices",
6468 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6469 : AUDIO_DEVICE_NONE));
6470
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006471 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006472 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006473 size_t numCounterOffers = 0;
6474 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006475#if !LOG_NDEBUG
6476 ssize_t index =
6477#else
6478 (void)
6479#endif
6480 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006481 ALOG_ASSERT(index == 0);
6482
6483 // initialize fast capture depending on configuration
6484 bool initFastCapture;
6485 switch (kUseFastCapture) {
6486 case FastCapture_Never:
6487 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006488 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006489 break;
6490 case FastCapture_Always:
6491 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006492 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006493 break;
6494 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006495 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006496 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6497 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6498 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006499 break;
6500 // case FastCapture_Dynamic:
6501 }
6502
6503 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006504 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006505 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006506 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6507 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006508 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006509 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006510 const sp<MemoryDealer> roHeap(readOnlyHeap());
6511 sp<IMemory> pipeMemory;
6512 if ((roHeap == 0) ||
6513 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006514 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6515 ALOGE("not enough memory for pipe buffer size=%zu; "
6516 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6517 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6518 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006519 goto failed;
6520 }
6521 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6522 memset(pipeBuffer, 0, pipeSize);
6523 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6524 const NBAIO_Format offers[1] = {format};
6525 size_t numCounterOffers = 0;
6526 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6527 ALOG_ASSERT(index == 0);
6528 mPipeSink = pipe;
6529 PipeReader *pipeReader = new PipeReader(*pipe);
6530 numCounterOffers = 0;
6531 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6532 ALOG_ASSERT(index == 0);
6533 mPipeSource = pipeReader;
6534 mPipeFramesP2 = pipeFramesP2;
6535 mPipeMemory = pipeMemory;
6536
6537 // create fast capture
6538 mFastCapture = new FastCapture();
6539 FastCaptureStateQueue *sq = mFastCapture->sq();
6540#ifdef STATE_QUEUE_DUMP
6541 // FIXME
6542#endif
6543 FastCaptureState *state = sq->begin();
6544 state->mCblk = NULL;
6545 state->mInputSource = mInputSource.get();
6546 state->mInputSourceGen++;
6547 state->mPipeSink = pipe;
6548 state->mPipeSinkGen++;
6549 state->mFrameCount = mFrameCount;
6550 state->mCommand = FastCaptureState::COLD_IDLE;
6551 // already done in constructor initialization list
6552 //mFastCaptureFutex = 0;
6553 state->mColdFutexAddr = &mFastCaptureFutex;
6554 state->mColdGen++;
6555 state->mDumpState = &mFastCaptureDumpState;
6556#ifdef TEE_SINK
6557 // FIXME
6558#endif
6559 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6560 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6561 sq->end();
6562 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6563
6564 // start the fast capture
6565 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6566 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006567 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006568 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006569#ifdef AUDIO_WATCHDOG
6570 // FIXME
6571#endif
6572
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006573 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006574 }
Andy Hung8946a282018-04-19 20:04:56 -07006575#ifdef TEE_SINK
6576 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6577 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6578#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006579failed: ;
6580
6581 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006582}
6583
Eric Laurent81784c32012-11-19 14:55:58 -08006584AudioFlinger::RecordThread::~RecordThread()
6585{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006586 if (mFastCapture != 0) {
6587 FastCaptureStateQueue *sq = mFastCapture->sq();
6588 FastCaptureState *state = sq->begin();
6589 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6590 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6591 if (old == -1) {
6592 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6593 }
6594 }
6595 state->mCommand = FastCaptureState::EXIT;
6596 sq->end();
6597 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6598 mFastCapture->join();
6599 mFastCapture.clear();
6600 }
6601 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006602 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006603 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006604}
6605
6606void AudioFlinger::RecordThread::onFirstRef()
6607{
Glenn Kastend7dca052015-03-05 16:05:54 -08006608 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006609}
6610
Eric Laurent555530a2017-02-07 18:17:24 -08006611void AudioFlinger::RecordThread::preExit()
6612{
6613 ALOGV(" preExit()");
6614 Mutex::Autolock _l(mLock);
6615 for (size_t i = 0; i < mTracks.size(); i++) {
6616 sp<RecordTrack> track = mTracks[i];
6617 track->invalidate();
6618 }
6619 mActiveTracks.clear();
6620 mStartStopCond.broadcast();
6621}
6622
Eric Laurent81784c32012-11-19 14:55:58 -08006623bool AudioFlinger::RecordThread::threadLoop()
6624{
Eric Laurent81784c32012-11-19 14:55:58 -08006625 nsecs_t lastWarning = 0;
6626
6627 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006628
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006629reacquire_wakelock:
6630 sp<RecordTrack> activeTrack;
6631 {
6632 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006633 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006634 }
6635
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006636 // used to request a deferred sleep, to be executed later while mutex is unlocked
6637 uint32_t sleepUs = 0;
6638
6639 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006640 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006641 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006642
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006643 // activeTracks accumulates a copy of a subset of mActiveTracks
6644 Vector< sp<RecordTrack> > activeTracks;
6645
Glenn Kasten735f45f2014-08-18 15:51:59 -07006646 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006647 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006648
Glenn Kasten735f45f2014-08-18 15:51:59 -07006649 // reference to a fast track which is about to be removed
6650 sp<RecordTrack> fastTrackToRemove;
6651
Eric Laurent81784c32012-11-19 14:55:58 -08006652 { // scope for mLock
6653 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006654
Eric Laurent021cf962014-05-13 10:18:14 -07006655 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006656
Eric Laurent000a4192014-01-29 15:17:32 -08006657 // check exitPending here because checkForNewParameters_l() and
6658 // checkForNewParameters_l() can temporarily release mLock
6659 if (exitPending()) {
6660 break;
6661 }
6662
Eric Laurent5c25d562016-07-13 17:17:45 -07006663 // sleep with mutex unlocked
6664 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006665 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006666 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6667 ATRACE_END();
6668 sleepUs = 0;
6669 continue;
6670 }
6671
Glenn Kasten2b806402013-11-20 16:37:38 -08006672 // if no active track(s), then standby and release wakelock
6673 size_t size = mActiveTracks.size();
6674 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006675 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006676 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006677 releaseWakeLock_l();
6678 ALOGV("RecordThread: loop stopping");
6679 // go to sleep
6680 mWaitWorkCV.wait(mLock);
6681 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006682 goto reacquire_wakelock;
6683 }
6684
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006685 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006686 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006687 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006688
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006689 activeTrack = mActiveTracks[i];
6690 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006691 if (activeTrack->isFastTrack()) {
6692 ALOG_ASSERT(fastTrackToRemove == 0);
6693 fastTrackToRemove = activeTrack;
6694 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006695 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006696 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006697 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006698 continue;
6699 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006700
6701 TrackBase::track_state activeTrackState = activeTrack->mState;
6702 switch (activeTrackState) {
6703
6704 case TrackBase::PAUSING:
6705 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006706 doBroadcast = true;
6707 size--;
6708 continue;
6709
6710 case TrackBase::STARTING_1:
6711 sleepUs = 10000;
6712 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006713 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006714 continue;
6715
6716 case TrackBase::STARTING_2:
6717 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006718 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006719 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006720 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006721 break;
6722
6723 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006724 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006725 break;
6726
6727 case TrackBase::IDLE:
6728 i++;
6729 continue;
6730
6731 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006732 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006733 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006734
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006735 activeTracks.add(activeTrack);
6736 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006737
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006738 if (activeTrack->isFastTrack()) {
6739 ALOG_ASSERT(!mFastTrackAvail);
6740 ALOG_ASSERT(fastTrack == 0);
6741 fastTrack = activeTrack;
6742 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006743 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006744
Andy Hungdae27702016-10-31 14:01:16 -07006745 mActiveTracks.updatePowerState(this);
6746
Kevin Rocard069c2712018-03-29 19:09:14 -07006747 updateMetadata_l();
6748
Eric Laurent5c25d562016-07-13 17:17:45 -07006749 if (allStopped) {
6750 standbyIfNotAlreadyInStandby();
6751 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006752 if (doBroadcast) {
6753 mStartStopCond.broadcast();
6754 }
6755
6756 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006757 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006758 if (sleepUs == 0) {
6759 sleepUs = kRecordThreadSleepUs;
6760 }
6761 continue;
6762 }
6763 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006764
Eric Laurent81784c32012-11-19 14:55:58 -08006765 lockEffectChains_l(effectChains);
6766 }
6767
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006768 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006769
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006770 size_t size = effectChains.size();
6771 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006772 // thread mutex is not locked, but effect chain is locked
6773 effectChains[i]->process_l();
6774 }
6775
Glenn Kasten735f45f2014-08-18 15:51:59 -07006776 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006777 if (mFastCapture != 0) {
6778 FastCaptureStateQueue *sq = mFastCapture->sq();
6779 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006780 bool didModify = false;
6781 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006782 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6783 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6784 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6785 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6786 if (old == -1) {
6787 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6788 }
6789 }
6790 state->mCommand = FastCaptureState::READ_WRITE;
6791#if 0 // FIXME
6792 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006793 FastThreadDumpState::kSamplingNforLowRamDevice :
6794 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006795#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006796 didModify = true;
6797 }
6798 audio_track_cblk_t *cblkOld = state->mCblk;
6799 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6800 if (cblkNew != cblkOld) {
6801 state->mCblk = cblkNew;
6802 // block until acked if removing a fast track
6803 if (cblkOld != NULL) {
6804 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6805 }
6806 didModify = true;
6807 }
jiabin01c8f562018-07-19 17:47:28 -07006808 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
6809 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
6810 if (state->mFastPatchRecordBufferProvider != abp) {
6811 state->mFastPatchRecordBufferProvider = abp;
6812 state->mFastPatchRecordFormat = fastTrack == 0 ?
6813 AUDIO_FORMAT_INVALID : fastTrack->format();
6814 didModify = true;
6815 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07006816 sq->end(didModify);
6817 if (didModify) {
6818 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006819#if 0
6820 if (kUseFastCapture == FastCapture_Dynamic) {
6821 mNormalSource = mPipeSource;
6822 }
6823#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006824 }
6825 }
6826
Glenn Kasten735f45f2014-08-18 15:51:59 -07006827 // now run the fast track destructor with thread mutex unlocked
6828 fastTrackToRemove.clear();
6829
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006830 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6831 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6832 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6833 // If destination is non-contiguous, first read past the nominal end of buffer, then
6834 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006835
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006836 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006837 ssize_t framesRead;
6838
6839 // If an NBAIO source is present, use it to read the normal capture's data
6840 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07006841 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006842
6843 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6844 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6845 // we immediately retry the read() to get data and prevent another overflow.
6846 for (int retries = 0; retries <= 2; ++retries) {
6847 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6848 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6849 framesToRead);
6850 if (framesRead != OVERRUN) break;
6851 }
6852
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006853 const ssize_t availableToRead = mPipeSource->availableToRead();
6854 if (availableToRead >= 0) {
6855 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6856 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6857 "more frames to read than fifo size, %zd > %zu",
6858 availableToRead, mPipeFramesP2);
6859 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6860 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6861 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6862 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006863 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6864 }
6865 if (framesRead < 0) {
6866 status_t status = (status_t) framesRead;
6867 switch (status) {
6868 case OVERRUN:
6869 ALOGW("overrun on read from pipe");
6870 framesRead = 0;
6871 break;
6872 case NEGOTIATE:
6873 ALOGE("re-negotiation is needed");
6874 framesRead = -1; // Will cause an attempt to recover.
6875 break;
6876 default:
6877 ALOGE("unknown error %d on read from pipe", status);
6878 break;
6879 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006880 }
6881 // otherwise use the HAL / AudioStreamIn directly
6882 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006883 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006884 size_t bytesRead;
6885 status_t result = mInput->stream->read(
6886 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006887 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006888 if (result < 0) {
6889 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006890 } else {
6891 framesRead = bytesRead / mFrameSize;
6892 }
6893 }
6894
Andy Hung3f0c9022016-01-15 17:49:46 -08006895 // Update server timestamp with server stats
6896 // systemTime() is optional if the hardware supports timestamps.
6897 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6898 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6899
6900 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006901 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006902 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006903 if (mStandby) {
6904 mTimestampVerifier.discontinuity();
Andy Hungc8fddf32018-08-08 18:32:37 -07006905 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR
6906 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
6907
6908 mTimestampVerifier.add(position, time, mSampleRate);
6909
6910 // Correct timestamps
6911 if (isTimestampCorrectionEnabled()) {
6912 ALOGV("TS_BEFORE: %d %lld %lld",
6913 id(), (long long)time, (long long)position);
6914 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
6915 position = correctedTimestamp.mFrames;
6916 time = correctedTimestamp.mTimeNs;
6917 ALOGV("TS_AFTER: %d %lld %lld",
6918 id(), (long long)time, (long long)position);
6919 }
6920
Andy Hung3f0c9022016-01-15 17:49:46 -08006921 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6922 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6923 // Note: In general record buffers should tend to be empty in
6924 // a properly running pipeline.
6925 //
6926 // Also, it is not advantageous to call get_presentation_position during the read
6927 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006928 } else {
6929 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08006930 }
6931 }
6932 // Use this to track timestamp information
6933 // ALOGD("%s", mTimestamp.toString().c_str());
6934
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006935 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006936 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006937 // Force input into standby so that it tries to recover at next read attempt
6938 inputStandBy();
6939 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006940 }
6941 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006942 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006943 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006944 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07006945 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006946
Andy Hung8946a282018-04-19 20:04:56 -07006947#ifdef TEE_SINK
6948 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6949#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006950 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006951 {
6952 size_t part1 = mRsmpInFramesP2 - rear;
6953 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006954 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006955 (framesRead - part1) * mFrameSize);
6956 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006957 }
6958 rear = mRsmpInRear += framesRead;
6959
6960 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006961
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006962 // loop over each active track
6963 for (size_t i = 0; i < size; i++) {
6964 activeTrack = activeTracks[i];
6965
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006966 // skip fast tracks, as those are handled directly by FastCapture
6967 if (activeTrack->isFastTrack()) {
6968 continue;
6969 }
6970
Andy Hung73c02e42015-03-29 01:13:58 -07006971 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006972 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6973
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006974 enum {
6975 OVERRUN_UNKNOWN,
6976 OVERRUN_TRUE,
6977 OVERRUN_FALSE
6978 } overrun = OVERRUN_UNKNOWN;
6979
6980 // loop over getNextBuffer to handle circular sink
6981 for (;;) {
6982
6983 activeTrack->mSink.frameCount = ~0;
6984 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6985 size_t framesOut = activeTrack->mSink.frameCount;
6986 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6987
Andy Hung73c02e42015-03-29 01:13:58 -07006988 // check available frames and handle overrun conditions
6989 // if the record track isn't draining fast enough.
6990 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006991 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006992 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6993 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006994 overrun = OVERRUN_TRUE;
6995 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006996 if (framesOut == 0 || framesIn == 0) {
6997 break;
6998 }
6999
Andy Hung6770c6f2015-04-07 13:43:36 -07007000 // Don't allow framesOut to be larger than what is possible with resampling
7001 // from framesIn.
7002 // This isn't strictly necessary but helps limit buffer resizing in
7003 // RecordBufferConverter. TODO: remove when no longer needed.
7004 framesOut = min(framesOut,
7005 destinationFramesPossible(
7006 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007007
7008 if (activeTrack->isDirect()) {
7009 // No RecordBufferConverter used for compressed formats. Pass
7010 // straight from RecordThread buffer to RecordTrack buffer.
7011 AudioBufferProvider::Buffer buffer;
7012 buffer.frameCount = framesOut;
7013 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7014 if (status == OK && buffer.frameCount != 0) {
7015 ALOGV_IF(buffer.frameCount != framesOut,
7016 "%s() read less than expected (%zu vs %zu)",
7017 __func__, buffer.frameCount, framesOut);
7018 framesOut = buffer.frameCount;
7019 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount);
7020 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7021 } else {
7022 framesOut = 0;
7023 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7024 __func__, status, buffer.frameCount);
7025 }
7026 } else {
7027 // process frames from the RecordThread buffer provider to the RecordTrack
7028 // buffer
7029 framesOut = activeTrack->mRecordBufferConverter->convert(
7030 activeTrack->mSink.raw,
7031 activeTrack->mResamplerBufferProvider,
7032 framesOut);
7033 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007034
7035 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7036 overrun = OVERRUN_FALSE;
7037 }
7038
7039 if (activeTrack->mFramesToDrop == 0) {
7040 if (framesOut > 0) {
7041 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007042 // Sanitize before releasing if the track has no access to the source data
7043 // An idle UID receives silence from non virtual devices until active
7044 if (activeTrack->isSilenced()) {
7045 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
7046 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007047 activeTrack->releaseBuffer(&activeTrack->mSink);
7048 }
7049 } else {
7050 // FIXME could do a partial drop of framesOut
7051 if (activeTrack->mFramesToDrop > 0) {
7052 activeTrack->mFramesToDrop -= framesOut;
7053 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007054 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007055 }
7056 } else {
7057 activeTrack->mFramesToDrop += framesOut;
7058 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7059 activeTrack->mSyncStartEvent->isCancelled()) {
7060 ALOGW("Synced record %s, session %d, trigger session %d",
7061 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7062 activeTrack->sessionId(),
7063 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007064 activeTrack->mSyncStartEvent->triggerSession() :
7065 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007066 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007067 }
7068 }
7069 }
7070
7071 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007072 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007073 }
7074 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007075
7076 switch (overrun) {
7077 case OVERRUN_TRUE:
7078 // client isn't retrieving buffers fast enough
7079 if (!activeTrack->setOverflow()) {
7080 nsecs_t now = systemTime();
7081 // FIXME should lastWarning per track?
7082 if ((now - lastWarning) > kWarningThrottleNs) {
7083 ALOGW("RecordThread: buffer overflow");
7084 lastWarning = now;
7085 }
7086 }
7087 break;
7088 case OVERRUN_FALSE:
7089 activeTrack->clearOverflow();
7090 break;
7091 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007092 break;
7093 }
7094
Andy Hung3f0c9022016-01-15 17:49:46 -08007095 // update frame information and push timestamp out
7096 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007097 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007098 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7099 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007100 }
7101
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007102unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007103 // enable changes in effect chain
7104 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007105 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08007106 }
7107
Glenn Kasten93e471f2013-08-19 08:40:07 -07007108 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007109
7110 {
7111 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007112 for (size_t i = 0; i < mTracks.size(); i++) {
7113 sp<RecordTrack> track = mTracks[i];
7114 track->invalidate();
7115 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007116 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007117 mStartStopCond.broadcast();
7118 }
7119
7120 releaseWakeLock();
7121
7122 ALOGV("RecordThread %p exiting", this);
7123 return false;
7124}
7125
Glenn Kasten93e471f2013-08-19 08:40:07 -07007126void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007127{
7128 if (!mStandby) {
7129 inputStandBy();
7130 mStandby = true;
7131 }
7132}
7133
7134void AudioFlinger::RecordThread::inputStandBy()
7135{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007136 // Idle the fast capture if it's currently running
7137 if (mFastCapture != 0) {
7138 FastCaptureStateQueue *sq = mFastCapture->sq();
7139 FastCaptureState *state = sq->begin();
7140 if (!(state->mCommand & FastCaptureState::IDLE)) {
7141 state->mCommand = FastCaptureState::COLD_IDLE;
7142 state->mColdFutexAddr = &mFastCaptureFutex;
7143 state->mColdGen++;
7144 mFastCaptureFutex = 0;
7145 sq->end();
7146 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7147 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7148#if 0
7149 if (kUseFastCapture == FastCapture_Dynamic) {
7150 // FIXME
7151 }
7152#endif
7153#ifdef AUDIO_WATCHDOG
7154 // FIXME
7155#endif
7156 } else {
7157 sq->end(false /*didModify*/);
7158 }
7159 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007160 status_t result = mInput->stream->standby();
7161 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007162
7163 // If going into standby, flush the pipe source.
7164 if (mPipeSource.get() != nullptr) {
7165 const ssize_t flushed = mPipeSource->flush();
7166 if (flushed > 0) {
7167 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7168 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7169 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7170 }
7171 }
Eric Laurent81784c32012-11-19 14:55:58 -08007172}
7173
Glenn Kasten05997e22014-03-13 15:08:33 -07007174// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007175sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007176 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007177 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007178 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007179 audio_format_t format,
7180 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007181 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007182 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007183 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007184 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007185 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007186 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007187 status_t *status,
7188 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007189{
Glenn Kasten74935e42013-12-19 08:56:45 -08007190 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007191 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007192 sp<RecordTrack> track;
7193 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007194 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007195 audio_input_flags_t requestedFlags = *flags;
7196 uint32_t sampleRate;
7197
7198 lStatus = initCheck();
7199 if (lStatus != NO_ERROR) {
7200 ALOGE("createRecordTrack_l() audio driver not initialized");
7201 goto Exit;
7202 }
7203
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007204 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7205 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7206 lStatus = BAD_VALUE;
7207 goto Exit;
7208 }
7209
Eric Laurentf14db3c2017-12-08 14:20:36 -08007210 if (*pSampleRate == 0) {
7211 *pSampleRate = mSampleRate;
7212 }
7213 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007214
7215 // special case for FAST flag considered OK if fast capture is present
7216 if (hasFastCapture()) {
7217 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7218 }
7219
Eric Laurentf14db3c2017-12-08 14:20:36 -08007220 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007221 if ((*flags & inputFlags) != *flags) {
7222 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7223 " input flags (%08x)",
7224 *flags, inputFlags);
7225 *flags = (audio_input_flags_t)(*flags & inputFlags);
7226 }
Eric Laurent81784c32012-11-19 14:55:58 -08007227
Glenn Kasten90e58b12013-07-31 16:16:02 -07007228 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007229 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007230 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007231 // we formerly checked for a callback handler (non-0 tid),
7232 // but that is no longer required for TRANSFER_OBTAIN mode
7233 //
Glenn Kasten74105912014-07-03 12:28:53 -07007234 // frame count is not specified, or is exactly the pipe depth
7235 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007236 // PCM data
7237 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007238 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007239 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007240 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007241 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007242 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007243 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007244 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007245 hasFastCapture() &&
7246 // there are sufficient fast track slots available
7247 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007248 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007249 // check compatibility with audio effects.
7250 Mutex::Autolock _l(mLock);
7251 // Do not accept FAST flag if the session has software effects
7252 sp<EffectChain> chain = getEffectChain_l(sessionId);
7253 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007254 audio_input_flags_t old = *flags;
7255 chain->checkInputFlagCompatibility(flags);
7256 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007257 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7258 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007259 }
7260 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007261 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007262 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7263 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007264 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007265 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7266 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007267 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007268 this, frameCount, mFrameCount, mPipeFramesP2,
7269 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007270 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007271 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007272 }
7273 }
7274
Eric Laurentf14db3c2017-12-08 14:20:36 -08007275 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7276 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7277 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7278 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7279 lStatus = BAD_TYPE;
7280 goto Exit;
7281 }
7282
Glenn Kasten74105912014-07-03 12:28:53 -07007283 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007284 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007285 // fast track: frame count is exactly the pipe depth
7286 frameCount = mPipeFramesP2;
7287 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007288 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007289 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007290 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7291 // or 20 ms if there is a fast capture
7292 // TODO This could be a roundupRatio inline, and const
7293 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7294 * sampleRate + mSampleRate - 1) / mSampleRate;
7295 // minimum number of notification periods is at least kMinNotifications,
7296 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7297 static const size_t kMinNotifications = 3;
7298 static const uint32_t kMinMs = 30;
7299 // TODO This could be a roundupRatio inline
7300 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7301 // TODO This could be a roundupRatio inline
7302 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7303 maxNotificationFrames;
7304 const size_t minFrameCount = maxNotificationFrames *
7305 max(kMinNotifications, minNotificationsByMs);
7306 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007307 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7308 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007309 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007310 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007311 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007312 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007313
7314 { // scope for mLock
7315 Mutex::Autolock _l(mLock);
7316
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007317 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007318 format, channelMask, frameCount,
7319 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007320 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007321
Glenn Kasten03003332013-08-06 15:40:54 -07007322 lStatus = track->initCheck();
7323 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007324 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007325 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007326 goto Exit;
7327 }
7328 mTracks.add(track);
7329
Eric Laurent05067782016-06-01 18:27:28 -07007330 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007331 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7332 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7333 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007334 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007335 }
Eric Laurent81784c32012-11-19 14:55:58 -08007336 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007337
Eric Laurent81784c32012-11-19 14:55:58 -08007338 lStatus = NO_ERROR;
7339
7340Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007341 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007342 return track;
7343}
7344
7345status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7346 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007347 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007348{
7349 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7350 sp<ThreadBase> strongMe = this;
7351 status_t status = NO_ERROR;
7352
7353 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007354 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007355 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007356 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007357 triggerSession,
7358 recordTrack->sessionId(),
7359 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007360 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007361 // Sync event can be cancelled by the trigger session if the track is not in a
7362 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007363 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007364 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007365 } else {
7366 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007367 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007368 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007369 }
7370 }
7371
7372 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007373 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007374 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007375 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7376 if (recordTrack->mState == TrackBase::PAUSING) {
7377 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007378 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007379 } else {
7380 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007381 }
7382 return status;
7383 }
7384
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007385 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7386 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7387 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007388 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007389 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007390 status_t status = NO_ERROR;
7391 if (recordTrack->isExternalTrack()) {
7392 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007393 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007394 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007395 mLock.lock();
7396 // FIXME should verify that recordTrack is still in mActiveTracks
7397 if (status != NO_ERROR) {
7398 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007399 recordTrack->clearSyncStartEvent();
7400 ALOGV("RecordThread::start error %d", status);
7401 return status;
7402 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007403 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007404 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007405 // Catch up with current buffer indices if thread is already running.
7406 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7407 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7408 // see previously buffered data before it called start(), but with greater risk of overrun.
7409
Andy Hung73c02e42015-03-29 01:13:58 -07007410 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007411 if (!recordTrack->isDirect()) {
7412 // clear any converter state as new data will be discontinuous
7413 recordTrack->mRecordBufferConverter->reset();
7414 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007415 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007416 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007417 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007418 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007419 ALOGV("Record failed to start");
7420 status = BAD_VALUE;
7421 goto startError;
7422 }
Eric Laurent81784c32012-11-19 14:55:58 -08007423 return status;
7424 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007425
Eric Laurent81784c32012-11-19 14:55:58 -08007426startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007427 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007428 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007429 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007430 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007431 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007432 return status;
7433}
7434
Eric Laurent81784c32012-11-19 14:55:58 -08007435void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7436{
7437 sp<SyncEvent> strongEvent = event.promote();
7438
7439 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007440 sp<RefBase> ptr = strongEvent->cookie().promote();
7441 if (ptr != 0) {
7442 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7443 recordTrack->handleSyncStartEvent(strongEvent);
7444 }
Eric Laurent81784c32012-11-19 14:55:58 -08007445 }
7446}
7447
Glenn Kastena8356f62013-07-25 14:37:52 -07007448bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007449 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007450 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007451 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007452 return false;
7453 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007454 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007455 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007456 // signal thread to stop
7457 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007458 // do not wait for mStartStopCond if exiting
7459 if (exitPending()) {
7460 return true;
7461 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007462 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007463 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007464 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007465 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007466 ALOGV("Record stopped OK");
7467 return true;
7468 }
7469 return false;
7470}
7471
Glenn Kasten0f11b512014-01-31 16:18:54 -08007472bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007473{
7474 return false;
7475}
7476
Glenn Kasten0f11b512014-01-31 16:18:54 -08007477status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007478{
7479#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7480 if (!isValidSyncEvent(event)) {
7481 return BAD_VALUE;
7482 }
7483
Glenn Kastend848eb42016-03-08 13:42:11 -08007484 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007485 status_t ret = NAME_NOT_FOUND;
7486
7487 Mutex::Autolock _l(mLock);
7488
7489 for (size_t i = 0; i < mTracks.size(); i++) {
7490 sp<RecordTrack> track = mTracks[i];
7491 if (eventSession == track->sessionId()) {
7492 (void) track->setSyncEvent(event);
7493 ret = NO_ERROR;
7494 }
7495 }
7496 return ret;
7497#else
7498 return BAD_VALUE;
7499#endif
7500}
7501
jiabin653cc0a2018-01-17 17:54:10 -08007502status_t AudioFlinger::RecordThread::getActiveMicrophones(
7503 std::vector<media::MicrophoneInfo>* activeMicrophones)
7504{
7505 ALOGV("RecordThread::getActiveMicrophones");
7506 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007507 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7508 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007509}
7510
Kevin Rocard069c2712018-03-29 19:09:14 -07007511void AudioFlinger::RecordThread::updateMetadata_l()
7512{
7513 if (mInput == nullptr || mInput->stream == nullptr ||
7514 !mActiveTracks.readAndClearHasChanged()) {
7515 return;
7516 }
7517 StreamInHalInterface::SinkMetadata metadata;
7518 for (const sp<RecordTrack> &track : mActiveTracks) {
7519 // No track is invalid as this is called after prepareTrack_l in the same critical section
7520 metadata.tracks.push_back({
7521 .source = track->attributes().source,
7522 .gain = 1, // capture tracks do not have volumes
7523 });
7524 }
7525 mInput->stream->updateSinkMetadata(metadata);
7526}
7527
Eric Laurent81784c32012-11-19 14:55:58 -08007528// destroyTrack_l() must be called with ThreadBase::mLock held
7529void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7530{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007531 track->terminate();
7532 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007533 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007534 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007535 removeTrack_l(track);
7536 }
7537}
7538
7539void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7540{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007541 String8 result;
7542 track->appendDump(result, false /* active */);
7543 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7544
Eric Laurent81784c32012-11-19 14:55:58 -08007545 mTracks.remove(track);
7546 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007547 if (track->isFastTrack()) {
7548 ALOG_ASSERT(!mFastTrackAvail);
7549 mFastTrackAvail = true;
7550 }
Eric Laurent81784c32012-11-19 14:55:58 -08007551}
7552
7553void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7554{
7555 dumpInternals(fd, args);
7556 dumpTracks(fd, args);
7557 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007558 dprintf(fd, " Local log:\n");
7559 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007560}
7561
7562void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7563{
Glenn Kasten44182c22015-03-05 17:12:23 -08007564 dumpBase(fd, args);
7565
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007566 AudioStreamIn *input = mInput;
7567 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7568 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7569 input, flags, inputFlagsToString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007570 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007571 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007572 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007573 }
Andy Hungbfa64962017-06-12 14:43:19 -07007574
7575 if (input != nullptr) {
7576 dprintf(fd, " Hal stream dump:\n");
7577 (void)input->stream->dump(fd);
7578 }
7579
Andy Hung7f39f562018-08-08 17:30:20 -07007580 const double latencyMs = audio_is_linear_pcm(mFormat)
7581 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
Andy Hung20bd30b2018-06-01 15:39:35 -07007582 if (latencyMs != 0.) {
7583 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7584 } else {
7585 dprintf(fd, " NormalRecord latency ms: unavail\n");
7586 }
7587
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007588 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007589 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007590
Glenn Kasten2f90c512015-12-02 11:40:09 -08007591 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7592 // while we are dumping it. It may be inconsistent, but it won't mutate!
7593 // This is a large object so we place it on the heap.
7594 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan7b651152018-07-13 10:17:19 -07007595 std::unique_ptr<FastCaptureDumpState> copy(new FastCaptureDumpState(mFastCaptureDumpState));
Glenn Kasten2f90c512015-12-02 11:40:09 -08007596 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007597}
7598
Glenn Kasten0f11b512014-01-31 16:18:54 -08007599void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007600{
Eric Laurent81784c32012-11-19 14:55:58 -08007601 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007602 size_t numtracks = mTracks.size();
7603 size_t numactive = mActiveTracks.size();
7604 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007605 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007606 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007607 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007608 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007609 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007610 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007611 for (size_t i = 0; i < numtracks ; ++i) {
7612 sp<RecordTrack> track = mTracks[i];
7613 if (track != 0) {
7614 bool active = mActiveTracks.indexOf(track) >= 0;
7615 if (active) {
7616 numactiveseen++;
7617 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007618 result.append(prefix);
7619 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007620 }
Eric Laurent81784c32012-11-19 14:55:58 -08007621 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007622 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007623 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007624 }
7625
Marco Nelissenb2208842014-02-07 14:00:50 -08007626 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007627 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007628 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007629 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007630 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007631 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007632 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007633 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007634 result.append(prefix);
7635 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007636 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007637 }
Eric Laurent81784c32012-11-19 14:55:58 -08007638
7639 }
7640 write(fd, result.string(), result.size());
7641}
7642
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007643void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7644{
7645 Mutex::Autolock _l(mLock);
7646 for (size_t i = 0; i < mTracks.size() ; i++) {
7647 sp<RecordTrack> track = mTracks[i];
7648 if (track != 0 && track->uid() == uid) {
7649 track->setSilenced(silenced);
7650 }
7651 }
7652}
Andy Hung73c02e42015-03-29 01:13:58 -07007653
7654void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7655{
7656 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7657 RecordThread *recordThread = (RecordThread *) threadBase.get();
7658 mRsmpInFront = recordThread->mRsmpInRear;
7659 mRsmpInUnrel = 0;
7660}
7661
7662void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7663 size_t *framesAvailable, bool *hasOverrun)
7664{
7665 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7666 RecordThread *recordThread = (RecordThread *) threadBase.get();
7667 const int32_t rear = recordThread->mRsmpInRear;
7668 const int32_t front = mRsmpInFront;
7669 const ssize_t filled = rear - front;
7670
7671 size_t framesIn;
7672 bool overrun = false;
7673 if (filled < 0) {
7674 // should not happen, but treat like a massive overrun and re-sync
7675 framesIn = 0;
7676 mRsmpInFront = rear;
7677 overrun = true;
7678 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7679 framesIn = (size_t) filled;
7680 } else {
7681 // client is not keeping up with server, but give it latest data
7682 framesIn = recordThread->mRsmpInFrames;
7683 mRsmpInFront = /* front = */ rear - framesIn;
7684 overrun = true;
7685 }
7686 if (framesAvailable != NULL) {
7687 *framesAvailable = framesIn;
7688 }
7689 if (hasOverrun != NULL) {
7690 *hasOverrun = overrun;
7691 }
7692}
7693
Eric Laurent81784c32012-11-19 14:55:58 -08007694// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007695status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007696 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007697{
Andy Hung73c02e42015-03-29 01:13:58 -07007698 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007699 if (threadBase == 0) {
7700 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007701 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007702 return NOT_ENOUGH_DATA;
7703 }
7704 RecordThread *recordThread = (RecordThread *) threadBase.get();
7705 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007706 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007707 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007708 // FIXME should not be P2 (don't want to increase latency)
7709 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007710 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007711 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007712 front &= recordThread->mRsmpInFramesP2 - 1;
7713 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007714 if (part1 > (size_t) filled) {
7715 part1 = filled;
7716 }
7717 size_t ask = buffer->frameCount;
7718 ALOG_ASSERT(ask > 0);
7719 if (part1 > ask) {
7720 part1 = ask;
7721 }
7722 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007723 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007724 buffer->raw = NULL;
7725 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007726 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007727 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007728 }
7729
Andy Hung57446612015-04-19 23:56:46 -07007730 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007731 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007732 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007733 return NO_ERROR;
7734}
7735
7736// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007737void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7738 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007739{
Glenn Kasten85948432013-08-19 12:09:05 -07007740 size_t stepCount = buffer->frameCount;
7741 if (stepCount == 0) {
7742 return;
7743 }
Andy Hung73c02e42015-03-29 01:13:58 -07007744 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7745 mRsmpInUnrel -= stepCount;
7746 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007747 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007748 buffer->frameCount = 0;
7749}
7750
Eric Laurentd8365c52017-07-16 15:27:05 -07007751void AudioFlinger::RecordThread::checkBtNrec()
7752{
7753 Mutex::Autolock _l(mLock);
7754 checkBtNrec_l();
7755}
7756
7757void AudioFlinger::RecordThread::checkBtNrec_l()
7758{
7759 // disable AEC and NS if the device is a BT SCO headset supporting those
7760 // pre processings
7761 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7762 mAudioFlinger->btNrecIsOff();
7763 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7764 for (size_t i = 0; i < mEffectChains.size(); i++) {
7765 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7766 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7767 }
7768 }
7769}
7770
Andy Hung97a893e2015-03-29 01:03:07 -07007771
Eric Laurent10351942014-05-08 18:49:52 -07007772bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7773 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007774{
7775 bool reconfig = false;
7776
Eric Laurent10351942014-05-08 18:49:52 -07007777 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007778
Eric Laurent10351942014-05-08 18:49:52 -07007779 audio_format_t reqFormat = mFormat;
7780 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007781 // 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 -07007782 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7783
7784 AudioParameter param = AudioParameter(keyValuePair);
7785 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007786
7787 // scope for AutoPark extends to end of method
7788 AutoPark<FastCapture> park(mFastCapture);
7789
Eric Laurent10351942014-05-08 18:49:52 -07007790 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7791 // channel count change can be requested. Do we mandate the first client defines the
7792 // HAL sampling rate and channel count or do we allow changes on the fly?
7793 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7794 samplingRate = value;
7795 reconfig = true;
7796 }
7797 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007798 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007799 status = BAD_VALUE;
7800 } else {
7801 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007802 reconfig = true;
7803 }
Eric Laurent10351942014-05-08 18:49:52 -07007804 }
7805 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7806 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007807 if (!audio_is_input_channel(mask) ||
7808 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007809 status = BAD_VALUE;
7810 } else {
7811 channelMask = mask;
7812 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007813 }
Eric Laurent10351942014-05-08 18:49:52 -07007814 }
7815 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7816 // do not accept frame count changes if tracks are open as the track buffer
7817 // size depends on frame count and correct behavior would not be guaranteed
7818 // if frame count is changed after track creation
7819 if (mActiveTracks.size() > 0) {
7820 status = INVALID_OPERATION;
7821 } else {
7822 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007823 }
Eric Laurent10351942014-05-08 18:49:52 -07007824 }
7825 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7826 // forward device change to effects that have requested to be
7827 // aware of attached audio device.
7828 for (size_t i = 0; i < mEffectChains.size(); i++) {
7829 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007830 }
Eric Laurent81784c32012-11-19 14:55:58 -08007831
Eric Laurent10351942014-05-08 18:49:52 -07007832 // store input device and output device but do not forward output device to audio HAL.
7833 // Note that status is ignored by the caller for output device
7834 // (see AudioFlinger::setParameters()
7835 if (audio_is_output_devices(value)) {
7836 mOutDevice = value;
7837 status = BAD_VALUE;
7838 } else {
7839 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007840 if (value != AUDIO_DEVICE_NONE) {
7841 mPrevInDevice = value;
7842 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007843 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007844 }
Eric Laurent10351942014-05-08 18:49:52 -07007845 }
7846 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7847 mAudioSource != (audio_source_t)value) {
7848 // forward device change to effects that have requested to be
7849 // aware of attached audio device.
7850 for (size_t i = 0; i < mEffectChains.size(); i++) {
7851 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007852 }
Eric Laurent10351942014-05-08 18:49:52 -07007853 mAudioSource = (audio_source_t)value;
7854 }
Glenn Kastene198c362013-08-13 09:13:36 -07007855
Eric Laurent10351942014-05-08 18:49:52 -07007856 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007857 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007858 if (status == INVALID_OPERATION) {
7859 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007860 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007861 }
7862 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007863 if (status == BAD_VALUE) {
7864 uint32_t sRate;
7865 audio_channel_mask_t channelMask;
7866 audio_format_t format;
7867 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7868 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7869 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7870 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7871 status = NO_ERROR;
7872 }
Eric Laurent81784c32012-11-19 14:55:58 -08007873 }
Eric Laurent10351942014-05-08 18:49:52 -07007874 if (status == NO_ERROR) {
7875 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007876 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007877 }
7878 }
Eric Laurent81784c32012-11-19 14:55:58 -08007879 }
Eric Laurent10351942014-05-08 18:49:52 -07007880
Eric Laurent81784c32012-11-19 14:55:58 -08007881 return reconfig;
7882}
7883
7884String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7885{
Eric Laurent81784c32012-11-19 14:55:58 -08007886 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007887 if (initCheck() == NO_ERROR) {
7888 String8 out_s8;
7889 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7890 return out_s8;
7891 }
Eric Laurent81784c32012-11-19 14:55:58 -08007892 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007893 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007894}
7895
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007896void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007897 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7898
7899 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007900
7901 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007902 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007903 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007904 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007905 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007906 desc->mChannelMask = mChannelMask;
7907 desc->mSamplingRate = mSampleRate;
7908 desc->mFormat = mFormat;
7909 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007910 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007911 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007912 break;
7913
Eric Laurent73e26b62015-04-27 16:55:58 -07007914 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007915 default:
7916 break;
7917 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007918 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007919}
7920
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007921void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007922{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007923 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7924 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07007925 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007926 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
7927 if (audio_is_linear_pcm(mFormat)) {
7928 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
7929 mChannelCount, FCC_8);
7930 } else {
7931 // Can have more that FCC_8 channels in encoded streams.
7932 ALOGI("HAL format %#x is not linear pcm", mFormat);
7933 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007934 result = mInput->stream->getFrameSize(&mFrameSize);
7935 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7936 result = mInput->stream->getBufferSize(&mBufferSize);
7937 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007938 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007939 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7940 "mBufferSize=%lld, mFrameCount=%lld",
7941 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7942 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007943 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007944 // 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 -07007945 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007946 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007947 // A larger value should allow more old data to be read after a track calls start(),
7948 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007949 //
7950 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007951 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007952 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007953 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007954 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007955
7956 // TODO optimize audio capture buffer sizes ...
7957 // Here we calculate the size of the sliding buffer used as a source
7958 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7959 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7960 // be better to have it derived from the pipe depth in the long term.
7961 // The current value is higher than necessary. However it should not add to latency.
7962
Glenn Kasten85948432013-08-19 12:09:05 -07007963 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007964 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7965 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007966 // if posix_memalign fails, will segv here.
7967 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007968
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007969 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7970 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007971}
7972
Glenn Kasten5f972c02014-01-13 09:59:31 -08007973uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007974{
7975 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007976 uint32_t result;
7977 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7978 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007979 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007980 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007981}
7982
Eric Laurent4c415062016-06-17 16:14:16 -07007983// hasAudioSession_l() must be called with ThreadBase::mLock held
7984uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007985{
Eric Laurent81784c32012-11-19 14:55:58 -08007986 uint32_t result = 0;
7987 if (getEffectChain_l(sessionId) != 0) {
7988 result = EFFECT_SESSION;
7989 }
7990
7991 for (size_t i = 0; i < mTracks.size(); ++i) {
7992 if (sessionId == mTracks[i]->sessionId()) {
7993 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007994 if (mTracks[i]->isFastTrack()) {
7995 result |= FAST_SESSION;
7996 }
Eric Laurent81784c32012-11-19 14:55:58 -08007997 break;
7998 }
7999 }
8000
8001 return result;
8002}
8003
Glenn Kastend848eb42016-03-08 13:42:11 -08008004KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008005{
Glenn Kastend848eb42016-03-08 13:42:11 -08008006 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008007 Mutex::Autolock _l(mLock);
8008 for (size_t j = 0; j < mTracks.size(); ++j) {
8009 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008010 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008011 if (ids.indexOfKey(sessionId) < 0) {
8012 ids.add(sessionId, true);
8013 }
8014 }
8015 return ids;
8016}
8017
8018AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8019{
8020 Mutex::Autolock _l(mLock);
8021 AudioStreamIn *input = mInput;
8022 mInput = NULL;
8023 return input;
8024}
8025
8026// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008027sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008028{
8029 if (mInput == NULL) {
8030 return NULL;
8031 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008032 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008033}
8034
8035status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8036{
8037 // only one chain per input thread
Eric Tan39ec8d62018-07-24 09:49:29 -07008038 if (!mEffectChains.isEmpty()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07008039 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08008040 return INVALID_OPERATION;
8041 }
8042 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008043 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008044 chain->setInBuffer(NULL);
8045 chain->setOutBuffer(NULL);
8046
8047 checkSuspendOnAddEffectChain_l(chain);
8048
Eric Laurent1b928682014-10-02 19:41:47 -07008049 // make sure enabled pre processing effects state is communicated to the HAL as we
8050 // just moved them to a new input stream.
8051 chain->syncHalEffectsState();
8052
Eric Laurent81784c32012-11-19 14:55:58 -08008053 mEffectChains.add(chain);
8054
8055 return NO_ERROR;
8056}
8057
8058size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8059{
8060 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
8061 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008062 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08008063 chain.get(), mEffectChains.size(), this);
8064 if (mEffectChains.size() == 1) {
8065 mEffectChains.removeAt(0);
8066 }
8067 return 0;
8068}
8069
Eric Laurent1c333e22014-05-20 10:48:17 -07008070status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8071 audio_patch_handle_t *handle)
8072{
8073 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008074
8075 // store new device and send to effects
8076 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07008077 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07008078 for (size_t i = 0; i < mEffectChains.size(); i++) {
8079 mEffectChains[i]->setDevice_l(mInDevice);
8080 }
8081
Eric Laurentd8365c52017-07-16 15:27:05 -07008082 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008083
8084 // store new source and send to effects
8085 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8086 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008087 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008088 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008089 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008090 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008091
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008092 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008093 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8094 status = hwDevice->createAudioPatch(patch->num_sources,
8095 patch->sources,
8096 patch->num_sinks,
8097 patch->sinks,
8098 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008099 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008100 char *address;
8101 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8102 address = audio_device_address_to_parameter(
8103 patch->sources[0].ext.device.type,
8104 patch->sources[0].ext.device.address);
8105 } else {
8106 address = (char *)calloc(1, 1);
8107 }
8108 AudioParameter param = AudioParameter(String8(address));
8109 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008110 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008111 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008112 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008113 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008114 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008115 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008116 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008117
Eric Laurente8726fe2015-06-26 09:39:24 -07008118 if (mInDevice != mPrevInDevice) {
8119 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8120 mPrevInDevice = mInDevice;
8121 }
Eric Laurent296fb132015-05-01 11:38:42 -07008122
Eric Laurent1c333e22014-05-20 10:48:17 -07008123 return status;
8124}
8125
8126status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8127{
8128 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008129
8130 mInDevice = AUDIO_DEVICE_NONE;
8131
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008132 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008133 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8134 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008135 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008136 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008137 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008138 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008139 }
8140 return status;
8141}
8142
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008143void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008144{
8145 Mutex::Autolock _l(mLock);
8146 mTracks.add(record);
8147}
8148
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008149void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008150{
8151 Mutex::Autolock _l(mLock);
8152 destroyTrack_l(record);
8153}
8154
Mikhail Naganovdc769682018-05-04 15:34:08 -07008155void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008156{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008157 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008158 config->role = AUDIO_PORT_ROLE_SINK;
8159 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8160 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008161 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8162 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8163 config->flags.input = mInput->flags;
8164 }
Eric Laurent83b88082014-06-20 18:31:16 -07008165}
Eric Laurent1c333e22014-05-20 10:48:17 -07008166
Eric Laurent6acd1d42017-01-04 14:23:29 -08008167// ----------------------------------------------------------------------------
8168// Mmap
8169// ----------------------------------------------------------------------------
8170
8171AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8172 : mThread(thread)
8173{
Phil Burk9fabbf82017-08-03 12:02:00 -07008174 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008175}
8176
8177AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8178{
Phil Burk9fabbf82017-08-03 12:02:00 -07008179 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008180}
8181
8182status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8183 struct audio_mmap_buffer_info *info)
8184{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008185 return mThread->createMmapBuffer(minSizeFrames, info);
8186}
8187
8188status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8189{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008190 return mThread->getMmapPosition(position);
8191}
8192
Eric Laurenta54f1282017-07-01 19:39:32 -07008193status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008194 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008195
8196{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008197 return mThread->start(client, handle);
8198}
8199
8200status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8201{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008202 return mThread->stop(handle);
8203}
8204
Eric Laurent18b57012017-02-13 16:23:52 -08008205status_t AudioFlinger::MmapThreadHandle::standby()
8206{
Eric Laurent18b57012017-02-13 16:23:52 -08008207 return mThread->standby();
8208}
8209
Eric Laurent6acd1d42017-01-04 14:23:29 -08008210
8211AudioFlinger::MmapThread::MmapThread(
8212 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8213 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8214 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8215 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008216 mSessionId(AUDIO_SESSION_NONE),
8217 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008218 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008219 mActiveTracks(&this->mLocalLog),
8220 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8221 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008222{
Eric Laurent18b57012017-02-13 16:23:52 -08008223 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008224 readHalParameters_l();
8225}
8226
8227AudioFlinger::MmapThread::~MmapThread()
8228{
Eric Laurent18b57012017-02-13 16:23:52 -08008229 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008230}
8231
8232void AudioFlinger::MmapThread::onFirstRef()
8233{
8234 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8235}
8236
8237void AudioFlinger::MmapThread::disconnect()
8238{
Eric Laurent331679c2018-04-16 17:03:16 -07008239 ActiveTracks<MmapTrack> activeTracks;
8240 {
8241 Mutex::Autolock _l(mLock);
8242 for (const sp<MmapTrack> &t : mActiveTracks) {
8243 activeTracks.add(t);
8244 }
8245 }
8246 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008247 stop(t->portId());
8248 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008249 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008250 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008251 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008252 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008253 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008254 }
8255}
8256
8257
8258void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8259 audio_stream_type_t streamType __unused,
8260 audio_session_t sessionId,
8261 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008262 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008263 audio_port_handle_t portId)
8264{
8265 mAttr = *attr;
8266 mSessionId = sessionId;
8267 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008268 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008269 mPortId = portId;
8270}
8271
8272status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8273 struct audio_mmap_buffer_info *info)
8274{
8275 if (mHalStream == 0) {
8276 return NO_INIT;
8277 }
Eric Laurent18b57012017-02-13 16:23:52 -08008278 mStandby = true;
8279 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008280 return mHalStream->createMmapBuffer(minSizeFrames, info);
8281}
8282
8283status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8284{
8285 if (mHalStream == 0) {
8286 return NO_INIT;
8287 }
8288 return mHalStream->getMmapPosition(position);
8289}
8290
Eric Laurent331679c2018-04-16 17:03:16 -07008291status_t AudioFlinger::MmapThread::exitStandby()
8292{
8293 status_t ret = mHalStream->start();
8294 if (ret != NO_ERROR) {
8295 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8296 return ret;
8297 }
8298 mStandby = false;
8299 return NO_ERROR;
8300}
8301
Eric Laurenta54f1282017-07-01 19:39:32 -07008302status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008303 audio_port_handle_t *handle)
8304{
Eric Laurenta54f1282017-07-01 19:39:32 -07008305 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8306 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008307 if (mHalStream == 0) {
8308 return NO_INIT;
8309 }
8310
8311 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008312
Eric Laurenta54f1282017-07-01 19:39:32 -07008313 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008314 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008315 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008316 }
8317
8318 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8319
8320 audio_io_handle_t io = mId;
8321 if (isOutput()) {
8322 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8323 config.sample_rate = mSampleRate;
8324 config.channel_mask = mChannelMask;
8325 config.format = mFormat;
8326 audio_stream_type_t stream = streamType();
8327 audio_output_flags_t flags =
8328 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008329 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008330 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8331 mSessionId,
8332 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008333 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008334 client.clientUid,
8335 &config,
8336 flags,
8337 &deviceId,
8338 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008339 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008340 audio_config_base_t config;
8341 config.sample_rate = mSampleRate;
8342 config.channel_mask = mChannelMask;
8343 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008344 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008345 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8346 mSessionId,
8347 client.clientPid,
8348 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008349 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008350 &config,
8351 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8352 &deviceId,
8353 &portId);
8354 }
8355 // APM should not chose a different input or output stream for the same set of attributes
8356 // and audo configuration
8357 if (ret != NO_ERROR || io != mId) {
8358 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8359 __FUNCTION__, ret, io, mId);
8360 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008361 }
8362
Eric Laurent331679c2018-04-16 17:03:16 -07008363 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008364 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008365 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008366 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008367 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008368 }
8369
Eric Laurent331679c2018-04-16 17:03:16 -07008370 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008371 // abort if start is rejected by audio policy manager
8372 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008373 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008374 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008375 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008376 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008377 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008378 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008379 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008380 }
Eric Laurent331679c2018-04-16 17:03:16 -07008381 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008382 } else {
8383 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008384 }
8385 return PERMISSION_DENIED;
8386 }
8387
Eric Laurent67f97292018-04-20 18:05:41 -07008388 if (isOutput()) {
8389 // force volume update when a new track is added
8390 mHalVolFloat = -1.0f;
8391 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008392 for (const sp<MmapTrack> &track : mActiveTracks) {
8393 if (track->isSilenced_l() && track->uid() != client.clientUid)
8394 track->invalidate();
8395 }
8396 }
8397
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008398 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8399 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008400 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008401
Eric Laurent331679c2018-04-16 17:03:16 -07008402 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008403 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008404 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008405 if (chain != 0) {
8406 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8407 chain->incTrackCnt();
8408 chain->incActiveTrackCnt();
8409 }
8410
8411 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008412 broadcast_l();
8413
Eric Laurenta54f1282017-07-01 19:39:32 -07008414 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008415
8416 return NO_ERROR;
8417}
8418
8419status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8420{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008421 ALOGV("%s handle %d", __FUNCTION__, handle);
8422
8423 if (mHalStream == 0) {
8424 return NO_INIT;
8425 }
8426
Eric Laurenta54f1282017-07-01 19:39:32 -07008427 if (handle == mPortId) {
8428 mHalStream->stop();
8429 return NO_ERROR;
8430 }
8431
Eric Laurent331679c2018-04-16 17:03:16 -07008432 Mutex::Autolock _l(mLock);
8433
Eric Laurent6acd1d42017-01-04 14:23:29 -08008434 sp<MmapTrack> track;
8435 for (const sp<MmapTrack> &t : mActiveTracks) {
8436 if (handle == t->portId()) {
8437 track = t;
8438 break;
8439 }
8440 }
8441 if (track == 0) {
8442 return BAD_VALUE;
8443 }
8444
8445 mActiveTracks.remove(track);
8446
Eric Laurent331679c2018-04-16 17:03:16 -07008447 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008448 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008449 AudioSystem::stopOutput(track->portId());
8450 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008451 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008452 AudioSystem::stopInput(track->portId());
8453 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008454 }
Eric Laurent331679c2018-04-16 17:03:16 -07008455 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008456
8457 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8458 if (chain != 0) {
8459 chain->decActiveTrackCnt();
8460 chain->decTrackCnt();
8461 }
8462
8463 broadcast_l();
8464
Eric Laurent6acd1d42017-01-04 14:23:29 -08008465 return NO_ERROR;
8466}
8467
Eric Laurent18b57012017-02-13 16:23:52 -08008468status_t AudioFlinger::MmapThread::standby()
8469{
8470 ALOGV("%s", __FUNCTION__);
8471
8472 if (mHalStream == 0) {
8473 return NO_INIT;
8474 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008475 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008476 return INVALID_OPERATION;
8477 }
8478 mHalStream->standby();
8479 mStandby = true;
8480 releaseWakeLock();
8481 return NO_ERROR;
8482}
8483
Eric Laurent6acd1d42017-01-04 14:23:29 -08008484
8485void AudioFlinger::MmapThread::readHalParameters_l()
8486{
8487 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8488 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8489 mFormat = mHALFormat;
8490 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8491 result = mHalStream->getFrameSize(&mFrameSize);
8492 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8493 result = mHalStream->getBufferSize(&mBufferSize);
8494 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8495 mFrameCount = mBufferSize / mFrameSize;
8496}
8497
8498bool AudioFlinger::MmapThread::threadLoop()
8499{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008500 checkSilentMode_l();
8501
8502 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8503
8504 while (!exitPending())
8505 {
8506 Mutex::Autolock _l(mLock);
8507 Vector< sp<EffectChain> > effectChains;
8508
8509 if (mSignalPending) {
8510 // A signal was raised while we were unlocked
8511 mSignalPending = false;
8512 } else {
8513 if (mConfigEvents.isEmpty()) {
8514 // we're about to wait, flush the binder command buffer
8515 IPCThreadState::self()->flushCommands();
8516
8517 if (exitPending()) {
8518 break;
8519 }
8520
Eric Laurent6acd1d42017-01-04 14:23:29 -08008521 // wait until we have something to do...
8522 ALOGV("%s going to sleep", myName.string());
8523 mWaitWorkCV.wait(mLock);
8524 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008525
8526 checkSilentMode_l();
8527
8528 continue;
8529 }
8530 }
8531
8532 processConfigEvents_l();
8533
8534 processVolume_l();
8535
8536 checkInvalidTracks_l();
8537
8538 mActiveTracks.updatePowerState(this);
8539
Kevin Rocard069c2712018-03-29 19:09:14 -07008540 updateMetadata_l();
8541
Eric Laurent6acd1d42017-01-04 14:23:29 -08008542 lockEffectChains_l(effectChains);
8543 for (size_t i = 0; i < effectChains.size(); i ++) {
8544 effectChains[i]->process_l();
8545 }
8546 // enable changes in effect chain
8547 unlockEffectChains(effectChains);
8548 // Effect chains will be actually deleted here if they were removed from
8549 // mEffectChains list during mixing or effects processing
8550 }
8551
8552 threadLoop_exit();
8553
8554 if (!mStandby) {
8555 threadLoop_standby();
8556 mStandby = true;
8557 }
8558
Eric Laurent6acd1d42017-01-04 14:23:29 -08008559 ALOGV("Thread %p type %d exiting", this, mType);
8560 return false;
8561}
8562
8563// checkForNewParameter_l() must be called with ThreadBase::mLock held
8564bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8565 status_t& status)
8566{
8567 AudioParameter param = AudioParameter(keyValuePair);
8568 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008569 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008570 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008571 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008572 // forward device change to effects that have requested to be
8573 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008574 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008575 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008576 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008577 }
8578 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008579 if (audio_is_output_devices(device)) {
8580 mOutDevice = device;
8581 if (!isOutput()) {
8582 sendToHal = false;
8583 }
8584 } else {
8585 mInDevice = device;
8586 if (device != AUDIO_DEVICE_NONE) {
8587 mPrevInDevice = value;
8588 }
8589 // TODO: implement and call checkBtNrec_l();
8590 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008591 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008592 if (sendToHal) {
8593 status = mHalStream->setParameters(keyValuePair);
8594 } else {
8595 status = NO_ERROR;
8596 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008597
8598 return false;
8599}
8600
8601String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8602{
8603 Mutex::Autolock _l(mLock);
8604 String8 out_s8;
8605 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8606 return out_s8;
8607 }
8608 return String8();
8609}
8610
8611void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8612 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8613
8614 desc->mIoHandle = mId;
8615
8616 switch (event) {
8617 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008618 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008619 case AUDIO_INPUT_CONFIG_CHANGED:
8620 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008621 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008622 case AUDIO_OUTPUT_CONFIG_CHANGED:
8623 desc->mPatch = mPatch;
8624 desc->mChannelMask = mChannelMask;
8625 desc->mSamplingRate = mSampleRate;
8626 desc->mFormat = mFormat;
8627 desc->mFrameCount = mFrameCount;
8628 desc->mFrameCountHAL = mFrameCount;
8629 desc->mLatency = 0;
8630 break;
8631
8632 case AUDIO_INPUT_CLOSED:
8633 case AUDIO_OUTPUT_CLOSED:
8634 default:
8635 break;
8636 }
8637 mAudioFlinger->ioConfigChanged(event, desc, pid);
8638}
8639
8640status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8641 audio_patch_handle_t *handle)
8642{
8643 status_t status = NO_ERROR;
8644
8645 // store new device and send to effects
8646 audio_devices_t type = AUDIO_DEVICE_NONE;
8647 audio_port_handle_t deviceId;
8648 if (isOutput()) {
8649 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8650 type |= patch->sinks[i].ext.device.type;
8651 }
8652 deviceId = patch->sinks[0].id;
8653 } else {
8654 type = patch->sources[0].ext.device.type;
8655 deviceId = patch->sources[0].id;
8656 }
8657
8658 for (size_t i = 0; i < mEffectChains.size(); i++) {
8659 mEffectChains[i]->setDevice_l(type);
8660 }
8661
8662 if (isOutput()) {
8663 mOutDevice = type;
8664 } else {
8665 mInDevice = type;
8666 // store new source and send to effects
8667 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8668 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8669 for (size_t i = 0; i < mEffectChains.size(); i++) {
8670 mEffectChains[i]->setAudioSource_l(mAudioSource);
8671 }
8672 }
8673 }
8674
8675 if (mAudioHwDev->supportsAudioPatches()) {
8676 status = mHalDevice->createAudioPatch(patch->num_sources,
8677 patch->sources,
8678 patch->num_sinks,
8679 patch->sinks,
8680 handle);
8681 } else {
8682 char *address;
8683 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8684 //FIXME: we only support address on first sink with HAL version < 3.0
8685 address = audio_device_address_to_parameter(
8686 patch->sinks[0].ext.device.type,
8687 patch->sinks[0].ext.device.address);
8688 } else {
8689 address = (char *)calloc(1, 1);
8690 }
8691 AudioParameter param = AudioParameter(String8(address));
8692 free(address);
8693 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8694 if (!isOutput()) {
8695 param.addInt(String8(AudioParameter::keyInputSource),
8696 (int)patch->sinks[0].ext.mix.usecase.source);
8697 }
8698 status = mHalStream->setParameters(param.toString());
8699 *handle = AUDIO_PATCH_HANDLE_NONE;
8700 }
8701
8702 if (isOutput() && mPrevOutDevice != mOutDevice) {
8703 mPrevOutDevice = type;
8704 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008705 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008706 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008707 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008708 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008709 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008710 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008711 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008712 }
8713 if (!isOutput() && mPrevInDevice != mInDevice) {
8714 mPrevInDevice = type;
8715 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008716 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008717 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008718 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008719 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008720 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008721 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008722 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008723 }
8724 return status;
8725}
8726
8727status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8728{
8729 status_t status = NO_ERROR;
8730
8731 mInDevice = AUDIO_DEVICE_NONE;
8732
8733 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8734 supportsAudioPatches : false;
8735
8736 if (supportsAudioPatches) {
8737 status = mHalDevice->releaseAudioPatch(handle);
8738 } else {
8739 AudioParameter param;
8740 param.addInt(String8(AudioParameter::keyRouting), 0);
8741 status = mHalStream->setParameters(param.toString());
8742 }
8743 return status;
8744}
8745
Mikhail Naganovdc769682018-05-04 15:34:08 -07008746void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008747{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008748 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008749 if (isOutput()) {
8750 config->role = AUDIO_PORT_ROLE_SOURCE;
8751 config->ext.mix.hw_module = mAudioHwDev->handle();
8752 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8753 } else {
8754 config->role = AUDIO_PORT_ROLE_SINK;
8755 config->ext.mix.hw_module = mAudioHwDev->handle();
8756 config->ext.mix.usecase.source = mAudioSource;
8757 }
8758}
8759
8760status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8761{
8762 audio_session_t session = chain->sessionId();
8763
8764 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8765 // Attach all tracks with same session ID to this chain.
8766 // indicate all active tracks in the chain
8767 for (const sp<MmapTrack> &track : mActiveTracks) {
8768 if (session == track->sessionId()) {
8769 chain->incTrackCnt();
8770 chain->incActiveTrackCnt();
8771 }
8772 }
8773
8774 chain->setThread(this);
8775 chain->setInBuffer(nullptr);
8776 chain->setOutBuffer(nullptr);
8777 chain->syncHalEffectsState();
8778
8779 mEffectChains.add(chain);
8780 checkSuspendOnAddEffectChain_l(chain);
8781 return NO_ERROR;
8782}
8783
8784size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8785{
8786 audio_session_t session = chain->sessionId();
8787
8788 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8789
8790 for (size_t i = 0; i < mEffectChains.size(); i++) {
8791 if (chain == mEffectChains[i]) {
8792 mEffectChains.removeAt(i);
8793 // detach all active tracks from the chain
8794 // detach all tracks with same session ID from this chain
8795 for (const sp<MmapTrack> &track : mActiveTracks) {
8796 if (session == track->sessionId()) {
8797 chain->decActiveTrackCnt();
8798 chain->decTrackCnt();
8799 }
8800 }
8801 break;
8802 }
8803 }
8804 return mEffectChains.size();
8805}
8806
8807// hasAudioSession_l() must be called with ThreadBase::mLock held
8808uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8809{
8810 uint32_t result = 0;
8811 if (getEffectChain_l(sessionId) != 0) {
8812 result = EFFECT_SESSION;
8813 }
8814
8815 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8816 sp<MmapTrack> track = mActiveTracks[i];
8817 if (sessionId == track->sessionId()) {
8818 result |= TRACK_SESSION;
8819 if (track->isFastTrack()) {
8820 result |= FAST_SESSION;
8821 }
8822 break;
8823 }
8824 }
8825
8826 return result;
8827}
8828
8829void AudioFlinger::MmapThread::threadLoop_standby()
8830{
8831 mHalStream->standby();
8832}
8833
8834void AudioFlinger::MmapThread::threadLoop_exit()
8835{
Phil Burk7dce7282017-09-27 13:51:41 -07008836 // Do not call callback->onTearDown() because it is redundant for thread exit
8837 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008838}
8839
8840status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8841{
8842 return BAD_VALUE;
8843}
8844
8845bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8846{
8847 return false;
8848}
8849
8850status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8851 const effect_descriptor_t *desc, audio_session_t sessionId)
8852{
8853 // No global effect sessions on mmap threads
8854 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8855 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8856 desc->name, mThreadName);
8857 return BAD_VALUE;
8858 }
8859
8860 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8861 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8862 desc->name);
8863 return BAD_VALUE;
8864 }
8865 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008866 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8867 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008868 return BAD_VALUE;
8869 }
8870
8871 // Only allow effects without processing load or latency
8872 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8873 return BAD_VALUE;
8874 }
8875
8876 return NO_ERROR;
8877
8878}
8879
8880void AudioFlinger::MmapThread::checkInvalidTracks_l()
8881{
8882 for (const sp<MmapTrack> &track : mActiveTracks) {
8883 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008884 sp<MmapStreamCallback> callback = mCallback.promote();
8885 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008886 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008887 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008888 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008889 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8890 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8891 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008892 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008893 }
8894 }
8895}
8896
8897void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8898{
8899 dumpInternals(fd, args);
8900 dumpTracks(fd, args);
8901 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008902 dprintf(fd, " Local log:\n");
8903 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008904}
8905
8906void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8907{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008908 dumpBase(fd, args);
8909
8910 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8911 mAttr.content_type, mAttr.usage, mAttr.source);
8912 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07008913 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008914 dprintf(fd, " No active clients\n");
8915 }
8916}
8917
8918void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8919{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008920 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008921 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008922 dprintf(fd, " %zu Tracks\n", numtracks);
8923 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008924 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008925 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008926 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008927 for (size_t i = 0; i < numtracks ; ++i) {
8928 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008929 result.append(prefix);
8930 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008931 }
8932 } else {
8933 dprintf(fd, "\n");
8934 }
8935 write(fd, result.string(), result.size());
8936}
8937
8938AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8939 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8940 AudioHwDevice *hwDev, AudioStreamOut *output,
8941 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8942 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8943 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008944 mStreamVolume(1.0),
8945 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008946 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008947{
8948 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8949 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8950 mMasterVolume = audioFlinger->masterVolume_l();
8951 mMasterMute = audioFlinger->masterMute_l();
8952 if (mAudioHwDev) {
8953 if (mAudioHwDev->canSetMasterVolume()) {
8954 mMasterVolume = 1.0;
8955 }
8956
8957 if (mAudioHwDev->canSetMasterMute()) {
8958 mMasterMute = false;
8959 }
8960 }
8961}
8962
8963void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8964 audio_stream_type_t streamType,
8965 audio_session_t sessionId,
8966 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008967 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008968 audio_port_handle_t portId)
8969{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008970 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008971 mStreamType = streamType;
8972}
8973
8974AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8975{
8976 Mutex::Autolock _l(mLock);
8977 AudioStreamOut *output = mOutput;
8978 mOutput = NULL;
8979 return output;
8980}
8981
8982void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8983{
8984 Mutex::Autolock _l(mLock);
8985 // Don't apply master volume in SW if our HAL can do it for us.
8986 if (mAudioHwDev &&
8987 mAudioHwDev->canSetMasterVolume()) {
8988 mMasterVolume = 1.0;
8989 } else {
8990 mMasterVolume = value;
8991 }
8992}
8993
8994void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8995{
8996 Mutex::Autolock _l(mLock);
8997 // Don't apply master mute in SW if our HAL can do it for us.
8998 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8999 mMasterMute = false;
9000 } else {
9001 mMasterMute = muted;
9002 }
9003}
9004
9005void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9006{
9007 Mutex::Autolock _l(mLock);
9008 if (stream == mStreamType) {
9009 mStreamVolume = value;
9010 broadcast_l();
9011 }
9012}
9013
9014float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9015{
9016 Mutex::Autolock _l(mLock);
9017 if (stream == mStreamType) {
9018 return mStreamVolume;
9019 }
9020 return 0.0f;
9021}
9022
9023void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9024{
9025 Mutex::Autolock _l(mLock);
9026 if (stream == mStreamType) {
9027 mStreamMute= muted;
9028 broadcast_l();
9029 }
9030}
9031
9032void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9033{
9034 Mutex::Autolock _l(mLock);
9035 if (streamType == mStreamType) {
9036 for (const sp<MmapTrack> &track : mActiveTracks) {
9037 track->invalidate();
9038 }
9039 broadcast_l();
9040 }
9041}
9042
9043void AudioFlinger::MmapPlaybackThread::processVolume_l()
9044{
9045 float volume;
9046
9047 if (mMasterMute || mStreamMute) {
9048 volume = 0;
9049 } else {
9050 volume = mMasterVolume * mStreamVolume;
9051 }
9052
9053 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009054
9055 // Convert volumes from float to 8.24
9056 uint32_t vol = (uint32_t)(volume * (1 << 24));
9057
9058 // Delegate volume control to effect in track effect chain if needed
9059 // only one effect chain can be present on DirectOutputThread, so if
9060 // there is one, the track is connected to it
9061 if (!mEffectChains.isEmpty()) {
9062 mEffectChains[0]->setVolume_l(&vol, &vol);
9063 volume = (float)vol / (1 << 24);
9064 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009065 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009066 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9067 mHalVolFloat = volume; // HW volume control worked, so update value.
9068 mNoCallbackWarningCount = 0;
9069 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009070 sp<MmapStreamCallback> callback = mCallback.promote();
9071 if (callback != 0) {
9072 int channelCount;
9073 if (isOutput()) {
9074 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9075 } else {
9076 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9077 }
9078 Vector<float> values;
9079 for (int i = 0; i < channelCount; i++) {
9080 values.add(volume);
9081 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009082 mHalVolFloat = volume; // SW volume control worked, so update value.
9083 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009084 mLock.unlock();
9085 callback->onVolumeChanged(mChannelMask, values);
9086 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009087 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009088 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9089 ALOGW("Could not set MMAP stream volume: no volume callback!");
9090 mNoCallbackWarningCount++;
9091 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009092 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009093 }
9094 }
9095}
9096
Kevin Rocard069c2712018-03-29 19:09:14 -07009097void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9098{
9099 if (mOutput == nullptr || mOutput->stream == nullptr ||
9100 !mActiveTracks.readAndClearHasChanged()) {
9101 return;
9102 }
9103 StreamOutHalInterface::SourceMetadata metadata;
9104 for (const sp<MmapTrack> &track : mActiveTracks) {
9105 // No track is invalid as this is called after prepareTrack_l in the same critical section
9106 metadata.tracks.push_back({
9107 .usage = track->attributes().usage,
9108 .content_type = track->attributes().content_type,
9109 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9110 });
9111 }
9112 mOutput->stream->updateSourceMetadata(metadata);
9113}
9114
Eric Laurent6acd1d42017-01-04 14:23:29 -08009115void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9116{
9117 if (!mMasterMute) {
9118 char value[PROPERTY_VALUE_MAX];
9119 if (property_get("ro.audio.silent", value, "0") > 0) {
9120 char *endptr;
9121 unsigned long ul = strtoul(value, &endptr, 0);
9122 if (*endptr == '\0' && ul != 0) {
9123 ALOGD("Silence is golden");
9124 // The setprop command will not allow a property to be changed after
9125 // the first time it is set, so we don't have to worry about un-muting.
9126 setMasterMute_l(true);
9127 }
9128 }
9129 }
9130}
9131
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009132void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9133{
9134 MmapThread::toAudioPortConfig(config);
9135 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9136 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9137 config->flags.output = mOutput->flags;
9138 }
9139}
9140
Eric Laurent6acd1d42017-01-04 14:23:29 -08009141void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9142{
9143 MmapThread::dumpInternals(fd, args);
9144
Glenn Kastend3bb6452016-12-05 18:14:37 -08009145 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9146 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009147 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9148}
9149
9150AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9151 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9152 AudioHwDevice *hwDev, AudioStreamIn *input,
9153 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9154 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9155 mInput(input)
9156{
9157 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9158 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9159}
9160
Eric Laurent331679c2018-04-16 17:03:16 -07009161status_t AudioFlinger::MmapCaptureThread::exitStandby()
9162{
9163 mInput->stream->setGain(1.0f);
9164 return MmapThread::exitStandby();
9165}
9166
Eric Laurent6acd1d42017-01-04 14:23:29 -08009167AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9168{
9169 Mutex::Autolock _l(mLock);
9170 AudioStreamIn *input = mInput;
9171 mInput = NULL;
9172 return input;
9173}
Kevin Rocard069c2712018-03-29 19:09:14 -07009174
Eric Laurent331679c2018-04-16 17:03:16 -07009175
9176void AudioFlinger::MmapCaptureThread::processVolume_l()
9177{
9178 bool changed = false;
9179 bool silenced = false;
9180
9181 sp<MmapStreamCallback> callback = mCallback.promote();
9182 if (callback == 0) {
9183 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9184 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9185 mNoCallbackWarningCount++;
9186 }
9187 }
9188
9189 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9190 // track is silenced and unmute otherwise
9191 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9192 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9193 changed = true;
9194 silenced = mActiveTracks[i]->isSilenced_l();
9195 }
9196 }
9197
9198 if (changed) {
9199 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9200 }
9201}
9202
Kevin Rocard069c2712018-03-29 19:09:14 -07009203void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9204{
9205 if (mInput == nullptr || mInput->stream == nullptr ||
9206 !mActiveTracks.readAndClearHasChanged()) {
9207 return;
9208 }
9209 StreamInHalInterface::SinkMetadata metadata;
9210 for (const sp<MmapTrack> &track : mActiveTracks) {
9211 // No track is invalid as this is called after prepareTrack_l in the same critical section
9212 metadata.tracks.push_back({
9213 .source = track->attributes().source,
9214 .gain = 1, // capture tracks do not have volumes
9215 });
9216 }
9217 mInput->stream->updateSinkMetadata(metadata);
9218}
9219
Eric Laurent331679c2018-04-16 17:03:16 -07009220void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9221{
9222 Mutex::Autolock _l(mLock);
9223 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9224 if (mActiveTracks[i]->uid() == uid) {
9225 mActiveTracks[i]->setSilenced_l(silenced);
9226 broadcast_l();
9227 }
9228 }
9229}
9230
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009231void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9232{
9233 MmapThread::toAudioPortConfig(config);
9234 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9235 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9236 config->flags.input = mInput->flags;
9237 }
9238}
9239
Glenn Kasten63238ef2015-03-02 15:50:29 -08009240} // namespace android