blob: e70e567099ae6b5883a5edb487ef2d008244d013 [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>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070045#include <system/audio_effects/effect_ns.h>
46#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070047#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080048
49// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070050#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <media/nbaio/AudioStreamOutSink.h>
52#include <media/nbaio/MonoPipe.h>
53#include <media/nbaio/MonoPipeReader.h>
54#include <media/nbaio/Pipe.h>
55#include <media/nbaio/PipeReader.h>
56#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080057#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080058
59#include <powermanager/PowerManager.h>
60
Kevin Rocard7588ff42018-01-08 11:11:30 -080061#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070062#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080065#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070066#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070067#include <mediautils/SchedulingPolicyService.h>
68#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080069
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef ADD_BATTERY_DATA
71#include <media/IMediaPlayerService.h>
72#include <media/IMediaDeathNotifier.h>
73#endif
74
Eric Laurent81784c32012-11-19 14:55:58 -080075#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070076#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080077#include <cpustats/ThreadCpuUsage.h>
78#endif
79
Glenn Kastenc05b8d72016-03-24 09:48:17 -070080#include "AutoPark.h"
81
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080082#include <pthread.h>
83#include "TypedLogger.h"
84
Eric Laurent81784c32012-11-19 14:55:58 -080085// ----------------------------------------------------------------------------
86
87// Note: the following macro is used for extremely verbose logging message. In
88// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
89// 0; but one side effect of this is to turn all LOGV's as well. Some messages
90// are so verbose that we want to suppress them even when we have ALOG_ASSERT
91// turned on. Do not uncomment the #def below unless you really know what you
92// are doing and want to see all of the extremely verbose messages.
93//#define VERY_VERY_VERBOSE_LOGGING
94#ifdef VERY_VERY_VERBOSE_LOGGING
95#define ALOGVV ALOGV
96#else
97#define ALOGVV(a...) do { } while(0)
98#endif
99
Andy Hung6770c6f2015-04-07 13:43:36 -0700100// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700101#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700102template <typename T>
103static inline T min(const T& a, const T& b)
104{
105 return a < b ? a : b;
106}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700107
Eric Laurent81784c32012-11-19 14:55:58 -0800108namespace android {
109
110// retry counts for buffer fill timeout
111// 50 * ~20msecs = 1 second
112static const int8_t kMaxTrackRetries = 50;
113static const int8_t kMaxTrackStartupRetries = 50;
114// allow less retry attempts on direct output thread.
115// direct outputs can be a scarce resource in audio hardware and should
116// be released as quickly as possible.
117static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700118
Eric Laurent51716182016-02-29 18:00:56 -0800119
Eric Laurent81784c32012-11-19 14:55:58 -0800120
121// don't warn about blocked writes or record buffer overflows more often than this
122static const nsecs_t kWarningThrottleNs = seconds(5);
123
124// RecordThread loop sleep time upon application overrun or audio HAL read error
125static const int kRecordThreadSleepUs = 5000;
126
Eric Laurent10351942014-05-08 18:49:52 -0700127// maximum time to wait in sendConfigEvent_l() for a status to be received
128static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800129
130// minimum sleep time for the mixer thread loop when tracks are active but in underrun
131static const uint32_t kMinThreadSleepTimeUs = 5000;
132// maximum divider applied to the active sleep time in the mixer thread loop
133static const uint32_t kMaxThreadSleepTimeShift = 2;
134
Andy Hung09a50072014-02-27 14:30:47 -0800135// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800137static const uint32_t kMinNormalSinkBufferSizeMs = 20;
138// maximum normal sink buffer size
139static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800140
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700141// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
142// FIXME This should be based on experimentally observed scheduling jitter
143static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
144
Eric Laurent972a1732013-09-04 09:42:59 -0700145// Offloaded output thread standby delay: allows track transition without going to standby
146static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
147
Eric Laurent51716182016-02-29 18:00:56 -0800148// Direct output thread minimum sleep time in idle or active(underrun) state
149static const nsecs_t kDirectMinSleepTimeUs = 10000;
150
Glenn Kasten1b291842016-07-18 14:55:21 -0700151// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
152// balance between power consumption and latency, and allows threads to be scheduled reliably
153// by the CFS scheduler.
154// FIXME Express other hardcoded references to 20ms with references to this constant and move
155// it appropriately.
156#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800157
Eric Laurent81784c32012-11-19 14:55:58 -0800158// Whether to use fast mixer
159static const enum {
160 FastMixer_Never, // never initialize or use: for debugging only
161 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
162 // normal mixer multiplier is 1
163 FastMixer_Static, // initialize if needed, then use all the time if initialized,
164 // multiplier is calculated based on min & max normal mixer buffer size
165 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
166 // multiplier is calculated based on min & max normal mixer buffer size
167 // FIXME for FastMixer_Dynamic:
168 // Supporting this option will require fixing HALs that can't handle large writes.
169 // For example, one HAL implementation returns an error from a large write,
170 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
171 // We could either fix the HAL implementations, or provide a wrapper that breaks
172 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
173} kUseFastMixer = FastMixer_Static;
174
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700175// Whether to use fast capture
176static const enum {
177 FastCapture_Never, // never initialize or use: for debugging only
178 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
179 FastCapture_Static, // initialize if needed, then use all the time if initialized
180} kUseFastCapture = FastCapture_Static;
181
Eric Laurent81784c32012-11-19 14:55:58 -0800182// Priorities for requestPriority
183static const int kPriorityAudioApp = 2;
184static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700185static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800186
Glenn Kastenea38ee72016-04-18 11:08:01 -0700187// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
188// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
189// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700190
191// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800192static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800193
Glenn Kasten03490092014-05-27 12:30:54 -0700194// The minimum and maximum allowed values
195static const int kFastTrackMultiplierMin = 1;
196static const int kFastTrackMultiplierMax = 2;
197
198// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
199static int sFastTrackMultiplier = kFastTrackMultiplier;
200
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201// See Thread::readOnlyHeap().
202// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
203// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
204// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700205static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700206
Eric Laurent81784c32012-11-19 14:55:58 -0800207// ----------------------------------------------------------------------------
208
Glenn Kasten03490092014-05-27 12:30:54 -0700209static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
210
211static void sFastTrackMultiplierInit()
212{
213 char value[PROPERTY_VALUE_MAX];
214 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
215 char *endptr;
216 unsigned long ul = strtoul(value, &endptr, 0);
217 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
218 sFastTrackMultiplier = (int) ul;
219 }
220 }
221}
222
223// ----------------------------------------------------------------------------
224
Eric Laurent81784c32012-11-19 14:55:58 -0800225#ifdef ADD_BATTERY_DATA
226// To collect the amplifier usage
227static void addBatteryData(uint32_t params) {
228 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
229 if (service == NULL) {
230 // it already logged
231 return;
232 }
233
234 service->addBatteryData(params);
235}
236#endif
237
Andy Hung3f0c9022016-01-15 17:49:46 -0800238// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
239struct {
240 // call when you acquire a partial wakelock
241 void acquire(const sp<IBinder> &wakeLockToken) {
242 pthread_mutex_lock(&mLock);
243 if (wakeLockToken.get() == nullptr) {
244 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
245 } else {
246 if (mCount == 0) {
247 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
248 }
249 ++mCount;
250 }
251 pthread_mutex_unlock(&mLock);
252 }
253
254 // call when you release a partial wakelock.
255 void release(const sp<IBinder> &wakeLockToken) {
256 if (wakeLockToken.get() == nullptr) {
257 return;
258 }
259 pthread_mutex_lock(&mLock);
260 if (--mCount < 0) {
261 ALOGE("negative wakelock count");
262 mCount = 0;
263 }
264 pthread_mutex_unlock(&mLock);
265 }
266
267 // retrieves the boottime timebase offset from monotonic.
268 int64_t getBoottimeOffset() {
269 pthread_mutex_lock(&mLock);
270 int64_t boottimeOffset = mBoottimeOffset;
271 pthread_mutex_unlock(&mLock);
272 return boottimeOffset;
273 }
274
275 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
276 // and the selected timebase.
277 // Currently only TIMEBASE_BOOTTIME is allowed.
278 //
279 // This only needs to be called upon acquiring the first partial wakelock
280 // after all other partial wakelocks are released.
281 //
282 // We do an empirical measurement of the offset rather than parsing
283 // /proc/timer_list since the latter is not a formal kernel ABI.
284 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
285 int clockbase;
286 switch (timebase) {
287 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
288 clockbase = SYSTEM_TIME_BOOTTIME;
289 break;
290 default:
291 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
292 break;
293 }
294 // try three times to get the clock offset, choose the one
295 // with the minimum gap in measurements.
296 const int tries = 3;
297 nsecs_t bestGap, measured;
298 for (int i = 0; i < tries; ++i) {
299 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
300 const nsecs_t tbase = systemTime(clockbase);
301 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
302 const nsecs_t gap = tmono2 - tmono;
303 if (i == 0 || gap < bestGap) {
304 bestGap = gap;
305 measured = tbase - ((tmono + tmono2) >> 1);
306 }
307 }
308
309 // to avoid micro-adjusting, we don't change the timebase
310 // unless it is significantly different.
311 //
312 // Assumption: It probably takes more than toleranceNs to
313 // suspend and resume the device.
314 static int64_t toleranceNs = 10000; // 10 us
315 if (llabs(*offset - measured) > toleranceNs) {
316 ALOGV("Adjusting timebase offset old: %lld new: %lld",
317 (long long)*offset, (long long)measured);
318 *offset = measured;
319 }
320 }
321
322 pthread_mutex_t mLock;
323 int32_t mCount;
324 int64_t mBoottimeOffset;
325} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800326
327// ----------------------------------------------------------------------------
328// CPU Stats
329// ----------------------------------------------------------------------------
330
331class CpuStats {
332public:
333 CpuStats();
334 void sample(const String8 &title);
335#ifdef DEBUG_CPU_USAGE
336private:
337 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700338 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800339
Andy Hung16698b82018-08-01 10:48:38 -0700340 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800341
342 int mCpuNum; // thread's current CPU number
343 int mCpukHz; // frequency of thread's current CPU in kHz
344#endif
345};
346
347CpuStats::CpuStats()
348#ifdef DEBUG_CPU_USAGE
349 : mCpuNum(-1), mCpukHz(-1)
350#endif
351{
352}
353
Glenn Kasten0f11b512014-01-31 16:18:54 -0800354void CpuStats::sample(const String8 &title
355#ifndef DEBUG_CPU_USAGE
356 __unused
357#endif
358 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800359#ifdef DEBUG_CPU_USAGE
360 // get current thread's delta CPU time in wall clock ns
361 double wcNs;
362 bool valid = mCpuUsage.sampleAndEnable(wcNs);
363
364 // record sample for wall clock statistics
365 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700366 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800367 }
368
369 // get the current CPU number
370 int cpuNum = sched_getcpu();
371
372 // get the current CPU frequency in kHz
373 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
374
375 // check if either CPU number or frequency changed
376 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
377 mCpuNum = cpuNum;
378 mCpukHz = cpukHz;
379 // ignore sample for purposes of cycles
380 valid = false;
381 }
382
383 // if no change in CPU number or frequency, then record sample for cycle statistics
384 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700385 const double cycles = wcNs * cpukHz * 0.000001;
386 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800387 }
388
Eric Tan5b13ff82018-07-27 11:20:17 -0700389 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800390 // mCpuUsage.elapsed() is expensive, so don't call it every loop
391 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700392 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800393 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700394 const double perLoop = elapsed / (double) n;
395 const double perLoop100 = perLoop * 0.01;
396 const double perLoop1k = perLoop * 0.001;
397 const double mean = mWcStats.getMean();
398 const double stddev = mWcStats.getStdDev();
399 const double minimum = mWcStats.getMin();
400 const double maximum = mWcStats.getMax();
401 const double meanCycles = mHzStats.getMean();
402 const double stddevCycles = mHzStats.getStdDev();
403 const double minCycles = mHzStats.getMin();
404 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800405 mCpuUsage.resetElapsed();
406 mWcStats.reset();
407 mHzStats.reset();
408 ALOGD("CPU usage for %s over past %.1f secs\n"
409 " (%u mixer loops at %.1f mean ms per loop):\n"
410 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
411 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
412 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
413 title.string(),
414 elapsed * .000000001, n, perLoop * .000001,
415 mean * .001,
416 stddev * .001,
417 minimum * .001,
418 maximum * .001,
419 mean / perLoop100,
420 stddev / perLoop100,
421 minimum / perLoop100,
422 maximum / perLoop100,
423 meanCycles / perLoop1k,
424 stddevCycles / perLoop1k,
425 minCycles / perLoop1k,
426 maxCycles / perLoop1k);
427
428 }
429 }
430#endif
431};
432
433// ----------------------------------------------------------------------------
434// ThreadBase
435// ----------------------------------------------------------------------------
436
Glenn Kasten97b7b752014-09-28 13:04:24 -0700437// static
438const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
439{
440 switch (type) {
441 case MIXER:
442 return "MIXER";
443 case DIRECT:
444 return "DIRECT";
445 case DUPLICATING:
446 return "DUPLICATING";
447 case RECORD:
448 return "RECORD";
449 case OFFLOAD:
450 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800451 case MMAP:
452 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700453 default:
454 return "unknown";
455 }
456}
457
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700458std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800459{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700460 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800461 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700462 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800463 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465 }
466 return result;
467}
468
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700469std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800470{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471 std::string result;
472 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800473 return result;
474}
475
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700476std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700478 std::string result;
479 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700480 return result;
481}
482
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800483const char *sourceToString(audio_source_t source)
484{
485 switch (source) {
486 case AUDIO_SOURCE_DEFAULT: return "default";
487 case AUDIO_SOURCE_MIC: return "mic";
488 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
489 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
490 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
491 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
492 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
493 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
494 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800495 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800496 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
497 case AUDIO_SOURCE_HOTWORD: return "hotword";
498 default: return "unknown";
499 }
500}
501
Eric Laurent81784c32012-11-19 14:55:58 -0800502AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700503 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800504 : Thread(false /*canCallJava*/),
505 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700506 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700507 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800508 // are set by PlaybackThread::readOutputParameters_l() or
509 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700510 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800511 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700512 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
513 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800514 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700515 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800516 mSystemReady(systemReady),
517 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800518{
Eric Laurent296fb132015-05-01 11:38:42 -0700519 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800520}
521
522AudioFlinger::ThreadBase::~ThreadBase()
523{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700524 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700525 mConfigEvents.clear();
526
Eric Laurent81784c32012-11-19 14:55:58 -0800527 // do not lock the mutex in destructor
528 releaseWakeLock_l();
529 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800530 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800531 binder->unlinkToDeath(mDeathRecipient);
532 }
533}
534
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700535status_t AudioFlinger::ThreadBase::readyToRun()
536{
537 status_t status = initCheck();
538 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800539 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700540 } else {
541 ALOGE("No working audio driver found.");
542 }
543 return status;
544}
545
Eric Laurent81784c32012-11-19 14:55:58 -0800546void AudioFlinger::ThreadBase::exit()
547{
548 ALOGV("ThreadBase::exit");
549 // do any cleanup required for exit to succeed
550 preExit();
551 {
552 // This lock prevents the following race in thread (uniprocessor for illustration):
553 // if (!exitPending()) {
554 // // context switch from here to exit()
555 // // exit() calls requestExit(), what exitPending() observes
556 // // exit() calls signal(), which is dropped since no waiters
557 // // context switch back from exit() to here
558 // mWaitWorkCV.wait(...);
559 // // now thread is hung
560 // }
561 AutoMutex lock(mLock);
562 requestExit();
563 mWaitWorkCV.broadcast();
564 }
565 // When Thread::requestExitAndWait is made virtual and this method is renamed to
566 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
567 requestExitAndWait();
568}
569
570status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
571{
Eric Laurent81784c32012-11-19 14:55:58 -0800572 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
573 Mutex::Autolock _l(mLock);
574
Eric Laurent10351942014-05-08 18:49:52 -0700575 return sendSetParameterConfigEvent_l(keyValuePairs);
576}
577
578// sendConfigEvent_l() must be called with ThreadBase::mLock held
579// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
580status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
581{
582 status_t status = NO_ERROR;
583
Eric Laurent72e3f392015-05-20 14:43:50 -0700584 if (event->mRequiresSystemReady && !mSystemReady) {
585 event->mWaitStatus = false;
586 mPendingConfigEvents.add(event);
587 return status;
588 }
Eric Laurent10351942014-05-08 18:49:52 -0700589 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700590 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800591 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700592 mLock.unlock();
593 {
594 Mutex::Autolock _l(event->mLock);
595 while (event->mWaitStatus) {
596 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
597 event->mStatus = TIMED_OUT;
598 event->mWaitStatus = false;
599 }
600 }
601 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800602 }
Eric Laurent10351942014-05-08 18:49:52 -0700603 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800604 return status;
605}
606
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700607void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800608{
609 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700610 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800611}
612
613// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700614void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800615{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700616 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700617 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800618}
619
Mikhail Naganov83f04272017-02-07 10:45:09 -0800620void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700621{
622 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800623 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700624}
625
Eric Laurent81784c32012-11-19 14:55:58 -0800626// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800627void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
628 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800629{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800630 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700631 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800632}
633
Eric Laurent10351942014-05-08 18:49:52 -0700634// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
635status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800636{
Andy Hung2ddee192015-12-18 17:34:44 -0800637 sp<ConfigEvent> configEvent;
638 AudioParameter param(keyValuePair);
639 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700640 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800641 setMasterMono_l(value != 0);
642 if (param.size() == 1) {
643 return NO_ERROR; // should be a solo parameter - we don't pass down
644 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700645 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800646 configEvent = new SetParameterConfigEvent(param.toString());
647 } else {
648 configEvent = new SetParameterConfigEvent(keyValuePair);
649 }
Eric Laurent10351942014-05-08 18:49:52 -0700650 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700651}
652
Eric Laurent1c333e22014-05-20 10:48:17 -0700653status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
654 const struct audio_patch *patch,
655 audio_patch_handle_t *handle)
656{
657 Mutex::Autolock _l(mLock);
658 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
659 status_t status = sendConfigEvent_l(configEvent);
660 if (status == NO_ERROR) {
661 CreateAudioPatchConfigEventData *data =
662 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
663 *handle = data->mHandle;
664 }
665 return status;
666}
667
668status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
669 const audio_patch_handle_t handle)
670{
671 Mutex::Autolock _l(mLock);
672 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
673 return sendConfigEvent_l(configEvent);
674}
675
676
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700677// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700678void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700679{
Eric Laurent10351942014-05-08 18:49:52 -0700680 bool configChanged = false;
681
Eric Laurent81784c32012-11-19 14:55:58 -0800682 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700683 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700684 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800685 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700686 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700687 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700688 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
689 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800690 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700691 true /*asynchronous*/);
692 if (err != 0) {
693 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700694 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700695 }
696 } break;
697 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700698 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700699 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700700 } break;
701 case CFG_EVENT_SET_PARAMETER: {
702 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
703 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
704 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700705 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
706 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700707 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700708 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700709 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700710 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700711 CreateAudioPatchConfigEventData *data =
712 (CreateAudioPatchConfigEventData *)event->mData.get();
713 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700714 const audio_devices_t newDevice = getDevice();
715 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
716 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
717 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700718 } break;
719 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700720 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700721 ReleaseAudioPatchConfigEventData *data =
722 (ReleaseAudioPatchConfigEventData *)event->mData.get();
723 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700724 const audio_devices_t newDevice = getDevice();
725 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
726 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
727 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700728 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700729 default:
Eric Laurent10351942014-05-08 18:49:52 -0700730 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700731 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800732 }
Eric Laurent10351942014-05-08 18:49:52 -0700733 {
734 Mutex::Autolock _l(event->mLock);
735 if (event->mWaitStatus) {
736 event->mWaitStatus = false;
737 event->mCond.signal();
738 }
739 }
740 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
741 }
742
743 if (configChanged) {
744 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800745 }
Eric Laurent81784c32012-11-19 14:55:58 -0800746}
747
Marco Nelissenb2208842014-02-07 14:00:50 -0800748String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
749 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700750 const audio_channel_representation_t representation =
751 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700752
753 switch (representation) {
754 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
755 if (output) {
756 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
759 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
760 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
762 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
763 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
764 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
765 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
766 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
770 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
771 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
772 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
773 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700774 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
775 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700776 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
777 } else {
778 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
779 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
780 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
781 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
782 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
783 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
784 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
785 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
786 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
787 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
788 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
789 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700790 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
791 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
792 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
793 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
794 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
795 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700796 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
797 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
798 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
799 }
800 const int len = s.length();
801 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700802 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700803 s.unlockBuffer(len - 2); // remove trailing ", "
804 }
805 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800806 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700807 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
808 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
809 return s;
810 default:
811 s.appendFormat("unknown mask, representation:%d bits:%#x",
812 representation, audio_channel_mask_get_bits(mask));
813 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800814 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800815}
816
Glenn Kasten0f11b512014-01-31 16:18:54 -0800817void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800818{
819 const size_t SIZE = 256;
820 char buffer[SIZE];
821 String8 result;
822
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800823 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
824 this, mThreadName, getTid(), type(), threadTypeToString(type()));
825
Eric Laurent81784c32012-11-19 14:55:58 -0800826 bool locked = AudioFlinger::dumpTryLock(mLock);
827 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800828 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800829 }
830
Elliott Hughes87cebad2014-05-22 10:14:43 -0700831 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700832 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700833 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700835 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700836 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700837 dprintf(fd, " Channel count: %u\n", mChannelCount);
838 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800839 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700840 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700841 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700842 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800843 size_t numConfig = mConfigEvents.size();
844 if (numConfig) {
845 for (size_t i = 0; i < numConfig; i++) {
846 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700847 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800848 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700849 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800850 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700851 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800852 }
Andy Hung293558a2017-03-21 12:19:20 -0700853 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700854 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
855 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800856 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800857
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700858 // Dump timestamp statistics for the Thread types that support it.
859 if (mType == RECORD
860 || mType == MIXER
861 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700862 || mType == DIRECT
863 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700864 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700865 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700866 }
867
Eric Laurent81784c32012-11-19 14:55:58 -0800868 if (locked) {
869 mLock.unlock();
870 }
871}
872
873void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
874{
875 const size_t SIZE = 256;
876 char buffer[SIZE];
877 String8 result;
878
Marco Nelissenb2208842014-02-07 14:00:50 -0800879 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000880 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800881 write(fd, buffer, strlen(buffer));
882
Marco Nelissenb2208842014-02-07 14:00:50 -0800883 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800884 sp<EffectChain> chain = mEffectChains[i];
885 if (chain != 0) {
886 chain->dump(fd, args);
887 }
888 }
889}
890
Andy Hungdae27702016-10-31 14:01:16 -0700891void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800892{
893 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700894 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800895}
896
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100897String16 AudioFlinger::ThreadBase::getWakeLockTag()
898{
899 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800900 case MIXER:
901 return String16("AudioMix");
902 case DIRECT:
903 return String16("AudioDirectOut");
904 case DUPLICATING:
905 return String16("AudioDup");
906 case RECORD:
907 return String16("AudioIn");
908 case OFFLOAD:
909 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800910 case MMAP:
911 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800912 default:
913 ALOG_ASSERT(false);
914 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100915 }
916}
917
Andy Hungdae27702016-10-31 14:01:16 -0700918void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800919{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800920 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800921 if (mPowerManager != 0) {
922 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700923 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
924 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700925 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100926 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700927 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700928 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800929 if (status == NO_ERROR) {
930 mWakeLockToken = binder;
931 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800932 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800933 }
Wei Jia3f273d12015-11-24 09:06:49 -0800934
Andy Hung3f0c9022016-01-15 17:49:46 -0800935 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800936 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
937 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800938}
939
940void AudioFlinger::ThreadBase::releaseWakeLock()
941{
942 Mutex::Autolock _l(mLock);
943 releaseWakeLock_l();
944}
945
946void AudioFlinger::ThreadBase::releaseWakeLock_l()
947{
Andy Hung3f0c9022016-01-15 17:49:46 -0800948 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800949 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800950 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800951 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700952 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
953 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800954 }
955 mWakeLockToken.clear();
956 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957}
958
959void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700960 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800961 // use checkService() to avoid blocking if power service is not up yet
962 sp<IBinder> binder =
963 defaultServiceManager()->checkService(String16("power"));
964 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800965 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800966 } else {
967 mPowerManager = interface_cast<IPowerManager>(binder);
968 binder->linkToDeath(mDeathRecipient);
969 }
970 }
971}
972
Andy Hungd01b0f12016-11-07 16:10:30 -0800973void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800974 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700975
976#if !LOG_NDEBUG
977 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800978 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700979 s << uid << " ";
980 }
981 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
982#endif
983
Andy Hung438e7572015-12-14 15:51:17 -0800984 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
985 if (mSystemReady) {
986 ALOGE("no wake lock to update, but system ready!");
987 } else {
988 ALOGW("no wake lock to update, system not ready yet");
989 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800990 return;
991 }
992 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800993 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
994 status_t status = mPowerManager->updateWakeLockUids(
995 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
996 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800997 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800998 }
999}
1000
Eric Laurent81784c32012-11-19 14:55:58 -08001001void AudioFlinger::ThreadBase::clearPowerManager()
1002{
1003 Mutex::Autolock _l(mLock);
1004 releaseWakeLock_l();
1005 mPowerManager.clear();
1006}
1007
Glenn Kasten0f11b512014-01-31 16:18:54 -08001008void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001009{
1010 sp<ThreadBase> thread = mThread.promote();
1011 if (thread != 0) {
1012 thread->clearPowerManager();
1013 }
1014 ALOGW("power manager service died !!!");
1015}
1016
Eric Laurent81784c32012-11-19 14:55:58 -08001017void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001018 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001019{
1020 sp<EffectChain> chain = getEffectChain_l(sessionId);
1021 if (chain != 0) {
1022 if (type != NULL) {
1023 chain->setEffectSuspended_l(type, suspend);
1024 } else {
1025 chain->setEffectSuspendedAll_l(suspend);
1026 }
1027 }
1028
1029 updateSuspendedSessions_l(type, suspend, sessionId);
1030}
1031
1032void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1033{
1034 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1035 if (index < 0) {
1036 return;
1037 }
1038
1039 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1040 mSuspendedSessions.valueAt(index);
1041
1042 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001043 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001044 for (int j = 0; j < desc->mRefCount; j++) {
1045 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1046 chain->setEffectSuspendedAll_l(true);
1047 } else {
1048 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1049 desc->mType.timeLow);
1050 chain->setEffectSuspended_l(&desc->mType, true);
1051 }
1052 }
1053 }
1054}
1055
1056void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1057 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001058 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001059{
1060 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1061
1062 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1063
1064 if (suspend) {
1065 if (index >= 0) {
1066 sessionEffects = mSuspendedSessions.valueAt(index);
1067 } else {
1068 mSuspendedSessions.add(sessionId, sessionEffects);
1069 }
1070 } else {
1071 if (index < 0) {
1072 return;
1073 }
1074 sessionEffects = mSuspendedSessions.valueAt(index);
1075 }
1076
1077
1078 int key = EffectChain::kKeyForSuspendAll;
1079 if (type != NULL) {
1080 key = type->timeLow;
1081 }
1082 index = sessionEffects.indexOfKey(key);
1083
1084 sp<SuspendedSessionDesc> desc;
1085 if (suspend) {
1086 if (index >= 0) {
1087 desc = sessionEffects.valueAt(index);
1088 } else {
1089 desc = new SuspendedSessionDesc();
1090 if (type != NULL) {
1091 desc->mType = *type;
1092 }
1093 sessionEffects.add(key, desc);
1094 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1095 }
1096 desc->mRefCount++;
1097 } else {
1098 if (index < 0) {
1099 return;
1100 }
1101 desc = sessionEffects.valueAt(index);
1102 if (--desc->mRefCount == 0) {
1103 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1104 sessionEffects.removeItemsAt(index);
1105 if (sessionEffects.isEmpty()) {
1106 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1107 sessionId);
1108 mSuspendedSessions.removeItem(sessionId);
1109 }
1110 }
1111 }
1112 if (!sessionEffects.isEmpty()) {
1113 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1114 }
1115}
1116
1117void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1118 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001119 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001120{
1121 Mutex::Autolock _l(mLock);
1122 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1123}
1124
1125void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1126 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001127 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 if (mType != RECORD) {
1130 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1131 // another session. This gives the priority to well behaved effect control panels
1132 // and applications not using global effects.
1133 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1134 // global effects
1135 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1136 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1137 }
1138 }
1139
1140 sp<EffectChain> chain = getEffectChain_l(sessionId);
1141 if (chain != 0) {
1142 chain->checkSuspendOnEffectEnabled(effect, enabled);
1143 }
1144}
1145
Eric Laurent4c415062016-06-17 16:14:16 -07001146// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1147status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1148 const effect_descriptor_t *desc, audio_session_t sessionId)
1149{
1150 // No global effect sessions on record threads
1151 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1152 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1153 desc->name, mThreadName);
1154 return BAD_VALUE;
1155 }
1156 // only pre processing effects on record thread
1157 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1158 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1159 desc->name, mThreadName);
1160 return BAD_VALUE;
1161 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001162
1163 // always allow effects without processing load or latency
1164 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1165 return NO_ERROR;
1166 }
1167
Eric Laurent4c415062016-06-17 16:14:16 -07001168 audio_input_flags_t flags = mInput->flags;
1169 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1170 if (flags & AUDIO_INPUT_FLAG_RAW) {
1171 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1172 desc->name, mThreadName);
1173 return BAD_VALUE;
1174 }
1175 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1176 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1177 desc->name, mThreadName);
1178 return BAD_VALUE;
1179 }
1180 }
1181 return NO_ERROR;
1182}
1183
1184// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1185status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1186 const effect_descriptor_t *desc, audio_session_t sessionId)
1187{
1188 // no preprocessing on playback threads
1189 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1190 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1191 " thread %s", desc->name, mThreadName);
1192 return BAD_VALUE;
1193 }
1194
Eric Laurent3e4de772017-07-16 16:55:08 -07001195 // always allow effects without processing load or latency
1196 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1197 return NO_ERROR;
1198 }
1199
Eric Laurent4c415062016-06-17 16:14:16 -07001200 switch (mType) {
1201 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001202#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001203 // Reject any effect on mixer multichannel sinks.
1204 // TODO: fix both format and multichannel issues with effects.
1205 if (mChannelCount != FCC_2) {
1206 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1207 " thread %s", desc->name, mChannelCount, mThreadName);
1208 return BAD_VALUE;
1209 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001210#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001211 audio_output_flags_t flags = mOutput->flags;
1212 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1213 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1214 // global effects are applied only to non fast tracks if they are SW
1215 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1216 break;
1217 }
1218 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1219 // only post processing on output stage session
1220 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1221 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1222 " on output stage session", desc->name);
1223 return BAD_VALUE;
1224 }
1225 } else {
1226 // no restriction on effects applied on non fast tracks
1227 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1228 break;
1229 }
1230 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001231
Eric Laurent4c415062016-06-17 16:14:16 -07001232 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1233 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1234 desc->name);
1235 return BAD_VALUE;
1236 }
1237 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1238 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1239 " in fast mode", desc->name);
1240 return BAD_VALUE;
1241 }
1242 }
1243 } break;
1244 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001245 // nothing actionable on offload threads, if the effect:
1246 // - is offloadable: the effect can be created
1247 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1248 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001249 break;
1250 case DIRECT:
1251 // Reject any effect on Direct output threads for now, since the format of
1252 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1253 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1254 desc->name, mThreadName);
1255 return BAD_VALUE;
1256 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001257#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001258 // Reject any effect on mixer multichannel sinks.
1259 // TODO: fix both format and multichannel issues with effects.
1260 if (mChannelCount != FCC_2) {
1261 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1262 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1263 return BAD_VALUE;
1264 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001265#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001266 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1267 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1268 " thread %s", desc->name, mThreadName);
1269 return BAD_VALUE;
1270 }
1271 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1272 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1273 " DUPLICATING thread %s", desc->name, mThreadName);
1274 return BAD_VALUE;
1275 }
1276 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1277 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1278 " DUPLICATING thread %s", desc->name, mThreadName);
1279 return BAD_VALUE;
1280 }
1281 break;
1282 default:
1283 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1284 }
1285
1286 return NO_ERROR;
1287}
1288
Eric Laurent81784c32012-11-19 14:55:58 -08001289// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1290sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1291 const sp<AudioFlinger::Client>& client,
1292 const sp<IEffectClient>& effectClient,
1293 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001294 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001295 effect_descriptor_t *desc,
1296 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001297 status_t *status,
1298 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001299{
1300 sp<EffectModule> effect;
1301 sp<EffectHandle> handle;
1302 status_t lStatus;
1303 sp<EffectChain> chain;
1304 bool chainCreated = false;
1305 bool effectCreated = false;
1306 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001307 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001308
1309 lStatus = initCheck();
1310 if (lStatus != NO_ERROR) {
1311 ALOGW("createEffect_l() Audio driver not initialized.");
1312 goto Exit;
1313 }
1314
Eric Laurent81784c32012-11-19 14:55:58 -08001315 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1316
1317 { // scope for mLock
1318 Mutex::Autolock _l(mLock);
1319
Eric Laurent4c415062016-06-17 16:14:16 -07001320 lStatus = checkEffectCompatibility_l(desc, sessionId);
1321 if (lStatus != NO_ERROR) {
1322 goto Exit;
1323 }
1324
Eric Laurent81784c32012-11-19 14:55:58 -08001325 // check for existing effect chain with the requested audio session
1326 chain = getEffectChain_l(sessionId);
1327 if (chain == 0) {
1328 // create a new chain for this session
1329 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1330 chain = new EffectChain(this, sessionId);
1331 addEffectChain_l(chain);
1332 chain->setStrategy(getStrategyForSession_l(sessionId));
1333 chainCreated = true;
1334 } else {
1335 effect = chain->getEffectFromDesc_l(desc);
1336 }
1337
1338 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1339
1340 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001341 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001342 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001343 lStatus = AudioSystem::registerEffect(
1344 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001345 if (lStatus != NO_ERROR) {
1346 goto Exit;
1347 }
1348 effectRegistered = true;
1349 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001350 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001351 if (lStatus != NO_ERROR) {
1352 goto Exit;
1353 }
1354 effectCreated = true;
1355
1356 effect->setDevice(mOutDevice);
1357 effect->setDevice(mInDevice);
1358 effect->setMode(mAudioFlinger->getMode());
1359 effect->setAudioSource(mAudioSource);
1360 }
1361 // create effect handle and connect it to effect module
1362 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001363 lStatus = handle->initCheck();
1364 if (lStatus == OK) {
1365 lStatus = effect->addHandle(handle.get());
1366 }
Eric Laurent81784c32012-11-19 14:55:58 -08001367 if (enabled != NULL) {
1368 *enabled = (int)effect->isEnabled();
1369 }
1370 }
1371
1372Exit:
1373 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1374 Mutex::Autolock _l(mLock);
1375 if (effectCreated) {
1376 chain->removeEffect_l(effect);
1377 }
1378 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001379 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001380 }
1381 if (chainCreated) {
1382 removeEffectChain_l(chain);
1383 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001384 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001385 }
1386
Glenn Kasten9156ef32013-08-06 15:39:08 -07001387 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001388 return handle;
1389}
1390
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001391void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1392 bool unpinIfLast)
1393{
1394 bool remove = false;
1395 sp<EffectModule> effect;
1396 {
1397 Mutex::Autolock _l(mLock);
1398
1399 effect = handle->effect().promote();
1400 if (effect == 0) {
1401 return;
1402 }
1403 // restore suspended effects if the disconnected handle was enabled and the last one.
1404 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1405 if (remove) {
1406 removeEffect_l(effect, true);
1407 }
1408 }
1409 if (remove) {
1410 mAudioFlinger->updateOrphanEffectChains(effect);
1411 AudioSystem::unregisterEffect(effect->id());
1412 if (handle->enabled()) {
1413 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1414 }
1415 }
1416}
1417
Glenn Kastend848eb42016-03-08 13:42:11 -08001418sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1419 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001420{
1421 Mutex::Autolock _l(mLock);
1422 return getEffect_l(sessionId, effectId);
1423}
1424
Glenn Kastend848eb42016-03-08 13:42:11 -08001425sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1426 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001427{
1428 sp<EffectChain> chain = getEffectChain_l(sessionId);
1429 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1430}
1431
1432// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1433// PlaybackThread::mLock held
1434status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1435{
1436 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001437 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001438 sp<EffectChain> chain = getEffectChain_l(sessionId);
1439 bool chainCreated = false;
1440
Eric Laurent5baf2af2013-09-12 17:37:00 -07001441 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001442 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001443 this, effect->desc().name, effect->desc().flags);
1444
Eric Laurent81784c32012-11-19 14:55:58 -08001445 if (chain == 0) {
1446 // create a new chain for this session
1447 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1448 chain = new EffectChain(this, sessionId);
1449 addEffectChain_l(chain);
1450 chain->setStrategy(getStrategyForSession_l(sessionId));
1451 chainCreated = true;
1452 }
1453 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1454
1455 if (chain->getEffectFromId_l(effect->id()) != 0) {
1456 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1457 this, effect->desc().name, chain.get());
1458 return BAD_VALUE;
1459 }
1460
Eric Laurent5baf2af2013-09-12 17:37:00 -07001461 effect->setOffloaded(mType == OFFLOAD, mId);
1462
Eric Laurent81784c32012-11-19 14:55:58 -08001463 status_t status = chain->addEffect_l(effect);
1464 if (status != NO_ERROR) {
1465 if (chainCreated) {
1466 removeEffectChain_l(chain);
1467 }
1468 return status;
1469 }
1470
1471 effect->setDevice(mOutDevice);
1472 effect->setDevice(mInDevice);
1473 effect->setMode(mAudioFlinger->getMode());
1474 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001475
Eric Laurent81784c32012-11-19 14:55:58 -08001476 return NO_ERROR;
1477}
1478
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001479void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001480
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001481 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001482 effect_descriptor_t desc = effect->desc();
1483 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1484 detachAuxEffect_l(effect->id());
1485 }
1486
1487 sp<EffectChain> chain = effect->chain().promote();
1488 if (chain != 0) {
1489 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001490 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001491 removeEffectChain_l(chain);
1492 }
1493 } else {
1494 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1495 }
1496}
1497
1498void AudioFlinger::ThreadBase::lockEffectChains_l(
1499 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1500{
1501 effectChains = mEffectChains;
1502 for (size_t i = 0; i < mEffectChains.size(); i++) {
1503 mEffectChains[i]->lock();
1504 }
1505}
1506
1507void AudioFlinger::ThreadBase::unlockEffectChains(
1508 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1509{
1510 for (size_t i = 0; i < effectChains.size(); i++) {
1511 effectChains[i]->unlock();
1512 }
1513}
1514
Glenn Kastend848eb42016-03-08 13:42:11 -08001515sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001516{
1517 Mutex::Autolock _l(mLock);
1518 return getEffectChain_l(sessionId);
1519}
1520
Glenn Kastend848eb42016-03-08 13:42:11 -08001521sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1522 const
Eric Laurent81784c32012-11-19 14:55:58 -08001523{
1524 size_t size = mEffectChains.size();
1525 for (size_t i = 0; i < size; i++) {
1526 if (mEffectChains[i]->sessionId() == sessionId) {
1527 return mEffectChains[i];
1528 }
1529 }
1530 return 0;
1531}
1532
1533void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1534{
1535 Mutex::Autolock _l(mLock);
1536 size_t size = mEffectChains.size();
1537 for (size_t i = 0; i < size; i++) {
1538 mEffectChains[i]->setMode_l(mode);
1539 }
1540}
1541
Mikhail Naganovdc769682018-05-04 15:34:08 -07001542void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001543{
1544 config->type = AUDIO_PORT_TYPE_MIX;
1545 config->ext.mix.handle = mId;
1546 config->sample_rate = mSampleRate;
1547 config->format = mFormat;
1548 config->channel_mask = mChannelMask;
1549 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1550 AUDIO_PORT_CONFIG_FORMAT;
1551}
1552
Eric Laurent72e3f392015-05-20 14:43:50 -07001553void AudioFlinger::ThreadBase::systemReady()
1554{
1555 Mutex::Autolock _l(mLock);
1556 if (mSystemReady) {
1557 return;
1558 }
1559 mSystemReady = true;
1560
1561 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1562 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1563 }
1564 mPendingConfigEvents.clear();
1565}
1566
Andy Hungdae27702016-10-31 14:01:16 -07001567template <typename T>
1568ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1569 ssize_t index = mActiveTracks.indexOf(track);
1570 if (index >= 0) {
1571 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1572 return index;
1573 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001574 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001575 mActiveTracksGeneration++;
1576 mLatestActiveTrack = track;
1577 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001578 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001579 return mActiveTracks.add(track);
1580}
1581
1582template <typename T>
1583ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1584 ssize_t index = mActiveTracks.remove(track);
1585 if (index < 0) {
1586 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1587 return index;
1588 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001589 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001590 mActiveTracksGeneration++;
1591 --mBatteryCounter[track->uid()].second;
1592 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001593 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001594#ifdef TEE_SINK
1595 track->dumpTee(-1 /* fd */, "_REMOVE");
1596#endif
Andy Hungdae27702016-10-31 14:01:16 -07001597 return index;
1598}
1599
1600template <typename T>
1601void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1602 for (const sp<T> &track : mActiveTracks) {
1603 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001604 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001605 }
1606 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001607 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001608 mActiveTracks.clear();
1609 mLatestActiveTrack.clear();
1610 mBatteryCounter.clear();
1611}
1612
1613template <typename T>
1614void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1615 sp<ThreadBase> thread, bool force) {
1616 // Updates ActiveTracks client uids to the thread wakelock.
1617 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1618 thread->updateWakeLockUids_l(getWakeLockUids());
1619 mLastActiveTracksGeneration = mActiveTracksGeneration;
1620 }
1621
1622 // Updates BatteryNotifier uids
1623 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1624 const uid_t uid = it->first;
1625 ssize_t &previous = it->second.first;
1626 ssize_t &current = it->second.second;
1627 if (current > 0) {
1628 if (previous == 0) {
1629 BatteryNotifier::getInstance().noteStartAudio(uid);
1630 }
1631 previous = current;
1632 ++it;
1633 } else if (current == 0) {
1634 if (previous > 0) {
1635 BatteryNotifier::getInstance().noteStopAudio(uid);
1636 }
1637 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1638 } else /* (current < 0) */ {
1639 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1640 }
1641 }
1642}
Eric Laurent83b88082014-06-20 18:31:16 -07001643
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001644template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001645bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1646 const bool hasChanged = mHasChanged;
1647 mHasChanged = false;
1648 return hasChanged;
1649}
1650
1651template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001652void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1653 const char *funcName, const sp<T> &track) const {
1654 if (mLocalLog != nullptr) {
1655 String8 result;
1656 track->appendDump(result, false /* active */);
1657 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1658 }
1659}
1660
Eric Laurent6acd1d42017-01-04 14:23:29 -08001661void AudioFlinger::ThreadBase::broadcast_l()
1662{
1663 // Thread could be blocked waiting for async
1664 // so signal it to handle state changes immediately
1665 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1666 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1667 mSignalPending = true;
1668 mWaitWorkCV.broadcast();
1669}
1670
Eric Laurent81784c32012-11-19 14:55:58 -08001671// ----------------------------------------------------------------------------
1672// Playback
1673// ----------------------------------------------------------------------------
1674
1675AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1676 AudioStreamOut* output,
1677 audio_io_handle_t id,
1678 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001679 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001680 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001681 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001682 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001683 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001684 mMixerBuffer(NULL),
1685 mMixerBufferSize(0),
1686 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1687 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001688 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001689 mEffectBuffer(NULL),
1690 mEffectBufferSize(0),
1691 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1692 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001693 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001694 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001695 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001696 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001697 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001698 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001699 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001700 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001701 mMixerStatus(MIXER_IDLE),
1702 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001703 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001704 mBytesRemaining(0),
1705 mCurrentWriteLength(0),
1706 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001707 mWriteAckSequence(0),
1708 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001709 mScreenState(AudioFlinger::mScreenState),
1710 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001711 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001712 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1713 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001714{
Glenn Kastend7dca052015-03-05 16:05:54 -08001715 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1716 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001717
1718 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1719 // it would be safer to explicitly pass initial masterVolume/masterMute as
1720 // parameter.
1721 //
1722 // If the HAL we are using has support for master volume or master mute,
1723 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1724 // and the mute set to false).
1725 mMasterVolume = audioFlinger->masterVolume_l();
1726 mMasterMute = audioFlinger->masterMute_l();
1727 if (mOutput && mOutput->audioHwDev) {
1728 if (mOutput->audioHwDev->canSetMasterVolume()) {
1729 mMasterVolume = 1.0;
1730 }
1731
1732 if (mOutput->audioHwDev->canSetMasterMute()) {
1733 mMasterMute = false;
1734 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001735 mIsMsdDevice = strcmp(
1736 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001737 }
1738
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001739 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001740
Andy Hungc8fddf32018-08-08 18:32:37 -07001741 // TODO: We may also match on address as well as device type for
1742 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
1743 if (type == MIXER || type == DIRECT) {
1744 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
1745 "audio.timestamp.corrected_output_devices",
1746 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1747 : AUDIO_DEVICE_NONE));
1748 }
1749
Eric Laurent223fd5c2014-11-11 13:43:36 -08001750 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001751 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001752 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001753 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001754 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1755 }
Eric Laurent98e38192018-02-15 18:31:53 -08001756 // Audio patch volume is always max
1757 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1758 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001759}
1760
1761AudioFlinger::PlaybackThread::~PlaybackThread()
1762{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001763 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001764 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001765 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001766 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001767}
1768
1769void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1770{
1771 dumpInternals(fd, args);
1772 dumpTracks(fd, args);
1773 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001774 dprintf(fd, " Local log:\n");
1775 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001776}
1777
Glenn Kasten0f11b512014-01-31 16:18:54 -08001778void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001779{
Eric Laurent81784c32012-11-19 14:55:58 -08001780 String8 result;
1781
Marco Nelissenb2208842014-02-07 14:00:50 -08001782 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001783 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1784 const stream_type_t *st = &mStreamTypes[i];
1785 if (i > 0) {
1786 result.appendFormat(", ");
1787 }
1788 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1789 if (st->mute) {
1790 result.append("M");
1791 }
1792 }
1793 result.append("\n");
1794 write(fd, result.string(), result.length());
1795 result.clear();
1796
Eric Laurent81784c32012-11-19 14:55:58 -08001797 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1798 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001799 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001800 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001801
1802 size_t numtracks = mTracks.size();
1803 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001804 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001805 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001806 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001807 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001808 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001809 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001810 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001811 for (size_t i = 0; i < numtracks; ++i) {
1812 sp<Track> track = mTracks[i];
1813 if (track != 0) {
1814 bool active = mActiveTracks.indexOf(track) >= 0;
1815 if (active) {
1816 numactiveseen++;
1817 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001818 result.append(prefix);
1819 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001820 }
1821 }
1822 } else {
1823 result.append("\n");
1824 }
1825 if (numactiveseen != numactive) {
1826 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001827 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001828 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001829 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001830 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001831 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001832 sp<Track> track = mActiveTracks[i];
1833 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001834 result.append(prefix);
1835 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001836 }
1837 }
1838 }
1839
1840 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001841}
1842
1843void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1844{
Glenn Kasten44182c22015-03-05 17:12:23 -08001845 dumpBase(fd, args);
1846
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07001847 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Elliott Hughes87cebad2014-05-22 10:14:43 -07001848 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001849 dprintf(fd, " Last write occurred (msecs): %llu\n",
1850 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001851 dprintf(fd, " Total writes: %d\n", mNumWrites);
1852 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1853 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1854 dprintf(fd, " Suspend count: %d\n", mSuspended);
1855 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1856 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1857 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1858 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001859 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001860 AudioStreamOut *output = mOutput;
1861 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001862 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1863 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001864 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1865 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1866 if (mPipeSink.get() != nullptr) {
1867 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1868 }
1869 if (output != nullptr) {
1870 dprintf(fd, " Hal stream dump:\n");
1871 (void)output->stream->dump(fd);
1872 }
Eric Laurent81784c32012-11-19 14:55:58 -08001873}
1874
1875// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001876
1877void AudioFlinger::PlaybackThread::onFirstRef()
1878{
Glenn Kastend7dca052015-03-05 16:05:54 -08001879 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001880}
1881
1882// ThreadBase virtuals
1883void AudioFlinger::PlaybackThread::preExit()
1884{
1885 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001886 // FIXME this is using hard-coded strings but in the future, this functionality will be
1887 // converted to use audio HAL extensions required to support tunneling
1888 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1889 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001890}
1891
1892// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1893sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1894 const sp<AudioFlinger::Client>& client,
1895 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001896 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001897 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001898 audio_format_t format,
1899 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001900 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001901 size_t *pNotificationFrameCount,
1902 uint32_t notificationsPerBuffer,
1903 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001904 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001905 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001906 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001907 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001908 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001909 status_t *status,
1910 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001911{
Glenn Kasten74935e42013-12-19 08:56:45 -08001912 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001913 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001914 sp<Track> track;
1915 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001916 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001917 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001918 uint32_t sampleRate;
1919
1920 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1921 lStatus = BAD_VALUE;
1922 goto Exit;
1923 }
Eric Laurent21da6472017-11-09 16:29:26 -08001924
1925 if (*pSampleRate == 0) {
1926 *pSampleRate = mSampleRate;
1927 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001928 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001929
1930 // special case for FAST flag considered OK if fast mixer is present
1931 if (hasFastMixer()) {
1932 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1933 }
1934
1935 // Check if requested flags are compatible with output stream flags
1936 if ((*flags & outputFlags) != *flags) {
1937 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1938 *flags, outputFlags);
1939 *flags = (audio_output_flags_t)(*flags & outputFlags);
1940 }
Eric Laurent81784c32012-11-19 14:55:58 -08001941
Eric Laurent81784c32012-11-19 14:55:58 -08001942 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001943 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001944 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001945 // PCM data
1946 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001947 // TODO: extract as a data library function that checks that a computationally
1948 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001949 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001950 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1951 (channelMask == AUDIO_CHANNEL_OUT_MONO
1952 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001953 // hardware sample rate
1954 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001955 // normal mixer has an associated fast mixer
1956 hasFastMixer() &&
1957 // there are sufficient fast track slots available
1958 (mFastTrackAvailMask != 0)
1959 // FIXME test that MixerThread for this fast track has a capable output HAL
1960 // FIXME add a permission test also?
1961 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001962 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1963 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001964 // read the fast track multiplier property the first time it is needed
1965 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1966 if (ok != 0) {
1967 ALOGE("%s pthread_once failed: %d", __func__, ok);
1968 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001969 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001970 }
Eric Laurent4c415062016-06-17 16:14:16 -07001971
1972 // check compatibility with audio effects.
1973 { // scope for mLock
1974 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001975 for (audio_session_t session : {
1976 AUDIO_SESSION_OUTPUT_STAGE,
1977 AUDIO_SESSION_OUTPUT_MIX,
1978 sessionId,
1979 }) {
1980 sp<EffectChain> chain = getEffectChain_l(session);
1981 if (chain.get() != nullptr) {
1982 audio_output_flags_t old = *flags;
1983 chain->checkOutputFlagCompatibility(flags);
1984 if (old != *flags) {
1985 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1986 (int)session, (int)old, (int)*flags);
1987 }
Eric Laurent4c415062016-06-17 16:14:16 -07001988 }
1989 }
1990 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001991 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001992 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1993 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001994 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001995 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1996 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001997 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001998 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001999 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002000 audio_is_linear_pcm(format),
2001 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002002 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002003 }
2004 }
Eric Laurent21da6472017-11-09 16:29:26 -08002005
2006 if (!audio_has_proportional_frames(format)) {
2007 if (sharedBuffer != 0) {
2008 // Same comment as below about ignoring frameCount parameter for set()
2009 frameCount = sharedBuffer->size();
2010 } else if (frameCount == 0) {
2011 frameCount = mNormalFrameCount;
2012 }
2013 if (notificationFrameCount != frameCount) {
2014 notificationFrameCount = frameCount;
2015 }
2016 } else if (sharedBuffer != 0) {
2017 // FIXME: Ensure client side memory buffers need
2018 // not have additional alignment beyond sample
2019 // (e.g. 16 bit stereo accessed as 32 bit frame).
2020 size_t alignment = audio_bytes_per_sample(format);
2021 if (alignment & 1) {
2022 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2023 alignment = 1;
2024 }
2025 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2026 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2027 if (channelCount > 1) {
2028 // More than 2 channels does not require stronger alignment than stereo
2029 alignment <<= 1;
2030 }
2031 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2032 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2033 sharedBuffer->pointer(), channelCount);
2034 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002035 goto Exit;
2036 }
Eric Laurent21da6472017-11-09 16:29:26 -08002037
2038 // When initializing a shared buffer AudioTrack via constructors,
2039 // there's no frameCount parameter.
2040 // But when initializing a shared buffer AudioTrack via set(),
2041 // there _is_ a frameCount parameter. We silently ignore it.
2042 frameCount = sharedBuffer->size() / frameSize;
2043 } else {
2044 size_t minFrameCount = 0;
2045 // For fast tracks we try to respect the application's request for notifications per buffer.
2046 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2047 if (notificationsPerBuffer > 0) {
2048 // Avoid possible arithmetic overflow during multiplication.
2049 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2050 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2051 notificationsPerBuffer, mFrameCount);
2052 } else {
2053 minFrameCount = mFrameCount * notificationsPerBuffer;
2054 }
2055 }
2056 } else {
2057 // For normal PCM streaming tracks, update minimum frame count.
2058 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2059 // cover audio hardware latency.
2060 // This is probably too conservative, but legacy application code may depend on it.
2061 // If you change this calculation, also review the start threshold which is related.
2062 uint32_t latencyMs = latency_l();
2063 if (latencyMs == 0) {
2064 ALOGE("Error when retrieving output stream latency");
2065 lStatus = UNKNOWN_ERROR;
2066 goto Exit;
2067 }
2068
2069 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2070 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2071
Eric Laurent81784c32012-11-19 14:55:58 -08002072 }
Eric Laurent21da6472017-11-09 16:29:26 -08002073 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002074 frameCount = minFrameCount;
2075 }
Eric Laurent81784c32012-11-19 14:55:58 -08002076 }
Eric Laurent21da6472017-11-09 16:29:26 -08002077
2078 // Make sure that application is notified with sufficient margin before underrun.
2079 // The client can divide the AudioTrack buffer into sub-buffers,
2080 // and expresses its desire to server as the notification frame count.
2081 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2082 size_t maxNotificationFrames;
2083 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2084 // notify every HAL buffer, regardless of the size of the track buffer
2085 maxNotificationFrames = mFrameCount;
2086 } else {
2087 // For normal tracks, use at least double-buffering if no sample rate conversion,
2088 // or at least triple-buffering if there is sample rate conversion
2089 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2090 maxNotificationFrames = frameCount / nBuffering;
2091 // If client requested a fast track but this was denied, then use the smaller maximum.
2092 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2093 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2094 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2095 maxNotificationFrames = maxNotificationFramesFastDenied;
2096 }
2097 }
2098 }
2099 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2100 if (notificationFrameCount == 0) {
2101 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2102 maxNotificationFrames, frameCount);
2103 } else {
2104 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2105 notificationFrameCount, maxNotificationFrames, frameCount);
2106 }
2107 notificationFrameCount = maxNotificationFrames;
2108 }
2109 }
2110
Glenn Kasten74935e42013-12-19 08:56:45 -08002111 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002112 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002113
Glenn Kastenc3df8382014-03-13 15:05:25 -07002114 switch (mType) {
2115
2116 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002117 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002118 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002119 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2120 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002121 sampleRate, format, channelMask, mOutput, mFormat);
2122 lStatus = BAD_VALUE;
2123 goto Exit;
2124 }
2125 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002126 break;
2127
2128 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002129 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002130 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2131 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002132 sampleRate, format, channelMask, mOutput, mFormat);
2133 lStatus = BAD_VALUE;
2134 goto Exit;
2135 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002136 break;
2137
2138 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002139 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002140 ALOGE("createTrack_l() Bad parameter: format %#x \""
2141 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002142 format, mOutput, mFormat);
2143 lStatus = BAD_VALUE;
2144 goto Exit;
2145 }
Andy Hungcd044842014-08-07 11:04:34 -07002146 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002147 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2148 lStatus = BAD_VALUE;
2149 goto Exit;
2150 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002151 break;
2152
Eric Laurent81784c32012-11-19 14:55:58 -08002153 }
2154
2155 lStatus = initCheck();
2156 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002157 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002158 goto Exit;
2159 }
2160
2161 { // scope for mLock
2162 Mutex::Autolock _l(mLock);
2163
2164 // all tracks in same audio session must share the same routing strategy otherwise
2165 // conflicts will happen when tracks are moved from one output to another by audio policy
2166 // manager
2167 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2168 for (size_t i = 0; i < mTracks.size(); ++i) {
2169 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002170 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002171 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2172 if (sessionId == t->sessionId() && strategy != actual) {
2173 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2174 strategy, actual);
2175 lStatus = BAD_VALUE;
2176 goto Exit;
2177 }
2178 }
2179 }
2180
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002181 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002182 channelMask, frameCount,
2183 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002184 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002185
Glenn Kasten03003332013-08-06 15:40:54 -07002186 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2187 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002188 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002189 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002190 goto Exit;
2191 }
2192 mTracks.add(track);
2193
2194 sp<EffectChain> chain = getEffectChain_l(sessionId);
2195 if (chain != 0) {
2196 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2197 track->setMainBuffer(chain->inBuffer());
2198 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2199 chain->incTrackCnt();
2200 }
2201
Eric Laurent05067782016-06-01 18:27:28 -07002202 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002203 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2204 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2205 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002206 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002207 }
2208 }
2209
2210 lStatus = NO_ERROR;
2211
2212Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002213 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002214 return track;
2215}
2216
Andy Hung1bc088a2018-02-09 15:57:31 -08002217template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002218ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2219{
Andy Hungc0691382018-09-12 18:01:57 -07002220 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002221 const ssize_t index = mTracks.remove(track);
2222 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002223 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002224 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002225 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002226 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002227 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002228 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002229 }
2230 return index;
2231}
2232
Eric Laurent81784c32012-11-19 14:55:58 -08002233uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2234{
2235 return latency;
2236}
2237
2238uint32_t AudioFlinger::PlaybackThread::latency() const
2239{
2240 Mutex::Autolock _l(mLock);
2241 return latency_l();
2242}
2243uint32_t AudioFlinger::PlaybackThread::latency_l() const
2244{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002245 uint32_t latency;
2246 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2247 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002248 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002249 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002250}
2251
2252void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2253{
2254 Mutex::Autolock _l(mLock);
2255 // Don't apply master volume in SW if our HAL can do it for us.
2256 if (mOutput && mOutput->audioHwDev &&
2257 mOutput->audioHwDev->canSetMasterVolume()) {
2258 mMasterVolume = 1.0;
2259 } else {
2260 mMasterVolume = value;
2261 }
2262}
2263
2264void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2265{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002266 if (isDuplicating()) {
2267 return;
2268 }
Eric Laurent81784c32012-11-19 14:55:58 -08002269 Mutex::Autolock _l(mLock);
2270 // Don't apply master mute in SW if our HAL can do it for us.
2271 if (mOutput && mOutput->audioHwDev &&
2272 mOutput->audioHwDev->canSetMasterMute()) {
2273 mMasterMute = false;
2274 } else {
2275 mMasterMute = muted;
2276 }
2277}
2278
2279void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2280{
2281 Mutex::Autolock _l(mLock);
2282 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002283 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002284}
2285
2286void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2287{
2288 Mutex::Autolock _l(mLock);
2289 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002290 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002291}
2292
2293float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2294{
2295 Mutex::Autolock _l(mLock);
2296 return mStreamTypes[stream].volume;
2297}
2298
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002299void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2300{
2301 mOutput->stream->setVolume(left, right);
2302}
2303
Eric Laurent81784c32012-11-19 14:55:58 -08002304// addTrack_l() must be called with ThreadBase::mLock held
2305status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2306{
2307 status_t status = ALREADY_EXISTS;
2308
Eric Laurent81784c32012-11-19 14:55:58 -08002309 if (mActiveTracks.indexOf(track) < 0) {
2310 // the track is newly added, make sure it fills up all its
2311 // buffers before playing. This is to ensure the client will
2312 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002313 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002314 TrackBase::track_state state = track->mState;
2315 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002316 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002317 mLock.lock();
2318 // abort track was stopped/paused while we released the lock
2319 if (state != track->mState) {
2320 if (status == NO_ERROR) {
2321 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002322 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002323 mLock.lock();
2324 }
2325 return INVALID_OPERATION;
2326 }
2327 // abort if start is rejected by audio policy manager
2328 if (status != NO_ERROR) {
2329 return PERMISSION_DENIED;
2330 }
2331#ifdef ADD_BATTERY_DATA
2332 // to track the speaker usage
2333 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2334#endif
2335 }
2336
Eric Laurent51716182016-02-29 18:00:56 -08002337 // set retry count for buffer fill
2338 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002339 if (track->isStopping_1()) {
2340 track->mRetryCount = kMaxTrackStopRetriesOffload;
2341 } else {
2342 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2343 }
2344 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002345 } else {
2346 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002347 track->mFillingUpStatus =
2348 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002349 }
2350
Eric Laurent81784c32012-11-19 14:55:58 -08002351 track->mResetDone = false;
2352 track->mPresentationCompleteFrames = 0;
2353 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002354 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2355 if (chain != 0) {
2356 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2357 track->sessionId());
2358 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002359 }
2360
2361 status = NO_ERROR;
2362 }
2363
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002364 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002365 return status;
2366}
2367
Eric Laurentbfb1b832013-01-07 09:53:42 -08002368bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002369{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002370 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002371 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002372 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2373 track->mState = TrackBase::STOPPED;
2374 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002375 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002376 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002377 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002378 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002379
2380 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002381}
2382
2383void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2384{
2385 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002386
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002387 String8 result;
2388 track->appendDump(result, false /* active */);
2389 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002390
Eric Laurent81784c32012-11-19 14:55:58 -08002391 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002392 if (track->isFastTrack()) {
2393 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002394 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002395 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2396 mFastTrackAvailMask |= 1 << index;
2397 // redundant as track is about to be destroyed, for dumpsys only
2398 track->mFastIndex = -1;
2399 }
2400 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2401 if (chain != 0) {
2402 chain->decTrackCnt();
2403 }
2404}
2405
2406String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2407{
Eric Laurent81784c32012-11-19 14:55:58 -08002408 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002409 String8 out_s8;
2410 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2411 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002412 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002413 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002414}
2415
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002416status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2417 Mutex::Autolock _l(mLock);
2418 if (mOutput == nullptr || mOutput->stream == nullptr) {
2419 return NO_INIT;
2420 }
2421 return mOutput->stream->selectPresentation(presentationId, programId);
2422}
2423
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002424void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002425 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2426 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002427
Eric Laurent73e26b62015-04-27 16:55:58 -07002428 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002429
2430 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002431 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002432 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002433 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002434 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002435 desc->mChannelMask = mChannelMask;
2436 desc->mSamplingRate = mSampleRate;
2437 desc->mFormat = mFormat;
2438 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002439 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002440 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002441 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002442 break;
2443
Eric Laurent73e26b62015-04-27 16:55:58 -07002444 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002445 default:
2446 break;
2447 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002448 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002449}
2450
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002451void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002452{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002453 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002454}
2455
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002456void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002457{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002458 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459}
2460
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002461void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002462{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002463 mCallbackThread->setAsyncError();
2464}
2465
Eric Laurent3b4529e2013-09-05 18:09:19 -07002466void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002467{
2468 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002469 // reject out of sequence requests
2470 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2471 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002472 mWaitWorkCV.signal();
2473 }
2474}
2475
Eric Laurent3b4529e2013-09-05 18:09:19 -07002476void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002477{
2478 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002479 // reject out of sequence requests
2480 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002481 // Register discontinuity when HW drain is completed because that can cause
2482 // the timestamp frame position to reset to 0 for direct and offload threads.
2483 // (Out of sequence requests are ignored, since the discontinuity would be handled
2484 // elsewhere, e.g. in flush).
2485 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002486 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002487 mWaitWorkCV.signal();
2488 }
2489}
2490
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002491void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002492{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002493 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002494 mSampleRate = mOutput->getSampleRate();
2495 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002496 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002497 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002498 }
Andy Hung9a592762014-07-21 21:56:01 -07002499 if ((mType == MIXER || mType == DUPLICATING)
2500 && !isValidPcmSinkChannelMask(mChannelMask)) {
2501 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2502 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002503 }
Andy Hunge5412692014-05-16 11:25:07 -07002504 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002505
2506 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002507 status_t result = mOutput->stream->getFormat(&mHALFormat);
2508 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002509 // Get format from the shim, which will be different than the HAL format
2510 // if playing compressed audio over HDMI passthrough.
2511 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002512 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002513 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002514 }
Andy Hung6146c082014-03-18 11:56:15 -07002515 if ((mType == MIXER || mType == DUPLICATING)
2516 && !isValidPcmSinkFormat(mFormat)) {
2517 LOG_FATAL("HAL format %#x not supported for mixed output",
2518 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002519 }
Phil Burk062e67a2015-02-11 13:40:50 -08002520 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002521 result = mOutput->stream->getBufferSize(&mBufferSize);
2522 LOG_ALWAYS_FATAL_IF(result != OK,
2523 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002524 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002525 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002526 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002527 mFrameCount);
2528 }
2529
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002530 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2531 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002532 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002533 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002534 }
2535 }
2536
Eric Laurentd1f69b02014-12-15 14:33:13 -08002537 mHwSupportsPause = false;
2538 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002539 bool supportsPause = false, supportsResume = false;
2540 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2541 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002542 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002543 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002544 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002545 } else if (supportsResume) {
2546 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002547 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002548 }
2549 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002550 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2551 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2552 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002553
Andy Hungfbfc3952015-01-15 13:33:51 -08002554 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2555 // For best precision, we use float instead of the associated output
2556 // device format (typically PCM 16 bit).
2557
2558 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2559 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2560 mBufferSize = mFrameSize * mFrameCount;
2561
2562 // TODO: We currently use the associated output device channel mask and sample rate.
2563 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2564 // (if a valid mask) to avoid premature downmix.
2565 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2566 // instead of the output device sample rate to avoid loss of high frequency information.
2567 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2568 }
2569
Andy Hung09a50072014-02-27 14:30:47 -08002570 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002571 double multiplier = 1.0;
2572 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2573 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002574 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2575 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002576
Eric Laurent81784c32012-11-19 14:55:58 -08002577 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2578 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2579 maxNormalFrameCount = maxNormalFrameCount & ~15;
2580 if (maxNormalFrameCount < minNormalFrameCount) {
2581 maxNormalFrameCount = minNormalFrameCount;
2582 }
2583 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2584 if (multiplier <= 1.0) {
2585 multiplier = 1.0;
2586 } else if (multiplier <= 2.0) {
2587 if (2 * mFrameCount <= maxNormalFrameCount) {
2588 multiplier = 2.0;
2589 } else {
2590 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2591 }
2592 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002593 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002594 }
2595 }
2596 mNormalFrameCount = multiplier * mFrameCount;
2597 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002598 if (mType == MIXER || mType == DUPLICATING) {
2599 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2600 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002601 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002602 mNormalFrameCount);
2603
Andy Hung08fb1742015-05-31 23:22:10 -07002604 // Check if we want to throttle the processing to no more than 2x normal rate
2605 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002606 mThreadThrottleTimeMs = 0;
2607 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002608 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2609
Andy Hung010a1a12014-03-13 13:57:33 -07002610 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2611 // Originally this was int16_t[] array, need to remove legacy implications.
2612 free(mSinkBuffer);
2613 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002614 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2615 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2616 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002617 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002618
Andy Hung69aed5f2014-02-25 17:24:40 -08002619 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2620 // drives the output.
2621 free(mMixerBuffer);
2622 mMixerBuffer = NULL;
2623 if (mMixerBufferEnabled) {
2624 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2625 mMixerBufferSize = mNormalFrameCount * mChannelCount
2626 * audio_bytes_per_sample(mMixerBufferFormat);
2627 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2628 }
Andy Hung98ef9782014-03-04 14:46:50 -08002629 free(mEffectBuffer);
2630 mEffectBuffer = NULL;
2631 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002632 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002633 mEffectBufferSize = mNormalFrameCount * mChannelCount
2634 * audio_bytes_per_sample(mEffectBufferFormat);
2635 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2636 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002637
Eric Laurent81784c32012-11-19 14:55:58 -08002638 // force reconfiguration of effect chains and engines to take new buffer size and audio
2639 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002640 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002641 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2642 // matter.
2643 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2644 Vector< sp<EffectChain> > effectChains = mEffectChains;
2645 for (size_t i = 0; i < effectChains.size(); i ++) {
2646 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2647 }
2648}
2649
Kevin Rocard069c2712018-03-29 19:09:14 -07002650void AudioFlinger::PlaybackThread::updateMetadata_l()
2651{
Kevin Rocard12381092018-04-11 09:19:59 -07002652 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2653 return; // That should not happen
2654 }
2655 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2656 for (const sp<Track> &track : mActiveTracks) {
2657 // Do not short-circuit as all hasChanged states must be reset
2658 // as all the metadata are going to be sent
2659 hasChanged |= track->readAndClearHasChanged();
2660 }
2661 if (!hasChanged) {
2662 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002663 }
2664 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002665 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002666 for (const sp<Track> &track : mActiveTracks) {
2667 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002668 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002669 }
Kevin Rocard12381092018-04-11 09:19:59 -07002670 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002671}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002672
Kevin Rocard12381092018-04-11 09:19:59 -07002673void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2674 const StreamOutHalInterface::SourceMetadata& metadata)
2675{
2676 mOutput->stream->updateSourceMetadata(metadata);
2677};
2678
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002679status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002680{
2681 if (halFrames == NULL || dspFrames == NULL) {
2682 return BAD_VALUE;
2683 }
2684 Mutex::Autolock _l(mLock);
2685 if (initCheck() != NO_ERROR) {
2686 return INVALID_OPERATION;
2687 }
Andy Hung818e7a32016-02-16 18:08:07 -08002688 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002689 *halFrames = framesWritten;
2690
2691 if (isSuspended()) {
2692 // return an estimation of rendered frames when the output is suspended
2693 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002694 *dspFrames = (uint32_t)
2695 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002696 return NO_ERROR;
2697 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002698 status_t status;
2699 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002700 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002701 *dspFrames = (size_t)frames;
2702 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002703 }
2704}
2705
Eric Laurent4c415062016-06-17 16:14:16 -07002706// hasAudioSession_l() must be called with ThreadBase::mLock held
2707uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002708{
Eric Laurent81784c32012-11-19 14:55:58 -08002709 uint32_t result = 0;
2710 if (getEffectChain_l(sessionId) != 0) {
2711 result = EFFECT_SESSION;
2712 }
2713
2714 for (size_t i = 0; i < mTracks.size(); ++i) {
2715 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002716 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002717 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002718 if (track->isFastTrack()) {
2719 result |= FAST_SESSION;
2720 }
Eric Laurent81784c32012-11-19 14:55:58 -08002721 break;
2722 }
2723 }
2724
2725 return result;
2726}
2727
Glenn Kastend848eb42016-03-08 13:42:11 -08002728uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002729{
2730 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2731 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2732 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2733 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2734 }
2735 for (size_t i = 0; i < mTracks.size(); i++) {
2736 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002737 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002738 return AudioSystem::getStrategyForStream(track->streamType());
2739 }
2740 }
2741 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2742}
2743
2744
Phil Burk062e67a2015-02-11 13:40:50 -08002745AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002746{
2747 Mutex::Autolock _l(mLock);
2748 return mOutput;
2749}
2750
Phil Burk062e67a2015-02-11 13:40:50 -08002751AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002752{
2753 Mutex::Autolock _l(mLock);
2754 AudioStreamOut *output = mOutput;
2755 mOutput = NULL;
2756 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2757 // must push a NULL and wait for ack
2758 mOutputSink.clear();
2759 mPipeSink.clear();
2760 mNormalSink.clear();
2761 return output;
2762}
2763
2764// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002765sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002766{
2767 if (mOutput == NULL) {
2768 return NULL;
2769 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002770 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002771}
2772
2773uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2774{
2775 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2776}
2777
2778status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2779{
2780 if (!isValidSyncEvent(event)) {
2781 return BAD_VALUE;
2782 }
2783
2784 Mutex::Autolock _l(mLock);
2785
2786 for (size_t i = 0; i < mTracks.size(); ++i) {
2787 sp<Track> track = mTracks[i];
2788 if (event->triggerSession() == track->sessionId()) {
2789 (void) track->setSyncEvent(event);
2790 return NO_ERROR;
2791 }
2792 }
2793
2794 return NAME_NOT_FOUND;
2795}
2796
2797bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2798{
2799 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2800}
2801
2802void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2803 const Vector< sp<Track> >& tracksToRemove)
2804{
Andy Hungfe726a62018-09-27 15:17:25 -07002805 // Miscellaneous track cleanup when removed from the active list,
2806 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002807#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002808 for (const auto& track : tracksToRemove) {
2809 if (track->isExternalTrack()) {
2810 // to track the speaker usage
2811 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002812 }
2813 }
Andy Hungfe726a62018-09-27 15:17:25 -07002814#else
2815 (void)tracksToRemove; // suppress unused warning
2816#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002817}
2818
2819void AudioFlinger::PlaybackThread::checkSilentMode_l()
2820{
2821 if (!mMasterMute) {
2822 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002823 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2824 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2825 return;
2826 }
Eric Laurent81784c32012-11-19 14:55:58 -08002827 if (property_get("ro.audio.silent", value, "0") > 0) {
2828 char *endptr;
2829 unsigned long ul = strtoul(value, &endptr, 0);
2830 if (*endptr == '\0' && ul != 0) {
2831 ALOGD("Silence is golden");
2832 // The setprop command will not allow a property to be changed after
2833 // the first time it is set, so we don't have to worry about un-muting.
2834 setMasterMute_l(true);
2835 }
2836 }
2837 }
2838}
2839
2840// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002841ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002842{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002843 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002844 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002845 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002846 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002847
2848 // If an NBAIO sink is present, use it to write the normal mixer's submix
2849 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002850
Andy Hung010a1a12014-03-13 13:57:33 -07002851 const size_t count = mBytesRemaining / mFrameSize;
2852
Simon Wilson2d590962012-11-29 15:18:50 -08002853 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002854 // update the setpoint when AudioFlinger::mScreenState changes
2855 uint32_t screenState = AudioFlinger::mScreenState;
2856 if (screenState != mScreenState) {
2857 mScreenState = screenState;
2858 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2859 if (pipe != NULL) {
2860 pipe->setAvgFrames((mScreenState & 1) ?
2861 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2862 }
2863 }
Andy Hung010a1a12014-03-13 13:57:33 -07002864 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002865 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002866 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002867 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002868#ifdef TEE_SINK
2869 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2870#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002871 } else {
2872 bytesWritten = framesWritten;
2873 }
2874 // otherwise use the HAL / AudioStreamOut directly
2875 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002876 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002877
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002879 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2880 mWriteAckSequence += 2;
2881 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002883 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002884 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002885 // FIXME We should have an implementation of timestamps for direct output threads.
2886 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002887 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002888
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 if (mUseAsyncWrite &&
2890 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2891 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002892 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002894 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895 }
Eric Laurent81784c32012-11-19 14:55:58 -08002896 }
2897
Eric Laurent81784c32012-11-19 14:55:58 -08002898 mNumWrites++;
2899 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002900 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002901 return bytesWritten;
2902}
2903
2904void AudioFlinger::PlaybackThread::threadLoop_drain()
2905{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002906 bool supportsDrain = false;
2907 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2909 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002910 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2911 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002912 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002913 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002915 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002916 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002917 }
2918}
2919
2920void AudioFlinger::PlaybackThread::threadLoop_exit()
2921{
Eric Laurent275e8e92014-11-30 15:14:47 -08002922 {
2923 Mutex::Autolock _l(mLock);
2924 for (size_t i = 0; i < mTracks.size(); i++) {
2925 sp<Track> track = mTracks[i];
2926 track->invalidate();
2927 }
Andy Hungdae27702016-10-31 14:01:16 -07002928 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2929 // After we exit there are no more track changes sent to BatteryNotifier
2930 // because that requires an active threadLoop.
2931 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2932 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002933 }
Eric Laurent81784c32012-11-19 14:55:58 -08002934}
2935
2936/*
2937The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002938 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002939 - mActiveSleepTimeUs from activeSleepTimeUs()
2940 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002941 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2942 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002943 - maxPeriod from frame count and sample rate (MIXER only)
2944
2945The parameters that affect these derived values are:
2946 - frame count
2947 - frame size
2948 - sample rate
2949 - device type: A2DP or not
2950 - device latency
2951 - format: PCM or not
2952 - active sleep time
2953 - idle sleep time
2954*/
2955
2956void AudioFlinger::PlaybackThread::cacheParameters_l()
2957{
Andy Hung25c2dac2014-02-27 14:56:00 -08002958 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002959 mActiveSleepTimeUs = activeSleepTimeUs();
2960 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002961
2962 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2963 // truncating audio when going to standby.
2964 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2965 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2966 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2967 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2968 }
2969 }
Eric Laurent81784c32012-11-19 14:55:58 -08002970}
2971
Eric Laurent13084622016-05-17 10:51:49 -07002972bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002973{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002974 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002975 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002976 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002977 size_t size = mTracks.size();
2978 for (size_t i = 0; i < size; i++) {
2979 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002980 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002981 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002982 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002983 }
2984 }
Eric Laurent13084622016-05-17 10:51:49 -07002985 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002986}
2987
Haynes Mathew George05317d22016-05-03 16:34:26 -07002988void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2989{
2990 Mutex::Autolock _l(mLock);
2991 invalidateTracks_l(streamType);
2992}
2993
Eric Laurent81784c32012-11-19 14:55:58 -08002994status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2995{
Glenn Kastend848eb42016-03-08 13:42:11 -08002996 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002997 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002998 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08002999 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3000 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3001 &halInBuffer);
3002 if (result != OK) return result;
3003 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003004 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003005 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003006 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003007 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003008 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003009 if (mType != DIRECT) {
3010 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003011 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003012 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003013 &halInBuffer);
3014 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003015#ifdef FLOAT_EFFECT_CHAIN
3016 buffer = halInBuffer->audioBuffer()->f32;
3017#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003018 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003019#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003020 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3021 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003022 }
3023
3024 // Attach all tracks with same session ID to this chain.
3025 for (size_t i = 0; i < mTracks.size(); ++i) {
3026 sp<Track> track = mTracks[i];
3027 if (session == track->sessionId()) {
3028 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3029 buffer);
3030 track->setMainBuffer(buffer);
3031 chain->incTrackCnt();
3032 }
3033 }
3034
3035 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003036 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003037 if (session == track->sessionId()) {
3038 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3039 chain->incActiveTrackCnt();
3040 }
3041 }
3042 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003043 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003044 chain->setInBuffer(halInBuffer);
3045 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003046 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003047 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003048 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3049 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003050 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003051 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003052 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003053 // Effect chain for other sessions are inserted at beginning of effect
3054 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003055 // sessions is not important.
3056 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3057 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3058 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003059 size_t size = mEffectChains.size();
3060 size_t i = 0;
3061 for (i = 0; i < size; i++) {
3062 if (mEffectChains[i]->sessionId() < session) {
3063 break;
3064 }
3065 }
3066 mEffectChains.insertAt(chain, i);
3067 checkSuspendOnAddEffectChain_l(chain);
3068
3069 return NO_ERROR;
3070}
3071
3072size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3073{
Glenn Kastend848eb42016-03-08 13:42:11 -08003074 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003075
3076 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3077
3078 for (size_t i = 0; i < mEffectChains.size(); i++) {
3079 if (chain == mEffectChains[i]) {
3080 mEffectChains.removeAt(i);
3081 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003082 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003083 if (session == track->sessionId()) {
3084 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3085 chain.get(), session);
3086 chain->decActiveTrackCnt();
3087 }
3088 }
3089
3090 // detach all tracks with same session ID from this chain
3091 for (size_t i = 0; i < mTracks.size(); ++i) {
3092 sp<Track> track = mTracks[i];
3093 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003094 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003095 chain->decTrackCnt();
3096 }
3097 }
3098 break;
3099 }
3100 }
3101 return mEffectChains.size();
3102}
3103
3104status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003105 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003106{
3107 Mutex::Autolock _l(mLock);
3108 return attachAuxEffect_l(track, EffectId);
3109}
3110
3111status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003112 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003113{
3114 status_t status = NO_ERROR;
3115
3116 if (EffectId == 0) {
3117 track->setAuxBuffer(0, NULL);
3118 } else {
3119 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3120 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3121 if (effect != 0) {
3122 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3123 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3124 } else {
3125 status = INVALID_OPERATION;
3126 }
3127 } else {
3128 status = BAD_VALUE;
3129 }
3130 }
3131 return status;
3132}
3133
3134void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3135{
3136 for (size_t i = 0; i < mTracks.size(); ++i) {
3137 sp<Track> track = mTracks[i];
3138 if (track->auxEffectId() == effectId) {
3139 attachAuxEffect_l(track, 0);
3140 }
3141 }
3142}
3143
3144bool AudioFlinger::PlaybackThread::threadLoop()
3145{
Glenn Kasten388d5712017-04-07 14:38:41 -07003146 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003147
Eric Laurent81784c32012-11-19 14:55:58 -08003148 Vector< sp<Track> > tracksToRemove;
3149
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003150 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003151 nsecs_t lastWriteFinished = -1; // time last server write completed
3152 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003153
3154 // MIXER
3155 nsecs_t lastWarning = 0;
3156
3157 // DUPLICATING
3158 // FIXME could this be made local to while loop?
3159 writeFrames = 0;
3160
3161 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003162 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003163
3164 if (mType == MIXER) {
3165 sleepTimeShift = 0;
3166 }
3167
3168 CpuStats cpuStats;
3169 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3170
3171 acquireWakeLock();
3172
Glenn Kasteneef598c2017-04-03 14:41:13 -07003173 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3174 // thread associated with this PlaybackThread.
3175 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3176 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003177 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3178 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003179 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003180 const char *logString = NULL;
3181
rago1bb90822017-05-02 18:31:48 -07003182 // Estimated time for next buffer to be written to hal. This is used only on
3183 // suspended mode (for now) to help schedule the wait time until next iteration.
3184 nsecs_t timeLoopNextNs = 0;
3185
Eric Laurent664539d2013-09-23 18:24:31 -07003186 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003187
Andy Hungf3234512018-07-03 14:51:47 -07003188 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3189 // TODO: add confirmation checks:
3190 // 1) DIRECT threads and linear PCM format really resets to 0?
3191 // 2) Is frame count really valid if not linear pcm?
3192 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3193 if (mType == OFFLOAD || mType == DIRECT) {
3194 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3195 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003196 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003197
Eric Laurent81784c32012-11-19 14:55:58 -08003198 while (!exitPending())
3199 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003200 // Log merge requests are performed during AudioFlinger binder transactions, but
3201 // that does not cover audio playback. It's requested here for that reason.
3202 mAudioFlinger->requestLogMerge();
3203
Eric Laurent81784c32012-11-19 14:55:58 -08003204 cpuStats.sample(myName);
3205
3206 Vector< sp<EffectChain> > effectChains;
3207
Andy Hung2dbffc22018-08-08 18:50:41 -07003208 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3209 //
3210 // Note: we access outDevice() outside of mLock.
3211 if (isMsdDevice() && (outDevice() & AUDIO_DEVICE_OUT_BUS) != 0) {
3212 // Here, we try for the AF lock, but do not block on it as the latency
3213 // is more informational.
3214 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3215 std::vector<PatchPanel::SoftwarePatch> swPatches;
3216 double latencyMs;
3217 status_t status = INVALID_OPERATION;
3218 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3219 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3220 && swPatches.size() > 0) {
3221 status = swPatches[0].getLatencyMs_l(&latencyMs);
3222 downstreamPatchHandle = swPatches[0].getPatchHandle();
3223 }
3224 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003225 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003226 lastDownstreamPatchHandle = downstreamPatchHandle;
3227 }
3228 if (status == OK) {
3229 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003230 // latency of 5 seconds).
3231 const double minLatency = 0., maxLatency = 5000.;
3232 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003233 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003234 } else {
3235 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003236 if (latencyMs < minLatency) latencyMs = minLatency;
3237 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003238 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003239 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003240 }
3241 mAudioFlinger->mLock.unlock();
3242 }
3243 } else {
3244 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3245 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003246 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003247 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3248 }
3249 }
3250
Eric Laurent81784c32012-11-19 14:55:58 -08003251 { // scope for mLock
3252
3253 Mutex::Autolock _l(mLock);
3254
Eric Laurent021cf962014-05-13 10:18:14 -07003255 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003256
Glenn Kasteneef598c2017-04-03 14:41:13 -07003257 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003258 if (logString != NULL) {
3259 mNBLogWriter->logTimestamp();
3260 mNBLogWriter->log(logString);
3261 logString = NULL;
3262 }
3263
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003264 // Collect timestamp statistics for the Playback Thread types that support it.
3265 if (mType == MIXER
3266 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003267 || mType == DIRECT
3268 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003269 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003270 // and associate with the sink frames written out. We need
3271 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003272 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003273 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003274 if (mStandby) {
3275 mTimestampVerifier.discontinuity();
3276 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3277 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3278 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3279 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003280
3281 if (isTimestampCorrectionEnabled()) {
3282 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3283 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3284 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3285 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3286 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3287 = correctedTimestamp.mFrames;
3288 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3289 = correctedTimestamp.mTimeNs;
3290 ALOGV("TS_AFTER: %d %lld %lld", id(),
3291 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3292 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003293
3294 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003295 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003296 const int64_t newPosition =
3297 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003298 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003299 // prevent retrograde
3300 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3301 newPosition,
3302 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3303 - mSuspendedFrames));
3304 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003305 }
3306
Andy Hung818e7a32016-02-16 18:08:07 -08003307 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003308 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003309
3310 // We keep track of the last valid kernel position in case we are in underrun
3311 // and the normal mixer period is the same as the fast mixer period, or there
3312 // is some error from the HAL.
3313 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3314 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3315 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3316 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3317 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3318
3319 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3320 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3321 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3322 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003323 }
3324
3325 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3326 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003327 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003328 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003329 }
3330
Andy Hung818e7a32016-02-16 18:08:07 -08003331 // copy over kernel info
3332 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003333 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3334 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003335 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3336 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003337 } else {
3338 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003339 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003340
Andy Hungc54b1ff2016-02-23 14:07:07 -08003341 // mFramesWritten for non-offloaded tracks are contiguous
3342 // even after standby() is called. This is useful for the track frame
3343 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003344 bool serverLocationUpdate = false;
3345 if (mFramesWritten != lastFramesWritten) {
3346 serverLocationUpdate = true;
3347 lastFramesWritten = mFramesWritten;
3348 }
3349 // Only update timestamps if there is a meaningful change.
3350 // Either the kernel timestamp must be valid or we have written something.
3351 if (kernelLocationUpdate || serverLocationUpdate) {
3352 if (serverLocationUpdate) {
3353 // use the time before we called the HAL write - it is a bit more accurate
3354 // to when the server last read data than the current time here.
3355 //
3356 // If we haven't written anything, mLastWriteTime will be -1
3357 // and we use systemTime().
3358 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3359 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3360 ? systemTime() : mLastWriteTime;
3361 }
Andy Hungdae27702016-10-31 14:01:16 -07003362
3363 for (const sp<Track> &t : mActiveTracks) {
3364 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003365 t->updateTrackFrameInfo(
3366 t->mAudioTrackServerProxy->framesReleased(),
3367 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003368 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003369 mTimestamp);
3370 }
Andy Hunge10393e2015-06-12 13:59:33 -07003371 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003372 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003373 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003374#if 0
3375 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003376 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003377 timespec ts;
3378 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003379 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003380 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003381 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003382 }
3383 ++z;
3384#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003385 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003386 if (mSignalPending) {
3387 // A signal was raised while we were unlocked
3388 mSignalPending = false;
3389 } else if (waitingAsyncCallback_l()) {
3390 if (exitPending()) {
3391 break;
3392 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003393 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003394 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003395 releaseWakeLock_l();
3396 released = true;
3397 }
Andy Hung10cbff12017-02-21 17:30:14 -08003398
3399 const int64_t waitNs = computeWaitTimeNs_l();
3400 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3401 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3402 if (status == TIMED_OUT) {
3403 mSignalPending = true; // if timeout recheck everything
3404 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003405 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003406 if (released) {
3407 acquireWakeLock_l();
3408 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003409 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3410 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003411
3412 continue;
3413 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003414 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003415 isSuspended()) {
3416 // put audio hardware into standby after short delay
3417 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003418
3419 threadLoop_standby();
3420
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003421 // This is where we go into standby
3422 if (!mStandby) {
3423 LOG_AUDIO_STATE();
3424 }
Eric Laurent81784c32012-11-19 14:55:58 -08003425 mStandby = true;
3426 }
3427
Eric Tan39ec8d62018-07-24 09:49:29 -07003428 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003429 // we're about to wait, flush the binder command buffer
3430 IPCThreadState::self()->flushCommands();
3431
3432 clearOutputTracks();
3433
3434 if (exitPending()) {
3435 break;
3436 }
3437
3438 releaseWakeLock_l();
3439 // wait until we have something to do...
3440 ALOGV("%s going to sleep", myName.string());
3441 mWaitWorkCV.wait(mLock);
3442 ALOGV("%s waking up", myName.string());
3443 acquireWakeLock_l();
3444
3445 mMixerStatus = MIXER_IDLE;
3446 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3447 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003448 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003449 checkSilentMode_l();
3450
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003451 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3452 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003453 if (mType == MIXER) {
3454 sleepTimeShift = 0;
3455 }
3456
3457 continue;
3458 }
3459 }
Eric Laurent81784c32012-11-19 14:55:58 -08003460 // mMixerStatusIgnoringFastTracks is also updated internally
3461 mMixerStatus = prepareTracks_l(&tracksToRemove);
3462
Andy Hungdae27702016-10-31 14:01:16 -07003463 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003464
Kevin Rocard069c2712018-03-29 19:09:14 -07003465 updateMetadata_l();
3466
Eric Laurent81784c32012-11-19 14:55:58 -08003467 // prevent any changes in effect chain list and in each effect chain
3468 // during mixing and effect process as the audio buffers could be deleted
3469 // or modified if an effect is created or deleted
3470 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003471 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003472
Eric Laurentbfb1b832013-01-07 09:53:42 -08003473 if (mBytesRemaining == 0) {
3474 mCurrentWriteLength = 0;
3475 if (mMixerStatus == MIXER_TRACKS_READY) {
3476 // threadLoop_mix() sets mCurrentWriteLength
3477 threadLoop_mix();
3478 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3479 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003480 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003481 // must be written to HAL
3482 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003483 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003484 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003485 }
3486 }
Andy Hung98ef9782014-03-04 14:46:50 -08003487 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003488 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003489 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3490 // or mSinkBuffer (if there are no effects).
3491 //
3492 // This is done pre-effects computation; if effects change to
3493 // support higher precision, this needs to move.
3494 //
3495 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003496 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003497 if (mMixerBufferValid) {
3498 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3499 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3500
Andy Hung2ddee192015-12-18 17:34:44 -08003501 // mono blend occurs for mixer threads only (not direct or offloaded)
3502 // and is handled here if we're going directly to the sink.
3503 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003504 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3505 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003506 }
3507
Andy Hung98ef9782014-03-04 14:46:50 -08003508 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3509 mNormalFrameCount * mChannelCount);
3510 }
3511
Eric Laurentbfb1b832013-01-07 09:53:42 -08003512 mBytesRemaining = mCurrentWriteLength;
3513 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003514 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3515 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3516 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3517 mBytesWritten += mBytesRemaining;
3518 mFramesWritten += framesRemaining;
3519 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003520 mBytesRemaining = 0;
3521 }
Eric Laurent81784c32012-11-19 14:55:58 -08003522
Eric Laurentbfb1b832013-01-07 09:53:42 -08003523 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003524 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003525 for (size_t i = 0; i < effectChains.size(); i ++) {
3526 effectChains[i]->process_l();
3527 }
Eric Laurent81784c32012-11-19 14:55:58 -08003528 }
3529 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003530 // Process effect chains for offloaded thread even if no audio
3531 // was read from audio track: process only updates effect state
3532 // and thus does have to be synchronized with audio writes but may have
3533 // to be called while waiting for async write callback
3534 if (mType == OFFLOAD) {
3535 for (size_t i = 0; i < effectChains.size(); i ++) {
3536 effectChains[i]->process_l();
3537 }
3538 }
Eric Laurent81784c32012-11-19 14:55:58 -08003539
Andy Hung98ef9782014-03-04 14:46:50 -08003540 // Only if the Effects buffer is enabled and there is data in the
3541 // Effects buffer (buffer valid), we need to
3542 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003543 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003544 if (mEffectBufferValid) {
3545 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003546
3547 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003548 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3549 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003550 }
3551
Andy Hung98ef9782014-03-04 14:46:50 -08003552 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3553 mNormalFrameCount * mChannelCount);
3554 }
3555
Eric Laurent81784c32012-11-19 14:55:58 -08003556 // enable changes in effect chain
3557 unlockEffectChains(effectChains);
3558
Eric Laurentbfb1b832013-01-07 09:53:42 -08003559 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003560 // mSleepTimeUs == 0 means we must write to audio hardware
3561 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003562 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003563 // We save lastWriteFinished here, as previousLastWriteFinished,
3564 // for throttling. On thread start, previousLastWriteFinished will be
3565 // set to -1, which properly results in no throttling after the first write.
3566 nsecs_t previousLastWriteFinished = lastWriteFinished;
3567 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003568 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003569 // FIXME rewrite to reduce number of system calls
3570 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003571 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003572 lastWriteFinished = systemTime();
3573 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 if (ret < 0) {
3575 mBytesRemaining = 0;
3576 } else {
3577 mBytesWritten += ret;
3578 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003579 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580 }
3581 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3582 (mMixerStatus == MIXER_DRAIN_ALL)) {
3583 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003584 }
Andy Hung08fb1742015-05-31 23:22:10 -07003585 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003586 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003587 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003588 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003589 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003590 ATRACE_NAME("underrun");
3591 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003592 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003593 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003594 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003595 }
Andy Hung08fb1742015-05-31 23:22:10 -07003596
3597 if (mThreadThrottle
3598 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3599 && ret > 0) { // we wrote something
3600 // Limit MixerThread data processing to no more than twice the
3601 // expected processing rate.
3602 //
3603 // This helps prevent underruns with NuPlayer and other applications
3604 // which may set up buffers that are close to the minimum size, or use
3605 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3606 //
3607 // The throttle smooths out sudden large data drains from the device,
3608 // e.g. when it comes out of standby, which often causes problems with
3609 // (1) mixer threads without a fast mixer (which has its own warm-up)
3610 // (2) minimum buffer sized tracks (even if the track is full,
3611 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003612 //
3613 // Total time spent in last processing cycle equals time spent in
3614 // 1. threadLoop_write, as well as time spent in
3615 // 2. threadLoop_mix (significant for heavy mixing, especially
3616 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003617
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003618 // it's OK if deltaMs (and deltaNs) is an overestimate.
3619 nsecs_t deltaNs;
3620 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3621 __builtin_sub_overflow(
3622 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3623 const int32_t deltaMs = deltaNs / 1000000;
3624
Ivan Lozanoea04d392017-11-07 14:37:07 -08003625 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003626 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3627 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003628 // notify of throttle start on verbose log
3629 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3630 "mixer(%p) throttle begin:"
3631 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003632 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003633 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003634 // Throttle must be attributed to the previous mixer loop's write time
3635 // to allow back-to-back throttling.
3636 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003637 } else {
3638 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3639 if (diff > 0) {
3640 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003641 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003642 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3643 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003644 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003645 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3646 }
Andy Hung08fb1742015-05-31 23:22:10 -07003647 }
3648 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003649 }
Eric Laurent81784c32012-11-19 14:55:58 -08003650
Eric Laurentbfb1b832013-01-07 09:53:42 -08003651 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003652 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003653 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003654 // suspended requires accurate metering of sleep time.
3655 if (isSuspended()) {
3656 // advance by expected sleepTime
3657 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3658 const nsecs_t nowNs = systemTime();
3659
3660 // compute expected next time vs current time.
3661 // (negative deltas are treated as delays).
3662 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3663 if (deltaNs < -kMaxNextBufferDelayNs) {
3664 // Delays longer than the max allowed trigger a reset.
3665 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3666 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3667 timeLoopNextNs = nowNs + deltaNs;
3668 } else if (deltaNs < 0) {
3669 // Delays within the max delay allowed: zero the delta/sleepTime
3670 // to help the system catch up in the next iteration(s)
3671 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3672 deltaNs = 0;
3673 }
3674 // update sleep time (which is >= 0)
3675 mSleepTimeUs = deltaNs / 1000;
3676 }
Eric Laurente93cc032016-05-05 10:15:10 -07003677 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3678 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003679 }
Glenn Kastene7754022014-10-31 12:11:26 -07003680 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681 }
Eric Laurent81784c32012-11-19 14:55:58 -08003682 }
3683
3684 // Finally let go of removed track(s), without the lock held
3685 // since we can't guarantee the destructors won't acquire that
3686 // same lock. This will also mutate and push a new fast mixer state.
3687 threadLoop_removeTracks(tracksToRemove);
3688 tracksToRemove.clear();
3689
3690 // FIXME I don't understand the need for this here;
3691 // it was in the original code but maybe the
3692 // assignment in saveOutputTracks() makes this unnecessary?
3693 clearOutputTracks();
3694
3695 // Effect chains will be actually deleted here if they were removed from
3696 // mEffectChains list during mixing or effects processing
3697 effectChains.clear();
3698
3699 // FIXME Note that the above .clear() is no longer necessary since effectChains
3700 // is now local to this block, but will keep it for now (at least until merge done).
3701 }
3702
Eric Laurentbfb1b832013-01-07 09:53:42 -08003703 threadLoop_exit();
3704
Eric Laurentcf817a22014-08-04 20:36:31 -07003705 if (!mStandby) {
3706 threadLoop_standby();
3707 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003708 }
3709
3710 releaseWakeLock();
3711
3712 ALOGV("Thread %p type %d exiting", this, mType);
3713 return false;
3714}
3715
Eric Laurentbfb1b832013-01-07 09:53:42 -08003716// removeTracks_l() must be called with ThreadBase::mLock held
3717void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3718{
Andy Hungfe726a62018-09-27 15:17:25 -07003719 for (const auto& track : tracksToRemove) {
3720 mActiveTracks.remove(track);
3721 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3722 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3723 if (chain != 0) {
3724 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3725 __func__, track->id(), chain.get(), track->sessionId());
3726 chain->decActiveTrackCnt();
3727 }
3728 // If an external client track, inform APM we're no longer active, and remove if needed.
3729 // We do this under lock so that the state is consistent if the Track is destroyed.
3730 if (track->isExternalTrack()) {
3731 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003732 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003733 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003734 }
3735 }
Andy Hungfe726a62018-09-27 15:17:25 -07003736 if (track->isTerminated()) {
3737 // remove from our tracks vector
3738 removeTrack_l(track);
3739 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003740 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003741}
Eric Laurent81784c32012-11-19 14:55:58 -08003742
Eric Laurentaccc1472013-09-20 09:36:34 -07003743status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3744{
3745 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003746 ExtendedTimestamp ets;
3747 status_t status = mNormalSink->getTimestamp(ets);
3748 if (status == NO_ERROR) {
3749 status = ets.getBestTimestamp(&timestamp);
3750 }
3751 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003752 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003753 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003754 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003755 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003756 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11003757 if (mDownstreamLatencyStatMs.getN() > 0) {
3758 const uint32_t positionOffset =
3759 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3760 if (positionOffset > timestamp.mPosition) {
3761 timestamp.mPosition = 0;
3762 } else {
3763 timestamp.mPosition -= positionOffset;
3764 }
3765 }
Eric Laurentaccc1472013-09-20 09:36:34 -07003766 return NO_ERROR;
3767 }
3768 }
3769 return INVALID_OPERATION;
3770}
Eric Laurent1c333e22014-05-20 10:48:17 -07003771
Eric Laurent054d9d32015-04-24 08:48:48 -07003772status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3773 audio_patch_handle_t *handle)
3774{
Andy Hungf60abce2016-08-26 11:37:54 -07003775 status_t status;
3776 if (property_get_bool("af.patch_park", false /* default_value */)) {
3777 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3778 // or if HAL does not properly lock against access.
3779 AutoPark<FastMixer> park(mFastMixer);
3780 status = PlaybackThread::createAudioPatch_l(patch, handle);
3781 } else {
3782 status = PlaybackThread::createAudioPatch_l(patch, handle);
3783 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003784 return status;
3785}
3786
Eric Laurent1c333e22014-05-20 10:48:17 -07003787status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3788 audio_patch_handle_t *handle)
3789{
3790 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003791
3792 // store new device and send to effects
3793 audio_devices_t type = AUDIO_DEVICE_NONE;
3794 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3795 type |= patch->sinks[i].ext.device.type;
3796 }
3797
3798#ifdef ADD_BATTERY_DATA
3799 // when changing the audio output device, call addBatteryData to notify
3800 // the change
3801 if (mOutDevice != type) {
3802 uint32_t params = 0;
3803 // check whether speaker is on
3804 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3805 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003806 }
3807
Eric Laurent054d9d32015-04-24 08:48:48 -07003808 audio_devices_t deviceWithoutSpeaker
3809 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3810 // check if any other device (except speaker) is on
3811 if (type & deviceWithoutSpeaker) {
3812 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3813 }
3814
3815 if (params != 0) {
3816 addBatteryData(params);
3817 }
3818 }
3819#endif
3820
3821 for (size_t i = 0; i < mEffectChains.size(); i++) {
3822 mEffectChains[i]->setDevice_l(type);
3823 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003824
3825 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3826 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3827 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003828 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003829 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003830
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003831 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003832 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3833 status = hwDevice->createAudioPatch(patch->num_sources,
3834 patch->sources,
3835 patch->num_sinks,
3836 patch->sinks,
3837 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003838 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003839 char *address;
3840 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3841 //FIXME: we only support address on first sink with HAL version < 3.0
3842 address = audio_device_address_to_parameter(
3843 patch->sinks[0].ext.device.type,
3844 patch->sinks[0].ext.device.address);
3845 } else {
3846 address = (char *)calloc(1, 1);
3847 }
3848 AudioParameter param = AudioParameter(String8(address));
3849 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003850 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003851 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003852 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003853 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003854 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003855 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003856 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3857 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003858 return status;
3859}
3860
Eric Laurent054d9d32015-04-24 08:48:48 -07003861status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3862{
Andy Hungf60abce2016-08-26 11:37:54 -07003863 status_t status;
3864 if (property_get_bool("af.patch_park", false /* default_value */)) {
3865 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3866 // or if HAL does not properly lock against access.
3867 AutoPark<FastMixer> park(mFastMixer);
3868 status = PlaybackThread::releaseAudioPatch_l(handle);
3869 } else {
3870 status = PlaybackThread::releaseAudioPatch_l(handle);
3871 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003872 return status;
3873}
3874
Eric Laurent1c333e22014-05-20 10:48:17 -07003875status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3876{
3877 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003878
3879 mOutDevice = AUDIO_DEVICE_NONE;
3880
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003881 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003882 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3883 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003884 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003885 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003886 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003887 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003888 }
3889 return status;
3890}
3891
Eric Laurent83b88082014-06-20 18:31:16 -07003892void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3893{
3894 Mutex::Autolock _l(mLock);
3895 mTracks.add(track);
3896}
3897
3898void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3899{
3900 Mutex::Autolock _l(mLock);
3901 destroyTrack_l(track);
3902}
3903
Mikhail Naganovdc769682018-05-04 15:34:08 -07003904void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003905{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003906 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003907 config->role = AUDIO_PORT_ROLE_SOURCE;
3908 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3909 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003910 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3911 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3912 config->flags.output = mOutput->flags;
3913 }
Eric Laurent83b88082014-06-20 18:31:16 -07003914}
3915
Eric Laurent81784c32012-11-19 14:55:58 -08003916// ----------------------------------------------------------------------------
3917
3918AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003919 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3920 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003921 // mAudioMixer below
3922 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003923 mFastMixerFutex(0),
3924 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003925 // mOutputSink below
3926 // mPipeSink below
3927 // mNormalSink below
3928{
3929 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003930 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003931 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003932 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3933 mNormalFrameCount);
3934 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3935
Andy Hungfbfc3952015-01-15 13:33:51 -08003936 if (type == DUPLICATING) {
3937 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3938 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3939 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3940 return;
3941 }
Eric Laurent81784c32012-11-19 14:55:58 -08003942 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003943 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003944 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003945 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003946#if !LOG_NDEBUG
3947 ssize_t index =
3948#else
3949 (void)
3950#endif
3951 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003952 ALOG_ASSERT(index == 0);
3953
3954 // initialize fast mixer depending on configuration
3955 bool initFastMixer;
3956 switch (kUseFastMixer) {
3957 case FastMixer_Never:
3958 initFastMixer = false;
3959 break;
3960 case FastMixer_Always:
3961 initFastMixer = true;
3962 break;
3963 case FastMixer_Static:
3964 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003965 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3966 // where the period is less than an experimentally determined threshold that can be
3967 // scheduled reliably with CFS. However, the BT A2DP HAL is
3968 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3969 initFastMixer = mFrameCount < mNormalFrameCount
3970 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003971 break;
3972 }
Andy Hungfda69402017-02-15 14:33:12 -08003973 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3974 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3975 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003976 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003977 audio_format_t fastMixerFormat;
3978 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3979 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3980 } else {
3981 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3982 }
3983 if (mFormat != fastMixerFormat) {
3984 // change our Sink format to accept our intermediate precision
3985 mFormat = fastMixerFormat;
3986 free(mSinkBuffer);
3987 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3988 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3989 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3990 }
Eric Laurent81784c32012-11-19 14:55:58 -08003991
3992 // create a MonoPipe to connect our submix to FastMixer
3993 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07003994
Andy Hung1258c1a2014-05-23 21:22:17 -07003995 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003996 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003997 format.mFormat = fastMixerFormat;
3998 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3999
Eric Laurent81784c32012-11-19 14:55:58 -08004000 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4001 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4002 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4003 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4004 const NBAIO_Format offers[1] = {format};
4005 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004006#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004007 ssize_t index =
4008#else
4009 (void)
4010#endif
4011 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004012 ALOG_ASSERT(index == 0);
4013 monoPipe->setAvgFrames((mScreenState & 1) ?
4014 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4015 mPipeSink = monoPipe;
4016
Eric Laurent81784c32012-11-19 14:55:58 -08004017 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004018 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004019 FastMixerStateQueue *sq = mFastMixer->sq();
4020#ifdef STATE_QUEUE_DUMP
4021 sq->setObserverDump(&mStateQueueObserverDump);
4022 sq->setMutatorDump(&mStateQueueMutatorDump);
4023#endif
4024 FastMixerState *state = sq->begin();
4025 FastTrack *fastTrack = &state->mFastTracks[0];
4026 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4027 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4028 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004029 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
4030 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08004031 fastTrack->mGeneration++;
4032 state->mFastTracksGen++;
4033 state->mTrackMask = 1;
4034 // fast mixer will use the HAL output sink
4035 state->mOutputSink = mOutputSink.get();
4036 state->mOutputSinkGen++;
4037 state->mFrameCount = mFrameCount;
4038 state->mCommand = FastMixerState::COLD_IDLE;
4039 // already done in constructor initialization list
4040 //mFastMixerFutex = 0;
4041 state->mColdFutexAddr = &mFastMixerFutex;
4042 state->mColdGen++;
4043 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004044 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4045 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004046 sq->end();
4047 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4048
Eric Tan0513b5d2018-09-17 10:32:48 -07004049 NBLog::thread_info_t info;
4050 info.id = mId;
4051 info.type = NBLog::FASTMIXER;
4052 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4053
Eric Laurent81784c32012-11-19 14:55:58 -08004054 // start the fast mixer
4055 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4056 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004057 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004058 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004059
4060#ifdef AUDIO_WATCHDOG
4061 // create and start the watchdog
4062 mAudioWatchdog = new AudioWatchdog();
4063 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4064 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4065 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004066 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004067#endif
Andy Hung8946a282018-04-19 20:04:56 -07004068 } else {
4069#ifdef TEE_SINK
4070 // Only use the MixerThread tee if there is no FastMixer.
4071 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4072 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4073#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004074 }
4075
4076 switch (kUseFastMixer) {
4077 case FastMixer_Never:
4078 case FastMixer_Dynamic:
4079 mNormalSink = mOutputSink;
4080 break;
4081 case FastMixer_Always:
4082 mNormalSink = mPipeSink;
4083 break;
4084 case FastMixer_Static:
4085 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4086 break;
4087 }
4088}
4089
4090AudioFlinger::MixerThread::~MixerThread()
4091{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004092 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004093 FastMixerStateQueue *sq = mFastMixer->sq();
4094 FastMixerState *state = sq->begin();
4095 if (state->mCommand == FastMixerState::COLD_IDLE) {
4096 int32_t old = android_atomic_inc(&mFastMixerFutex);
4097 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004098 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004099 }
4100 }
4101 state->mCommand = FastMixerState::EXIT;
4102 sq->end();
4103 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4104 mFastMixer->join();
4105 // Though the fast mixer thread has exited, it's state queue is still valid.
4106 // We'll use that extract the final state which contains one remaining fast track
4107 // corresponding to our sub-mix.
4108 state = sq->begin();
4109 ALOG_ASSERT(state->mTrackMask == 1);
4110 FastTrack *fastTrack = &state->mFastTracks[0];
4111 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4112 delete fastTrack->mBufferProvider;
4113 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004114 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004115#ifdef AUDIO_WATCHDOG
4116 if (mAudioWatchdog != 0) {
4117 mAudioWatchdog->requestExit();
4118 mAudioWatchdog->requestExitAndWait();
4119 mAudioWatchdog.clear();
4120 }
4121#endif
4122 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004123 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004124 delete mAudioMixer;
4125}
4126
4127
4128uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4129{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004130 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004131 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4132 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4133 }
4134 return latency;
4135}
4136
Eric Laurentbfb1b832013-01-07 09:53:42 -08004137ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004138{
4139 // FIXME we should only do one push per cycle; confirm this is true
4140 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004141 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004142 FastMixerStateQueue *sq = mFastMixer->sq();
4143 FastMixerState *state = sq->begin();
4144 if (state->mCommand != FastMixerState::MIX_WRITE &&
4145 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4146 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004147
4148 // FIXME workaround for first HAL write being CPU bound on some devices
4149 ATRACE_BEGIN("write");
4150 mOutput->write((char *)mSinkBuffer, 0);
4151 ATRACE_END();
4152
Eric Laurent81784c32012-11-19 14:55:58 -08004153 int32_t old = android_atomic_inc(&mFastMixerFutex);
4154 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004155 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004156 }
4157#ifdef AUDIO_WATCHDOG
4158 if (mAudioWatchdog != 0) {
4159 mAudioWatchdog->resume();
4160 }
4161#endif
4162 }
4163 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004164#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004165 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004166 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004167#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004168 sq->end();
4169 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4170 if (kUseFastMixer == FastMixer_Dynamic) {
4171 mNormalSink = mPipeSink;
4172 }
4173 } else {
4174 sq->end(false /*didModify*/);
4175 }
4176 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004177 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004178}
4179
4180void AudioFlinger::MixerThread::threadLoop_standby()
4181{
4182 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004183 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004184 FastMixerStateQueue *sq = mFastMixer->sq();
4185 FastMixerState *state = sq->begin();
4186 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004187 // Report any frames trapped in the Monopipe
4188 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4189 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4190 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4191 "monoPipeWritten:%lld monoPipeLeft:%lld",
4192 (long long)mFramesWritten, (long long)mSuspendedFrames,
4193 (long long)mPipeSink->framesWritten(), pipeFrames);
4194 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4195
Eric Laurent81784c32012-11-19 14:55:58 -08004196 state->mCommand = FastMixerState::COLD_IDLE;
4197 state->mColdFutexAddr = &mFastMixerFutex;
4198 state->mColdGen++;
4199 mFastMixerFutex = 0;
4200 sq->end();
4201 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4202 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4203 if (kUseFastMixer == FastMixer_Dynamic) {
4204 mNormalSink = mOutputSink;
4205 }
4206#ifdef AUDIO_WATCHDOG
4207 if (mAudioWatchdog != 0) {
4208 mAudioWatchdog->pause();
4209 }
4210#endif
4211 } else {
4212 sq->end(false /*didModify*/);
4213 }
4214 }
4215 PlaybackThread::threadLoop_standby();
4216}
4217
Eric Laurentbfb1b832013-01-07 09:53:42 -08004218bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4219{
4220 return false;
4221}
4222
4223bool AudioFlinger::PlaybackThread::shouldStandby_l()
4224{
4225 return !mStandby;
4226}
4227
4228bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4229{
4230 Mutex::Autolock _l(mLock);
4231 return waitingAsyncCallback_l();
4232}
4233
Eric Laurent81784c32012-11-19 14:55:58 -08004234// shared by MIXER and DIRECT, overridden by DUPLICATING
4235void AudioFlinger::PlaybackThread::threadLoop_standby()
4236{
4237 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004238 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004239 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004240 // discard any pending drain or write ack by incrementing sequence
4241 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4242 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004243 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004244 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4245 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004246 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004247 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004248}
4249
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004250void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4251{
4252 ALOGV("signal playback thread");
4253 broadcast_l();
4254}
4255
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004256void AudioFlinger::PlaybackThread::onAsyncError()
4257{
4258 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4259 invalidateTracks((audio_stream_type_t)i);
4260 }
4261}
4262
Eric Laurent81784c32012-11-19 14:55:58 -08004263void AudioFlinger::MixerThread::threadLoop_mix()
4264{
Eric Laurent81784c32012-11-19 14:55:58 -08004265 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004266 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004267 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004268 // increase sleep time progressively when application underrun condition clears.
4269 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4270 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4271 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004272 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004273 sleepTimeShift--;
4274 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004275 mSleepTimeUs = 0;
4276 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004277 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004278
Eric Laurent81784c32012-11-19 14:55:58 -08004279}
4280
4281void AudioFlinger::MixerThread::threadLoop_sleepTime()
4282{
4283 // If no tracks are ready, sleep once for the duration of an output
4284 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004285 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004286 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004287 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4288 // Using the Monopipe availableToWrite, we estimate the
4289 // sleep time to retry for more data (before we underrun).
4290 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4291 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4292 const size_t pipeFrames = monoPipe->maxFrames();
4293 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4294 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4295 const size_t framesDelay = std::min(
4296 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4297 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4298 pipeFrames, framesLeft, framesDelay);
4299 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4300 } else {
4301 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4302 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4303 mSleepTimeUs = kMinThreadSleepTimeUs;
4304 }
4305 // reduce sleep time in case of consecutive application underruns to avoid
4306 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4307 // duration we would end up writing less data than needed by the audio HAL if
4308 // the condition persists.
4309 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4310 sleepTimeShift++;
4311 }
Eric Laurent81784c32012-11-19 14:55:58 -08004312 }
4313 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004314 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004315 }
4316 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004317 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4318 // before effects processing or output.
4319 if (mMixerBufferValid) {
4320 memset(mMixerBuffer, 0, mMixerBufferSize);
4321 } else {
4322 memset(mSinkBuffer, 0, mSinkBufferSize);
4323 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004324 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004325 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4326 "anticipated start");
4327 }
4328 // TODO add standby time extension fct of effect tail
4329}
4330
4331// prepareTracks_l() must be called with ThreadBase::mLock held
4332AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4333 Vector< sp<Track> > *tracksToRemove)
4334{
Andy Hungc0691382018-09-12 18:01:57 -07004335 // clean up deleted track ids in AudioMixer before allocating new tracks
4336 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4337 // for each trackId, destroy it in the AudioMixer
4338 if (mAudioMixer->exists(trackId)) {
4339 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004340 }
4341 });
Andy Hungc0691382018-09-12 18:01:57 -07004342 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004343
4344 mixer_state mixerStatus = MIXER_IDLE;
4345 // find out which tracks need to be processed
4346 size_t count = mActiveTracks.size();
4347 size_t mixedTracks = 0;
4348 size_t tracksWithEffect = 0;
4349 // counts only _active_ fast tracks
4350 size_t fastTracks = 0;
4351 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4352
4353 float masterVolume = mMasterVolume;
4354 bool masterMute = mMasterMute;
4355
4356 if (masterMute) {
4357 masterVolume = 0;
4358 }
4359 // Delegate master volume control to effect in output mix effect chain if needed
4360 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4361 if (chain != 0) {
4362 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4363 chain->setVolume_l(&v, &v);
4364 masterVolume = (float)((v + (1 << 23)) >> 24);
4365 chain.clear();
4366 }
4367
4368 // prepare a new state to push
4369 FastMixerStateQueue *sq = NULL;
4370 FastMixerState *state = NULL;
4371 bool didModify = false;
4372 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004373 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004374 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004375 sq = mFastMixer->sq();
4376 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004377 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004378 }
4379
Andy Hung69aed5f2014-02-25 17:24:40 -08004380 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004381 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004382
Andy Hungbd3b2b02018-05-21 10:53:11 -07004383 // DeferredOperations handles statistics after setting mixerStatus.
4384 class DeferredOperations {
4385 public:
4386 DeferredOperations(mixer_state *mixerStatus)
4387 : mMixerStatus(mixerStatus) { }
4388
4389 // when leaving scope, tally frames properly.
4390 ~DeferredOperations() {
4391 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4392 // because that is when the underrun occurs.
4393 // We do not distinguish between FastTracks and NormalTracks here.
4394 if (*mMixerStatus == MIXER_TRACKS_READY) {
4395 for (const auto &underrun : mUnderrunFrames) {
4396 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4397 underrun.second);
4398 }
4399 }
4400 }
4401
4402 // tallyUnderrunFrames() is called to update the track counters
4403 // with the number of underrun frames for a particular mixer period.
4404 // We defer tallying until we know the final mixer status.
4405 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4406 mUnderrunFrames.emplace_back(track, underrunFrames);
4407 }
4408
4409 private:
4410 const mixer_state * const mMixerStatus;
4411 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4412 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4413
Eric Laurent81784c32012-11-19 14:55:58 -08004414 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004415 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004416
4417 // this const just means the local variable doesn't change
4418 Track* const track = t.get();
4419
4420 // process fast tracks
4421 if (track->isFastTrack()) {
4422
4423 // It's theoretically possible (though unlikely) for a fast track to be created
4424 // and then removed within the same normal mix cycle. This is not a problem, as
4425 // the track never becomes active so it's fast mixer slot is never touched.
4426 // The converse, of removing an (active) track and then creating a new track
4427 // at the identical fast mixer slot within the same normal mix cycle,
4428 // is impossible because the slot isn't marked available until the end of each cycle.
4429 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004430 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004431 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4432 FastTrack *fastTrack = &state->mFastTracks[j];
4433
4434 // Determine whether the track is currently in underrun condition,
4435 // and whether it had a recent underrun.
4436 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4437 FastTrackUnderruns underruns = ftDump->mUnderruns;
4438 uint32_t recentFull = (underruns.mBitFields.mFull -
4439 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4440 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4441 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4442 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4443 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4444 uint32_t recentUnderruns = recentPartial + recentEmpty;
4445 track->mObservedUnderruns = underruns;
4446 // don't count underruns that occur while stopping or pausing
4447 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004448 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004449 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4450 recentUnderruns > 0) {
4451 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004452 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004453 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004454 // Immediately account for FastTrack underruns.
4455 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004456
4457 // This is similar to the state machine for normal tracks,
4458 // with a few modifications for fast tracks.
4459 bool isActive = true;
4460 switch (track->mState) {
4461 case TrackBase::STOPPING_1:
4462 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004463 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004464 track->mState = TrackBase::STOPPING_2;
4465 }
4466 break;
4467 case TrackBase::PAUSING:
4468 // ramp down is not yet implemented
4469 track->setPaused();
4470 break;
4471 case TrackBase::RESUMING:
4472 // ramp up is not yet implemented
4473 track->mState = TrackBase::ACTIVE;
4474 break;
4475 case TrackBase::ACTIVE:
4476 if (recentFull > 0 || recentPartial > 0) {
4477 // track has provided at least some frames recently: reset retry count
4478 track->mRetryCount = kMaxTrackRetries;
4479 }
4480 if (recentUnderruns == 0) {
4481 // no recent underruns: stay active
4482 break;
4483 }
4484 // there has recently been an underrun of some kind
4485 if (track->sharedBuffer() == 0) {
4486 // were any of the recent underruns "empty" (no frames available)?
4487 if (recentEmpty == 0) {
4488 // no, then ignore the partial underruns as they are allowed indefinitely
4489 break;
4490 }
4491 // there has recently been an "empty" underrun: decrement the retry counter
4492 if (--(track->mRetryCount) > 0) {
4493 break;
4494 }
4495 // indicate to client process that the track was disabled because of underrun;
4496 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004497 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004498 // remove from active list, but state remains ACTIVE [confusing but true]
4499 isActive = false;
4500 break;
4501 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004502 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004503 case TrackBase::STOPPING_2:
4504 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004505 case TrackBase::STOPPED:
4506 case TrackBase::FLUSHED: // flush() while active
4507 // Check for presentation complete if track is inactive
4508 // We have consumed all the buffers of this track.
4509 // This would be incomplete if we auto-paused on underrun
4510 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004511 uint32_t latency = 0;
4512 status_t result = mOutput->stream->getLatency(&latency);
4513 ALOGE_IF(result != OK,
4514 "Error when retrieving output stream latency: %d", result);
4515 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004516 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004517 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4518 // track stays in active list until presentation is complete
4519 break;
4520 }
4521 }
4522 if (track->isStopping_2()) {
4523 track->mState = TrackBase::STOPPED;
4524 }
4525 if (track->isStopped()) {
4526 // Can't reset directly, as fast mixer is still polling this track
4527 // track->reset();
4528 // So instead mark this track as needing to be reset after push with ack
4529 resetMask |= 1 << i;
4530 }
4531 isActive = false;
4532 break;
4533 case TrackBase::IDLE:
4534 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004535 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004536 }
4537
4538 if (isActive) {
4539 // was it previously inactive?
4540 if (!(state->mTrackMask & (1 << j))) {
4541 ExtendedAudioBufferProvider *eabp = track;
4542 VolumeProvider *vp = track;
4543 fastTrack->mBufferProvider = eabp;
4544 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004545 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004546 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004547 fastTrack->mGeneration++;
4548 state->mTrackMask |= 1 << j;
4549 didModify = true;
4550 // no acknowledgement required for newly active tracks
4551 }
Kevin Rocard12381092018-04-11 09:19:59 -07004552 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004553 // cache the combined master volume and stream type volume for fast mixer; this
4554 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004555 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004556 proxy->framesReleased()).first;
4557 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004558 * mStreamTypes[track->streamType()].volume
4559 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004560 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004561 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4562 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4563 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4564 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004565 ++fastTracks;
4566 } else {
4567 // was it previously active?
4568 if (state->mTrackMask & (1 << j)) {
4569 fastTrack->mBufferProvider = NULL;
4570 fastTrack->mGeneration++;
4571 state->mTrackMask &= ~(1 << j);
4572 didModify = true;
4573 // If any fast tracks were removed, we must wait for acknowledgement
4574 // because we're about to decrement the last sp<> on those tracks.
4575 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4576 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004577 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4578 // AudioTrack may start (which may not be with a start() but with a write()
4579 // after underrun) and immediately paused or released. In that case the
4580 // FastTrack state hasn't had time to update.
4581 // TODO Remove the ALOGW when this theory is confirmed.
4582 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004583 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4584 j, track->mState, state->mTrackMask, recentUnderruns,
4585 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004586 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004587 }
4588 tracksToRemove->add(track);
4589 // Avoids a misleading display in dumpsys
4590 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4591 }
4592 continue;
4593 }
4594
4595 { // local variable scope to avoid goto warning
4596
4597 audio_track_cblk_t* cblk = track->cblk();
4598
4599 // The first time a track is added we wait
4600 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004601 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004602
4603 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004604 // use the trackId as the AudioMixer name.
4605 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004606 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004607 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004608 track->mChannelMask,
4609 track->mFormat,
4610 track->mSessionId);
4611 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004612 ALOGW("%s(): AudioMixer cannot create track(%d)"
4613 " mask %#x, format %#x, sessionId %d",
4614 __func__, trackId,
4615 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004616 tracksToRemove->add(track);
4617 track->invalidate(); // consider it dead.
4618 continue;
4619 }
4620 }
4621
Eric Laurent81784c32012-11-19 14:55:58 -08004622 // make sure that we have enough frames to mix one full buffer.
4623 // enforce this condition only once to enable draining the buffer in case the client
4624 // app does not call stop() and relies on underrun to stop:
4625 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4626 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004627 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004628 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004629 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004630
4631 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004632 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004633 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4634 // add frames already consumed but not yet released by the resampler
4635 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004636 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004637
Eric Laurent81784c32012-11-19 14:55:58 -08004638 uint32_t minFrames = 1;
4639 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4640 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004641 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004642 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004643
4644 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004645 if (ATRACE_ENABLED()) {
4646 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004647 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004648 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004649 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004650 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004651 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004652 !track->isPaused() && !track->isTerminated())
4653 {
Andy Hungc0691382018-09-12 18:01:57 -07004654 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004655
4656 mixedTracks++;
4657
Andy Hung69aed5f2014-02-25 17:24:40 -08004658 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4659 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004660 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004661 if (track->mainBuffer() != mSinkBuffer &&
4662 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004663 if (mEffectBufferEnabled) {
4664 mEffectBufferValid = true; // Later can set directly.
4665 }
Eric Laurent81784c32012-11-19 14:55:58 -08004666 chain = getEffectChain_l(track->sessionId());
4667 // Delegate volume control to effect in track effect chain if needed
4668 if (chain != 0) {
4669 tracksWithEffect++;
4670 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004671 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004672 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004673 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004674 }
4675 }
4676
4677
4678 int param = AudioMixer::VOLUME;
4679 if (track->mFillingUpStatus == Track::FS_FILLED) {
4680 // no ramp for the first volume setting
4681 track->mFillingUpStatus = Track::FS_ACTIVE;
4682 if (track->mState == TrackBase::RESUMING) {
4683 track->mState = TrackBase::ACTIVE;
4684 param = AudioMixer::RAMP_VOLUME;
4685 }
Andy Hungc0691382018-09-12 18:01:57 -07004686 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004687 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004688 // FIXME should not make a decision based on mServer
4689 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004690 // If the track is stopped before the first frame was mixed,
4691 // do not apply ramp
4692 param = AudioMixer::RAMP_VOLUME;
4693 }
4694
4695 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004696 uint32_t vl, vr; // in U8.24 integer format
4697 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004698 // read original volumes with volume control
4699 float typeVolume = mStreamTypes[track->streamType()].volume;
4700 float v = masterVolume * typeVolume;
4701
Glenn Kastene4756fe2012-11-29 13:38:14 -08004702 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004703 vl = vr = 0;
4704 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004705 if (track->isPausing()) {
4706 track->setPaused();
4707 }
4708 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004709 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004710 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004711 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4712 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004713 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004714 if (vlf > GAIN_FLOAT_UNITY) {
4715 ALOGV("Track left volume out of range: %.3g", vlf);
4716 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004717 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004718 if (vrf > GAIN_FLOAT_UNITY) {
4719 ALOGV("Track right volume out of range: %.3g", vrf);
4720 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004721 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004722 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004723 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004724 // now apply the master volume and stream type volume and shaper volume
4725 vlf *= v * vh;
4726 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004727 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004728 // then derive vl and vr as U8.24 versions for the effect chain
4729 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4730 vl = (uint32_t) (scaleto8_24 * vlf);
4731 vr = (uint32_t) (scaleto8_24 * vrf);
4732 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004733 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004734 // send level comes from shared memory and so may be corrupt
4735 if (sendLevel > MAX_GAIN_INT) {
4736 ALOGV("Track send level out of range: %04X", sendLevel);
4737 sendLevel = MAX_GAIN_INT;
4738 }
Andy Hung6be49402014-05-30 10:42:03 -07004739 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4740 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004741 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004742
Kevin Rocard12381092018-04-11 09:19:59 -07004743 track->setFinalVolume((vrf + vlf) / 2.f);
4744
Eric Laurent81784c32012-11-19 14:55:58 -08004745 // Delegate volume control to effect in track effect chain if needed
4746 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4747 // Do not ramp volume if volume is controlled by effect
4748 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004749 // Update remaining floating point volume levels
4750 vlf = (float)vl / (1 << 24);
4751 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004752 track->mHasVolumeController = true;
4753 } else {
4754 // force no volume ramp when volume controller was just disabled or removed
4755 // from effect chain to avoid volume spike
4756 if (track->mHasVolumeController) {
4757 param = AudioMixer::VOLUME;
4758 }
4759 track->mHasVolumeController = false;
4760 }
4761
Eric Laurent7c29ec92017-09-20 17:54:22 -07004762 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4763 // still applied by the mixer.
4764 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4765 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4766 if (v != mLeftVolFloat) {
4767 status_t result = mOutput->stream->setVolume(v, v);
4768 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4769 if (result == OK) {
4770 mLeftVolFloat = v;
4771 }
4772 }
4773 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4774 // remove stream volume contribution from software volume.
4775 if (v != 0.0f && mLeftVolFloat == v) {
4776 vlf = min(1.0f, vlf / v);
4777 vrf = min(1.0f, vrf / v);
4778 vaf = min(1.0f, vaf / v);
4779 }
4780 }
Eric Laurent81784c32012-11-19 14:55:58 -08004781 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07004782 mAudioMixer->setBufferProvider(trackId, track);
4783 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004784
Andy Hungc0691382018-09-12 18:01:57 -07004785 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
4786 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
4787 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004788 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004789 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004790 AudioMixer::TRACK,
4791 AudioMixer::FORMAT, (void *)track->format());
4792 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004793 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004794 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004795 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004796 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004797 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07004798 AudioMixer::TRACK,
4799 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004800 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004801 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004802 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004803 if (reqSampleRate == 0) {
4804 reqSampleRate = mSampleRate;
4805 } else if (reqSampleRate > maxSampleRate) {
4806 reqSampleRate = maxSampleRate;
4807 }
Eric Laurent81784c32012-11-19 14:55:58 -08004808 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004809 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004810 AudioMixer::RESAMPLE,
4811 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004812 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004813
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004814 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004815 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004816 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07004817 AudioMixer::TIMESTRETCH,
4818 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004819 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004820
Andy Hung69aed5f2014-02-25 17:24:40 -08004821 /*
4822 * Select the appropriate output buffer for the track.
4823 *
Andy Hung98ef9782014-03-04 14:46:50 -08004824 * Tracks with effects go into their own effects chain buffer
4825 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004826 *
4827 * Other tracks can use mMixerBuffer for higher precision
4828 * channel accumulation. If this buffer is enabled
4829 * (mMixerBufferEnabled true), then selected tracks will accumulate
4830 * into it.
4831 *
4832 */
4833 if (mMixerBufferEnabled
4834 && (track->mainBuffer() == mSinkBuffer
4835 || track->mainBuffer() == mMixerBuffer)) {
4836 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004837 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004838 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004839 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004840 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004841 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004842 AudioMixer::TRACK,
4843 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4844 // TODO: override track->mainBuffer()?
4845 mMixerBufferValid = true;
4846 } else {
4847 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004848 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004849 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004850 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004851 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004852 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004853 AudioMixer::TRACK,
4854 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4855 }
Eric Laurent81784c32012-11-19 14:55:58 -08004856 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004857 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004858 AudioMixer::TRACK,
4859 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4860
4861 // reset retry count
4862 track->mRetryCount = kMaxTrackRetries;
4863
4864 // If one track is ready, set the mixer ready if:
4865 // - the mixer was not ready during previous round OR
4866 // - no other track is not ready
4867 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4868 mixerStatus != MIXER_TRACKS_ENABLED) {
4869 mixerStatus = MIXER_TRACKS_READY;
4870 }
4871 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004872 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004873 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07004874 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
4875 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004876 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004877 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004878 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004879
Eric Laurent81784c32012-11-19 14:55:58 -08004880 // clear effect chain input buffer if an active track underruns to avoid sending
4881 // previous audio buffer again to effects
4882 chain = getEffectChain_l(track->sessionId());
4883 if (chain != 0) {
4884 chain->clearInputBuffer();
4885 }
4886
Andy Hungc0691382018-09-12 18:01:57 -07004887 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004888 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4889 track->isStopped() || track->isPaused()) {
4890 // We have consumed all the buffers of this track.
4891 // Remove it from the list of active tracks.
4892 // TODO: use actual buffer filling status instead of latency when available from
4893 // audio HAL
4894 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004895 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004896 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4897 if (track->isStopped()) {
4898 track->reset();
4899 }
4900 tracksToRemove->add(track);
4901 }
4902 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004903 // No buffers for this track. Give it a few chances to
4904 // fill a buffer, then remove it from active list.
4905 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07004906 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
4907 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004908 tracksToRemove->add(track);
4909 // indicate to client process that the track was disabled because of underrun;
4910 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004911 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004912 // If one track is not ready, mark the mixer also not ready if:
4913 // - the mixer was ready during previous round OR
4914 // - no other track is ready
4915 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4916 mixerStatus != MIXER_TRACKS_READY) {
4917 mixerStatus = MIXER_TRACKS_ENABLED;
4918 }
4919 }
Andy Hungc0691382018-09-12 18:01:57 -07004920 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004921 }
4922
4923 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004924
4925 }
4926
4927 // Push the new FastMixer state if necessary
4928 bool pauseAudioWatchdog = false;
4929 if (didModify) {
4930 state->mFastTracksGen++;
4931 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4932 if (kUseFastMixer == FastMixer_Dynamic &&
4933 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4934 state->mCommand = FastMixerState::COLD_IDLE;
4935 state->mColdFutexAddr = &mFastMixerFutex;
4936 state->mColdGen++;
4937 mFastMixerFutex = 0;
4938 if (kUseFastMixer == FastMixer_Dynamic) {
4939 mNormalSink = mOutputSink;
4940 }
4941 // If we go into cold idle, need to wait for acknowledgement
4942 // so that fast mixer stops doing I/O.
4943 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4944 pauseAudioWatchdog = true;
4945 }
Eric Laurent81784c32012-11-19 14:55:58 -08004946 }
4947 if (sq != NULL) {
4948 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004949 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4950 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4951 // when bringing the output sink into standby.)
4952 //
4953 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4954 //
4955 // This occurs with BT suspend when we idle the FastMixer with
4956 // active tracks, which may be added or removed.
4957 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004958 }
4959#ifdef AUDIO_WATCHDOG
4960 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4961 mAudioWatchdog->pause();
4962 }
4963#endif
4964
4965 // Now perform the deferred reset on fast tracks that have stopped
4966 while (resetMask != 0) {
4967 size_t i = __builtin_ctz(resetMask);
4968 ALOG_ASSERT(i < count);
4969 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004970 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004971 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4972 track->reset();
4973 }
4974
Andy Hung80d03d22018-04-10 10:32:11 -07004975 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4976 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4977 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4978 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4979 // See also the implementation of destroyTrack_l().
4980 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07004981 const int trackId = track->id();
4982 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
4983 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07004984 }
4985 }
4986
Eric Laurent81784c32012-11-19 14:55:58 -08004987 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004988 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004989
Eric Laurent97d547d2014-09-02 14:45:53 -07004990 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4991 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004992 }
4993
4994 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004995 // as long as there are effects we should clear the effects buffer, to avoid
4996 // passing a non-clean buffer to the effect chain
4997 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004998 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004999 // sink or mix buffer must be cleared if all tracks are connected to an
5000 // effect chain as in this case the mixer will not write to the sink or mix buffer
5001 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005002 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5003 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005004 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005005 if (mMixerBufferValid) {
5006 memset(mMixerBuffer, 0, mMixerBufferSize);
5007 // TODO: In testing, mSinkBuffer below need not be cleared because
5008 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5009 // after mixing.
5010 //
5011 // To enforce this guarantee:
5012 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5013 // (mixedTracks == 0 && fastTracks > 0))
5014 // must imply MIXER_TRACKS_READY.
5015 // Later, we may clear buffers regardless, and skip much of this logic.
5016 }
Andy Hung98ef9782014-03-04 14:46:50 -08005017 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005018 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005019 }
5020
5021 // if any fast tracks, then status is ready
5022 mMixerStatusIgnoringFastTracks = mixerStatus;
5023 if (fastTracks > 0) {
5024 mixerStatus = MIXER_TRACKS_READY;
5025 }
5026 return mixerStatus;
5027}
5028
Eric Laurentad7dd962016-09-22 12:38:37 -07005029// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005030uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005031{
5032 uint32_t trackCount = 0;
5033 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005034 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005035 trackCount++;
5036 }
5037 }
5038 return trackCount;
5039}
5040
Andy Hung1bc088a2018-02-09 15:57:31 -08005041// isTrackAllowed_l() must be called with ThreadBase::mLock held
5042bool AudioFlinger::MixerThread::isTrackAllowed_l(
5043 audio_channel_mask_t channelMask, audio_format_t format,
5044 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005045{
Andy Hung1bc088a2018-02-09 15:57:31 -08005046 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5047 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005048 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005049 // Check validity as we don't call AudioMixer::create() here.
5050 if (!AudioMixer::isValidFormat(format)) {
5051 ALOGW("%s: invalid format: %#x", __func__, format);
5052 return false;
5053 }
5054 if (!AudioMixer::isValidChannelMask(channelMask)) {
5055 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5056 return false;
5057 }
5058 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005059}
5060
Eric Laurent10351942014-05-08 18:49:52 -07005061// checkForNewParameter_l() must be called with ThreadBase::mLock held
5062bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5063 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005064{
Eric Laurent81784c32012-11-19 14:55:58 -08005065 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005066 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005067
Eric Laurent10351942014-05-08 18:49:52 -07005068 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005069
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005070 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005071
Eric Laurent10351942014-05-08 18:49:52 -07005072 AudioParameter param = AudioParameter(keyValuePair);
5073 int value;
5074 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5075 reconfig = true;
5076 }
5077 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005078 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005079 status = BAD_VALUE;
5080 } else {
5081 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005082 reconfig = true;
5083 }
Eric Laurent10351942014-05-08 18:49:52 -07005084 }
5085 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005086 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005087 status = BAD_VALUE;
5088 } else {
5089 // no need to save value, since it's constant
5090 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005091 }
Eric Laurent10351942014-05-08 18:49:52 -07005092 }
5093 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5094 // do not accept frame count changes if tracks are open as the track buffer
5095 // size depends on frame count and correct behavior would not be guaranteed
5096 // if frame count is changed after track creation
5097 if (!mTracks.isEmpty()) {
5098 status = INVALID_OPERATION;
5099 } else {
5100 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005101 }
Eric Laurent10351942014-05-08 18:49:52 -07005102 }
5103 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005104#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005105 // when changing the audio output device, call addBatteryData to notify
5106 // the change
5107 if (mOutDevice != value) {
5108 uint32_t params = 0;
5109 // check whether speaker is on
5110 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5111 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005112 }
Eric Laurent10351942014-05-08 18:49:52 -07005113
5114 audio_devices_t deviceWithoutSpeaker
5115 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5116 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005117 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005118 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5119 }
5120
5121 if (params != 0) {
5122 addBatteryData(params);
5123 }
5124 }
Eric Laurent81784c32012-11-19 14:55:58 -08005125#endif
5126
Eric Laurent10351942014-05-08 18:49:52 -07005127 // forward device change to effects that have requested to be
5128 // aware of attached audio device.
5129 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005130 a2dpDeviceChanged =
5131 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005132 mOutDevice = value;
5133 for (size_t i = 0; i < mEffectChains.size(); i++) {
5134 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005135 }
5136 }
Eric Laurent10351942014-05-08 18:49:52 -07005137 }
Eric Laurent81784c32012-11-19 14:55:58 -08005138
Eric Laurent10351942014-05-08 18:49:52 -07005139 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005140 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005141 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005142 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005143 mStandby = true;
5144 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005145 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005146 }
Eric Laurent10351942014-05-08 18:49:52 -07005147 if (status == NO_ERROR && reconfig) {
5148 readOutputParameters_l();
5149 delete mAudioMixer;
5150 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005151 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005152 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005153 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005154 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005155 track->mChannelMask,
5156 track->mFormat,
5157 track->mSessionId);
5158 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005159 "%s(): AudioMixer cannot create track(%d)"
5160 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005161 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005162 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005163 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005164 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005165 }
Eric Laurent81784c32012-11-19 14:55:58 -08005166 }
5167
Eric Laurent42537be2016-01-08 17:16:42 -08005168 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005169}
5170
5171
5172void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5173{
Eric Laurent81784c32012-11-19 14:55:58 -08005174 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005175 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005176 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005177 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005178 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005179 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005180 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005181 } else {
5182 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005183 }
Eric Laurent81784c32012-11-19 14:55:58 -08005184
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005185 if (hasFastMixer()) {
5186 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5187
5188 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5189 // while we are dumping it. It may be inconsistent, but it won't mutate!
5190 // This is a large object so we place it on the heap.
5191 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005192 const std::unique_ptr<FastMixerDumpState> copy =
5193 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005194 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005195
5196#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005197 // Similar for state queue
5198 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5199 observerCopy.dump(fd);
5200 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5201 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005202#endif
5203
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005204#ifdef AUDIO_WATCHDOG
5205 if (mAudioWatchdog != 0) {
5206 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5207 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5208 wdCopy.dump(fd);
5209 }
5210#endif
5211
5212 } else {
5213 dprintf(fd, " No FastMixer\n");
5214 }
Eric Laurent81784c32012-11-19 14:55:58 -08005215}
5216
5217uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5218{
5219 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5220}
5221
5222uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5223{
5224 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5225}
5226
5227void AudioFlinger::MixerThread::cacheParameters_l()
5228{
5229 PlaybackThread::cacheParameters_l();
5230
5231 // FIXME: Relaxed timing because of a certain device that can't meet latency
5232 // Should be reduced to 2x after the vendor fixes the driver issue
5233 // increase threshold again due to low power audio mode. The way this warning
5234 // threshold is calculated and its usefulness should be reconsidered anyway.
5235 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5236}
5237
5238// ----------------------------------------------------------------------------
5239
5240AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005241 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5242 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005243{
5244}
5245
Eric Laurentbfb1b832013-01-07 09:53:42 -08005246AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5247 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005248 ThreadBase::type_t type, bool systemReady)
5249 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005250 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005251{
5252}
5253
Eric Laurent81784c32012-11-19 14:55:58 -08005254AudioFlinger::DirectOutputThread::~DirectOutputThread()
5255{
5256}
5257
Eric Laurent5850c4c2016-11-10 13:04:31 -08005258void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005259{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005260 float left, right;
5261
5262 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5263 left = right = 0;
5264 } else {
5265 float typeVolume = mStreamTypes[track->streamType()].volume;
5266 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005267 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005268
Andy Hung10cbff12017-02-21 17:30:14 -08005269 // Get volumeshaper scaling
5270 std::pair<float /* volume */, bool /* active */>
5271 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005272 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005273 v *= vh.first;
5274 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005275
Glenn Kastenc56f3422014-03-21 17:53:17 -07005276 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5277 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5278 if (left > GAIN_FLOAT_UNITY) {
5279 left = GAIN_FLOAT_UNITY;
5280 }
5281 left *= v;
5282 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5283 if (right > GAIN_FLOAT_UNITY) {
5284 right = GAIN_FLOAT_UNITY;
5285 }
5286 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005287 }
5288
5289 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005290 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005291 if (left != mLeftVolFloat || right != mRightVolFloat) {
5292 mLeftVolFloat = left;
5293 mRightVolFloat = right;
5294
Eric Laurentbfb1b832013-01-07 09:53:42 -08005295 // Delegate volume control to effect in track effect chain if needed
5296 // only one effect chain can be present on DirectOutputThread, so if
5297 // there is one, the track is connected to it
5298 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005299 // if effect chain exists, volume is handled by it.
5300 // Convert volumes from float to 8.24
5301 uint32_t vl = (uint32_t)(left * (1 << 24));
5302 uint32_t vr = (uint32_t)(right * (1 << 24));
5303 // Direct/Offload effect chains set output volume in setVolume_l().
5304 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5305 } else {
5306 // otherwise we directly set the volume.
5307 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309 }
5310 }
5311}
5312
Phil Burk43b4dcc2015-06-09 16:53:44 -07005313void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5314{
5315 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005316 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005317
Eric Laurent0f0631e2015-07-06 18:01:25 -07005318 if (previousTrack != 0 && latestTrack != 0) {
5319 if (mType == DIRECT) {
5320 if (previousTrack.get() != latestTrack.get()) {
5321 mFlushPending = true;
5322 }
5323 } else /* mType == OFFLOAD */ {
5324 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5325 mFlushPending = true;
5326 }
5327 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005328 }
5329 PlaybackThread::onAddNewTrack_l();
5330}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005331
Eric Laurent81784c32012-11-19 14:55:58 -08005332AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5333 Vector< sp<Track> > *tracksToRemove
5334)
5335{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005336 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005337 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005338 bool doHwPause = false;
5339 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005340
5341 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005342 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005343 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005344 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005345 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005346 continue;
5347 }
5348
Eric Laurent5850c4c2016-11-10 13:04:31 -08005349 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005350#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005351 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005352#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005353 // Only consider last track started for volume and mixer state control.
5354 // In theory an older track could underrun and restart after the new one starts
5355 // but as we only care about the transition phase between two tracks on a
5356 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005357 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005358 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005359
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005360 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005361 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005362 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005363 doHwPause = true;
5364 mHwPaused = true;
5365 }
5366 tracksToRemove->add(track);
5367 } else if (track->isFlushPending()) {
5368 track->flushAck();
5369 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005370 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005371 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005372 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005373 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005374 if (last) {
5375 mLeftVolFloat = mRightVolFloat = -1.0;
5376 if (mHwPaused) {
5377 doHwResume = true;
5378 mHwPaused = false;
5379 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005380 }
5381 }
5382
Eric Laurent81784c32012-11-19 14:55:58 -08005383 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005384 // for all its buffers to be filled before processing it.
5385 // Allow draining the buffer in case the client
5386 // app does not call stop() and relies on underrun to stop:
5387 // hence the test on (track->mRetryCount > 1).
5388 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005389 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005390 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005391 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005392 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005393 minFrames = mNormalFrameCount;
5394 } else {
5395 minFrames = 1;
5396 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397
Eric Laurentab5cdba2014-06-09 17:22:27 -07005398 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5399 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005400 {
Andy Hungc0691382018-09-12 18:01:57 -07005401 ALOGVV("track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005402
5403 if (track->mFillingUpStatus == Track::FS_FILLED) {
5404 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005405 if (last) {
5406 // make sure processVolume_l() will apply new volume even if 0
5407 mLeftVolFloat = mRightVolFloat = -1.0;
5408 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005409 if (!mHwSupportsPause) {
5410 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005411 }
5412 }
5413
5414 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005415 processVolume_l(track, last);
5416 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005417 sp<Track> previousTrack = mPreviousTrack.promote();
5418 if (previousTrack != 0) {
5419 if (track != previousTrack.get()) {
5420 // Flush any data still being written from last track
5421 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005422 // Invalidate previous track to force a seek when resuming.
5423 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005424 }
5425 }
5426 mPreviousTrack = track;
5427
Eric Laurentd595b7c2013-04-03 17:27:56 -07005428 // reset retry count
5429 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005430 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005431 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005432 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005433 doHwResume = true;
5434 mHwPaused = false;
5435 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005436 }
Eric Laurent81784c32012-11-19 14:55:58 -08005437 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005438 // clear effect chain input buffer if the last active track started underruns
5439 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005440 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005441 mEffectChains[0]->clearInputBuffer();
5442 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005443 if (track->isStopping_1()) {
5444 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005445 if (last && mHwPaused) {
5446 doHwResume = true;
5447 mHwPaused = false;
5448 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005449 }
5450 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5451 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005452 // We have consumed all the buffers of this track.
5453 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005454 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005455 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005456 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5457 } else {
5458 audioHALFrames = 0;
5459 }
5460
Andy Hung818e7a32016-02-16 18:08:07 -08005461 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005462 if (mStandby || !last ||
5463 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005464 if (track->isStopping_2()) {
5465 track->mState = TrackBase::STOPPED;
5466 }
Eric Laurent81784c32012-11-19 14:55:58 -08005467 if (track->isStopped()) {
5468 track->reset();
5469 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005470 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005471 }
5472 } else {
5473 // No buffers for this track. Give it a few chances to
5474 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005475 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005476 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005477 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", track->id());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005478 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005479 // indicate to client process that the track was disabled because of underrun;
5480 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005481 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005483 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5484 "minFrames = %u, mFormat = %#x",
5485 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005486 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005487 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005488 doHwPause = true;
5489 mHwPaused = true;
5490 }
Eric Laurent81784c32012-11-19 14:55:58 -08005491 }
5492 }
5493 }
5494 }
5495
Eric Laurentd1f69b02014-12-15 14:33:13 -08005496 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005497 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005498 for (size_t i = 0; i < mTracks.size(); i++) {
5499 if (mTracks[i]->isFlushPending()) {
5500 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005501 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005502 }
5503 }
5504 }
5505
5506 // make sure the pause/flush/resume sequence is executed in the right order.
5507 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5508 // before flush and then resume HW. This can happen in case of pause/flush/resume
5509 // if resume is received before pause is executed.
5510 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005511 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005512 status_t result = mOutput->stream->pause();
5513 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005514 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005515 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005516 flushHw_l();
5517 }
5518 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005519 status_t result = mOutput->stream->resume();
5520 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005521 }
Eric Laurent81784c32012-11-19 14:55:58 -08005522 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005523 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005524
5525 return mixerStatus;
5526}
5527
5528void AudioFlinger::DirectOutputThread::threadLoop_mix()
5529{
Eric Laurent81784c32012-11-19 14:55:58 -08005530 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005531 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005532 // output audio to hardware
5533 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005534 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005535 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005536 status_t status = mActiveTrack->getNextBuffer(&buffer);
5537 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005538 // no need to pad with 0 for compressed audio
5539 if (audio_has_proportional_frames(mFormat)) {
5540 memset(curBuf, 0, frameCount * mFrameSize);
5541 }
Eric Laurent81784c32012-11-19 14:55:58 -08005542 break;
5543 }
5544 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5545 frameCount -= buffer.frameCount;
5546 curBuf += buffer.frameCount * mFrameSize;
5547 mActiveTrack->releaseBuffer(&buffer);
5548 }
Andy Hung2098f272014-02-27 14:00:06 -08005549 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005550 mSleepTimeUs = 0;
5551 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005552 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005553}
5554
5555void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5556{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005557 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005558 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005559 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005560 return;
5561 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005562 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005563 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005564 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005565 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005566 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005567 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005568 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005569 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005570 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005571 }
5572}
5573
Eric Laurentd1f69b02014-12-15 14:33:13 -08005574void AudioFlinger::DirectOutputThread::threadLoop_exit()
5575{
5576 {
5577 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005578 for (size_t i = 0; i < mTracks.size(); i++) {
5579 if (mTracks[i]->isFlushPending()) {
5580 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005581 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005582 }
5583 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005584 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005585 flushHw_l();
5586 }
5587 }
5588 PlaybackThread::threadLoop_exit();
5589}
5590
5591// must be called with thread mutex locked
5592bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5593{
5594 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005595 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005596
vivek mehta9cd7ad12016-03-17 00:18:29 -07005597 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5598 return !mStandby;
5599 }
5600
Eric Laurentd1f69b02014-12-15 14:33:13 -08005601 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5602 // after a timeout and we will enter standby then.
5603 if (mTracks.size() > 0) {
5604 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005605 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5606 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005607 }
5608
Eric Laurent5cff4032015-05-26 13:49:58 -07005609 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005610}
5611
Eric Laurent10351942014-05-08 18:49:52 -07005612// checkForNewParameter_l() must be called with ThreadBase::mLock held
5613bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5614 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005615{
5616 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005617 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005618
Eric Laurent10351942014-05-08 18:49:52 -07005619 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005620
Eric Laurent10351942014-05-08 18:49:52 -07005621 AudioParameter param = AudioParameter(keyValuePair);
5622 int value;
5623 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5624 // forward device change to effects that have requested to be
5625 // aware of attached audio device.
5626 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005627 a2dpDeviceChanged =
5628 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005629 mOutDevice = value;
5630 for (size_t i = 0; i < mEffectChains.size(); i++) {
5631 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005632 }
5633 }
Eric Laurent81784c32012-11-19 14:55:58 -08005634 }
Eric Laurent10351942014-05-08 18:49:52 -07005635 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5636 // do not accept frame count changes if tracks are open as the track buffer
5637 // size depends on frame count and correct behavior would not be garantied
5638 // if frame count is changed after track creation
5639 if (!mTracks.isEmpty()) {
5640 status = INVALID_OPERATION;
5641 } else {
5642 reconfig = true;
5643 }
5644 }
5645 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005646 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005647 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005648 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005649 mStandby = true;
5650 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005651 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005652 }
5653 if (status == NO_ERROR && reconfig) {
5654 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005655 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005656 }
5657 }
5658
Eric Laurent42537be2016-01-08 17:16:42 -08005659 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005660}
5661
5662uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5663{
5664 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005665 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005666 time = PlaybackThread::activeSleepTimeUs();
5667 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005668 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005669 }
5670 return time;
5671}
5672
5673uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5674{
5675 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005676 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005677 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5678 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005679 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005680 }
5681 return time;
5682}
5683
5684uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5685{
5686 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005687 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005688 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5689 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005690 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005691 }
5692 return time;
5693}
5694
5695void AudioFlinger::DirectOutputThread::cacheParameters_l()
5696{
5697 PlaybackThread::cacheParameters_l();
5698
5699 // use shorter standby delay as on normal output to release
5700 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005701 // no delay on outputs with HW A/V sync
5702 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005703 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005704 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005705 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005706 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005707 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005708 }
Eric Laurent81784c32012-11-19 14:55:58 -08005709}
5710
Eric Laurente659ef42014-09-29 13:06:46 -07005711void AudioFlinger::DirectOutputThread::flushHw_l()
5712{
Phil Burk062e67a2015-02-11 13:40:50 -08005713 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005714 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005715 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005716 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005717}
5718
Andy Hung10cbff12017-02-21 17:30:14 -08005719int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5720 // If a VolumeShaper is active, we must wake up periodically to update volume.
5721 const int64_t NS_PER_MS = 1000000;
5722 return mVolumeShaperActive ?
5723 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5724}
5725
Eric Laurent81784c32012-11-19 14:55:58 -08005726// ----------------------------------------------------------------------------
5727
Eric Laurentbfb1b832013-01-07 09:53:42 -08005728AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005729 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005730 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005731 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005732 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005733 mDrainSequence(0),
5734 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005735{
5736}
5737
5738AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5739{
5740}
5741
5742void AudioFlinger::AsyncCallbackThread::onFirstRef()
5743{
5744 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5745}
5746
5747bool AudioFlinger::AsyncCallbackThread::threadLoop()
5748{
5749 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005750 uint32_t writeAckSequence;
5751 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005752 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005753
5754 {
5755 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005756 while (!((mWriteAckSequence & 1) ||
5757 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005758 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005759 exitPending())) {
5760 mWaitWorkCV.wait(mLock);
5761 }
5762
Eric Laurentbfb1b832013-01-07 09:53:42 -08005763 if (exitPending()) {
5764 break;
5765 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005766 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5767 mWriteAckSequence, mDrainSequence);
5768 writeAckSequence = mWriteAckSequence;
5769 mWriteAckSequence &= ~1;
5770 drainSequence = mDrainSequence;
5771 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005772 asyncError = mAsyncError;
5773 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005774 }
5775 {
Eric Laurent4de95592013-09-26 15:28:21 -07005776 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5777 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005778 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005779 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005780 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005781 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005782 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005783 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005784 if (asyncError) {
5785 playbackThread->onAsyncError();
5786 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005787 }
5788 }
5789 }
5790 return false;
5791}
5792
5793void AudioFlinger::AsyncCallbackThread::exit()
5794{
5795 ALOGV("AsyncCallbackThread::exit");
5796 Mutex::Autolock _l(mLock);
5797 requestExit();
5798 mWaitWorkCV.broadcast();
5799}
5800
Eric Laurent3b4529e2013-09-05 18:09:19 -07005801void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005802{
5803 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005804 // bit 0 is cleared
5805 mWriteAckSequence = sequence << 1;
5806}
5807
5808void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5809{
5810 Mutex::Autolock _l(mLock);
5811 // ignore unexpected callbacks
5812 if (mWriteAckSequence & 2) {
5813 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005814 mWaitWorkCV.signal();
5815 }
5816}
5817
Eric Laurent3b4529e2013-09-05 18:09:19 -07005818void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005819{
5820 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005821 // bit 0 is cleared
5822 mDrainSequence = sequence << 1;
5823}
5824
5825void AudioFlinger::AsyncCallbackThread::resetDraining()
5826{
5827 Mutex::Autolock _l(mLock);
5828 // ignore unexpected callbacks
5829 if (mDrainSequence & 2) {
5830 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005831 mWaitWorkCV.signal();
5832 }
5833}
5834
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005835void AudioFlinger::AsyncCallbackThread::setAsyncError()
5836{
5837 Mutex::Autolock _l(mLock);
5838 mAsyncError = true;
5839 mWaitWorkCV.signal();
5840}
5841
Eric Laurentbfb1b832013-01-07 09:53:42 -08005842
5843// ----------------------------------------------------------------------------
5844AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005845 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5846 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005847 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5848 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005849{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005850 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005851 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005852 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005853}
5854
Eric Laurentbfb1b832013-01-07 09:53:42 -08005855void AudioFlinger::OffloadThread::threadLoop_exit()
5856{
5857 if (mFlushPending || mHwPaused) {
5858 // If a flush is pending or track was paused, just discard buffered data
5859 flushHw_l();
5860 } else {
5861 mMixerStatus = MIXER_DRAIN_ALL;
5862 threadLoop_drain();
5863 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005864 if (mUseAsyncWrite) {
5865 ALOG_ASSERT(mCallbackThread != 0);
5866 mCallbackThread->exit();
5867 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005868 PlaybackThread::threadLoop_exit();
5869}
5870
5871AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5872 Vector< sp<Track> > *tracksToRemove
5873)
5874{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005875 size_t count = mActiveTracks.size();
5876
5877 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005878 bool doHwPause = false;
5879 bool doHwResume = false;
5880
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005881 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005882
Eric Laurentbfb1b832013-01-07 09:53:42 -08005883 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005884 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005885 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005886#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005887 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005888#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005889 // Only consider last track started for volume and mixer state control.
5890 // In theory an older track could underrun and restart after the new one starts
5891 // but as we only care about the transition phase between two tracks on a
5892 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005893 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005894 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005895
Haynes Mathew George7844f672014-01-15 12:32:55 -08005896 if (track->isInvalid()) {
5897 ALOGW("An invalidated track shouldn't be in active list");
5898 tracksToRemove->add(track);
5899 continue;
5900 }
5901
5902 if (track->mState == TrackBase::IDLE) {
5903 ALOGW("An idle track shouldn't be in active list");
5904 continue;
5905 }
5906
Eric Laurentbfb1b832013-01-07 09:53:42 -08005907 if (track->isPausing()) {
5908 track->setPaused();
5909 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005910 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005911 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005912 mHwPaused = true;
5913 }
5914 // If we were part way through writing the mixbuffer to
5915 // the HAL we must save this until we resume
5916 // BUG - this will be wrong if a different track is made active,
5917 // in that case we want to discard the pending data in the
5918 // mixbuffer and tell the client to present it again when the
5919 // track is resumed
5920 mPausedWriteLength = mCurrentWriteLength;
5921 mPausedBytesRemaining = mBytesRemaining;
5922 mBytesRemaining = 0; // stop writing
5923 }
5924 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005925 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005926 if (track->isStopping_1()) {
5927 track->mRetryCount = kMaxTrackStopRetriesOffload;
5928 } else {
5929 track->mRetryCount = kMaxTrackRetriesOffload;
5930 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005931 track->flushAck();
5932 if (last) {
5933 mFlushPending = true;
5934 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005935 } else if (track->isResumePending()){
5936 track->resumeAck();
5937 if (last) {
5938 if (mPausedBytesRemaining) {
5939 // Need to continue write that was interrupted
5940 mCurrentWriteLength = mPausedWriteLength;
5941 mBytesRemaining = mPausedBytesRemaining;
5942 mPausedBytesRemaining = 0;
5943 }
5944 if (mHwPaused) {
5945 doHwResume = true;
5946 mHwPaused = false;
5947 // threadLoop_mix() will handle the case that we need to
5948 // resume an interrupted write
5949 }
5950 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005951 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005952
Eric Laurent3df841a2016-07-15 15:15:40 -07005953 mLeftVolFloat = mRightVolFloat = -1.0;
5954
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005955 // Do not handle new data in this iteration even if track->framesReady()
5956 mixerStatus = MIXER_TRACKS_ENABLED;
5957 }
5958 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005959 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07005960 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005961 if (track->mFillingUpStatus == Track::FS_FILLED) {
5962 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005963 if (last) {
5964 // make sure processVolume_l() will apply new volume even if 0
5965 mLeftVolFloat = mRightVolFloat = -1.0;
5966 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005967 }
5968
5969 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005970 sp<Track> previousTrack = mPreviousTrack.promote();
5971 if (previousTrack != 0) {
5972 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005973 // Flush any data still being written from last track
5974 mBytesRemaining = 0;
5975 if (mPausedBytesRemaining) {
5976 // Last track was paused so we also need to flush saved
5977 // mixbuffer state and invalidate track so that it will
5978 // re-submit that unwritten data when it is next resumed
5979 mPausedBytesRemaining = 0;
5980 // Invalidate is a bit drastic - would be more efficient
5981 // to have a flag to tell client that some of the
5982 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005983 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005984 }
5985 // flush data already sent to the DSP if changing audio session as audio
5986 // comes from a different source. Also invalidate previous track to force a
5987 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005988 if (previousTrack->sessionId() != track->sessionId()) {
5989 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005990 }
5991 }
5992 }
5993 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005994 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005995 if (track->isStopping_1()) {
5996 track->mRetryCount = kMaxTrackStopRetriesOffload;
5997 } else {
5998 track->mRetryCount = kMaxTrackRetriesOffload;
5999 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006000 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006001 mixerStatus = MIXER_TRACKS_READY;
6002 }
6003 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006004 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006005 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006006 if (--(track->mRetryCount) <= 0) {
6007 // Hardware buffer can hold a large amount of audio so we must
6008 // wait for all current track's data to drain before we say
6009 // that the track is stopped.
6010 if (mBytesRemaining == 0) {
6011 // Only start draining when all data in mixbuffer
6012 // has been written
6013 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6014 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6015 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6016 if (last && !mStandby) {
6017 // do not modify drain sequence if we are already draining. This happens
6018 // when resuming from pause after drain.
6019 if ((mDrainSequence & 1) == 0) {
6020 mSleepTimeUs = 0;
6021 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6022 mixerStatus = MIXER_DRAIN_TRACK;
6023 mDrainSequence += 2;
6024 }
6025 if (mHwPaused) {
6026 // It is possible to move from PAUSED to STOPPING_1 without
6027 // a resume so we must ensure hardware is running
6028 doHwResume = true;
6029 mHwPaused = false;
6030 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006031 }
6032 }
Eric Laurente93cc032016-05-05 10:15:10 -07006033 } else if (last) {
6034 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6035 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006036 }
6037 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006038 // Drain has completed or we are in standby, signal presentation complete
6039 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006040 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006041 uint32_t latency = 0;
6042 status_t result = mOutput->stream->getLatency(&latency);
6043 ALOGE_IF(result != OK,
6044 "Error when retrieving output stream latency: %d", result);
6045 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006046 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006047 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006048 track->presentationComplete(framesWritten, audioHALFrames);
6049 track->reset();
6050 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006051 // DIRECT and OFFLOADED stop resets frame counts.
6052 if (!mUseAsyncWrite) {
6053 // If we don't get explicit drain notification we must
6054 // register discontinuity regardless of whether this is
6055 // the previous (!last) or the upcoming (last) track
6056 // to avoid skipping the discontinuity.
6057 mTimestampVerifier.discontinuity();
6058 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006059 }
6060 } else {
6061 // No buffers for this track. Give it a few chances to
6062 // fill a buffer, then remove it from active list.
6063 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006064 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006065 uint64_t position = 0;
6066 struct timespec unused;
6067 // The running check restarts the retry counter at least once.
6068 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6069 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6070 running = true;
6071 mOffloadUnderrunPosition = position;
6072 }
6073 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006074 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6075 (long long)position, (long long)mOffloadUnderrunPosition);
6076 }
6077 if (running) { // still running, give us more time.
6078 track->mRetryCount = kMaxTrackRetriesOffload;
6079 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006080 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6081 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006082 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006083 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006084 // it will then automatically call start() when data is available
6085 track->disable();
6086 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006087 } else if (last){
6088 mixerStatus = MIXER_TRACKS_ENABLED;
6089 }
6090 }
6091 }
6092 // compute volume for this track
6093 processVolume_l(track, last);
6094 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006095
Eric Laurentea0fade2013-10-04 16:23:48 -07006096 // make sure the pause/flush/resume sequence is executed in the right order.
6097 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6098 // before flush and then resume HW. This can happen in case of pause/flush/resume
6099 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006100 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006101 status_t result = mOutput->stream->pause();
6102 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006103 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006104 if (mFlushPending) {
6105 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006106 }
Eric Laurentfd477972013-10-25 18:10:40 -07006107 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006108 status_t result = mOutput->stream->resume();
6109 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006110 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006111
Eric Laurentbfb1b832013-01-07 09:53:42 -08006112 // remove all the tracks that need to be...
6113 removeTracks_l(*tracksToRemove);
6114
6115 return mixerStatus;
6116}
6117
Eric Laurentbfb1b832013-01-07 09:53:42 -08006118// must be called with thread mutex locked
6119bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6120{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006121 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6122 mWriteAckSequence, mDrainSequence);
6123 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006124 return true;
6125 }
6126 return false;
6127}
6128
Eric Laurentbfb1b832013-01-07 09:53:42 -08006129bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6130{
6131 Mutex::Autolock _l(mLock);
6132 return waitingAsyncCallback_l();
6133}
6134
6135void AudioFlinger::OffloadThread::flushHw_l()
6136{
Eric Laurente659ef42014-09-29 13:06:46 -07006137 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006138 // Flush anything still waiting in the mixbuffer
6139 mCurrentWriteLength = 0;
6140 mBytesRemaining = 0;
6141 mPausedWriteLength = 0;
6142 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006143 // reset bytes written count to reflect that DSP buffers are empty after flush.
6144 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006145 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006146
Eric Laurentbfb1b832013-01-07 09:53:42 -08006147 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006148 // discard any pending drain or write ack by incrementing sequence
6149 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6150 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006151 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006152 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6153 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006154 }
6155}
6156
Haynes Mathew George05317d22016-05-03 16:34:26 -07006157void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6158{
6159 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006160 if (PlaybackThread::invalidateTracks_l(streamType)) {
6161 mFlushPending = true;
6162 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006163}
6164
Eric Laurentbfb1b832013-01-07 09:53:42 -08006165// ----------------------------------------------------------------------------
6166
Eric Laurent81784c32012-11-19 14:55:58 -08006167AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006168 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006169 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006170 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006171 mWaitTimeMs(UINT_MAX)
6172{
6173 addOutputTrack(mainThread);
6174}
6175
6176AudioFlinger::DuplicatingThread::~DuplicatingThread()
6177{
6178 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6179 mOutputTracks[i]->destroy();
6180 }
6181}
6182
6183void AudioFlinger::DuplicatingThread::threadLoop_mix()
6184{
6185 // mix buffers...
6186 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006187 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006188 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006189 if (mMixerBufferValid) {
6190 memset(mMixerBuffer, 0, mMixerBufferSize);
6191 } else {
6192 memset(mSinkBuffer, 0, mSinkBufferSize);
6193 }
Eric Laurent81784c32012-11-19 14:55:58 -08006194 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006195 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006196 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006197 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006198 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006199}
6200
6201void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6202{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006203 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006204 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006205 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006206 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006207 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006208 }
6209 } else if (mBytesWritten != 0) {
6210 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6211 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006212 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006213 } else {
6214 // flush remaining overflow buffers in output tracks
6215 writeFrames = 0;
6216 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006217 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006218 }
6219}
6220
Eric Laurentbfb1b832013-01-07 09:53:42 -08006221ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006222{
6223 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006224 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6225
6226 // Consider the first OutputTrack for timestamp and frame counting.
6227
6228 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6229 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6230 // we always claim success.
6231 if (i == 0) {
6232 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6233 ALOGD_IF(correction != 0 && writeFrames != 0,
6234 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6235 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6236 mFramesWritten -= correction;
6237 }
6238
6239 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006240 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006241 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006242 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006243}
6244
6245void AudioFlinger::DuplicatingThread::threadLoop_standby()
6246{
6247 // DuplicatingThread implements standby by stopping all tracks
6248 for (size_t i = 0; i < outputTracks.size(); i++) {
6249 outputTracks[i]->stop();
6250 }
6251}
6252
Andy Hung1bc088a2018-02-09 15:57:31 -08006253void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6254{
6255 MixerThread::dumpInternals(fd, args);
6256
6257 std::stringstream ss;
6258 const size_t numTracks = mOutputTracks.size();
6259 ss << " " << numTracks << " OutputTracks";
6260 if (numTracks > 0) {
6261 ss << ":";
6262 for (const auto &track : mOutputTracks) {
6263 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006264 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006265 if (thread.get() != nullptr) {
6266 ss << thread.get() << ", " << thread->id();
6267 } else {
6268 ss << "null";
6269 }
6270 ss << ")";
6271 }
6272 }
6273 ss << "\n";
6274 std::string result = ss.str();
6275 write(fd, result.c_str(), result.size());
6276}
6277
Eric Laurent81784c32012-11-19 14:55:58 -08006278void AudioFlinger::DuplicatingThread::saveOutputTracks()
6279{
6280 outputTracks = mOutputTracks;
6281}
6282
6283void AudioFlinger::DuplicatingThread::clearOutputTracks()
6284{
6285 outputTracks.clear();
6286}
6287
6288void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6289{
6290 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006291 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6292 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6293 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6294 const size_t frameCount =
6295 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6296 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6297 // from different OutputTracks and their associated MixerThreads (e.g. one may
6298 // nearly empty and the other may be dropping data).
6299
6300 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006301 this,
6302 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006303 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006304 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006305 frameCount,
6306 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006307 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6308 if (status != NO_ERROR) {
6309 ALOGE("addOutputTrack() initCheck failed %d", status);
6310 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006311 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006312 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6313 mOutputTracks.add(outputTrack);
6314 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6315 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006316}
6317
6318void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6319{
6320 Mutex::Autolock _l(mLock);
6321 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6322 if (mOutputTracks[i]->thread() == thread) {
6323 mOutputTracks[i]->destroy();
6324 mOutputTracks.removeAt(i);
6325 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006326 if (thread->getOutput() == mOutput) {
6327 mOutput = NULL;
6328 }
Eric Laurent81784c32012-11-19 14:55:58 -08006329 return;
6330 }
6331 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006332 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006333}
6334
6335// caller must hold mLock
6336void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6337{
6338 mWaitTimeMs = UINT_MAX;
6339 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6340 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6341 if (strong != 0) {
6342 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6343 if (waitTimeMs < mWaitTimeMs) {
6344 mWaitTimeMs = waitTimeMs;
6345 }
6346 }
6347 }
6348}
6349
6350
6351bool AudioFlinger::DuplicatingThread::outputsReady(
6352 const SortedVector< sp<OutputTrack> > &outputTracks)
6353{
6354 for (size_t i = 0; i < outputTracks.size(); i++) {
6355 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6356 if (thread == 0) {
6357 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6358 outputTracks[i].get());
6359 return false;
6360 }
6361 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6362 // see note at standby() declaration
6363 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6364 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6365 thread.get());
6366 return false;
6367 }
6368 }
6369 return true;
6370}
6371
Kevin Rocard12381092018-04-11 09:19:59 -07006372void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6373 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006374{
Kevin Rocard12381092018-04-11 09:19:59 -07006375 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6376 outputTrack->setMetadatas(metadata.tracks);
6377 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006378}
6379
Eric Laurent81784c32012-11-19 14:55:58 -08006380uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6381{
6382 return (mWaitTimeMs * 1000) / 2;
6383}
6384
6385void AudioFlinger::DuplicatingThread::cacheParameters_l()
6386{
6387 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6388 updateWaitTime_l();
6389
6390 MixerThread::cacheParameters_l();
6391}
6392
Eric Laurent6acd1d42017-01-04 14:23:29 -08006393
Eric Laurent81784c32012-11-19 14:55:58 -08006394// ----------------------------------------------------------------------------
6395// Record
6396// ----------------------------------------------------------------------------
6397
6398AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6399 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006400 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006401 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006402 audio_devices_t inDevice,
6403 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006404 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006405 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006406 mInput(input),
6407 mActiveTracks(&this->mLocalLog),
6408 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006409 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006410 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006411 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6412 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006413 // mFastCapture below
6414 , mFastCaptureFutex(0)
6415 // mInputSource
6416 // mPipeSink
6417 // mPipeSource
6418 , mPipeFramesP2(0)
6419 // mPipeMemory
6420 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006421 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006422 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006423{
Glenn Kastend7dca052015-03-05 16:05:54 -08006424 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6425 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006426
Andy Hungc8fddf32018-08-08 18:32:37 -07006427 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6428 mIsMsdDevice = strcmp(
6429 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6430 }
6431
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006432 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006433
Andy Hungc8fddf32018-08-08 18:32:37 -07006434 // TODO: We may also match on address as well as device type for
6435 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
6436 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
6437 "audio.timestamp.corrected_input_devices",
6438 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6439 : AUDIO_DEVICE_NONE));
6440
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006441 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006442 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006443 size_t numCounterOffers = 0;
6444 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006445#if !LOG_NDEBUG
6446 ssize_t index =
6447#else
6448 (void)
6449#endif
6450 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006451 ALOG_ASSERT(index == 0);
6452
6453 // initialize fast capture depending on configuration
6454 bool initFastCapture;
6455 switch (kUseFastCapture) {
6456 case FastCapture_Never:
6457 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006458 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006459 break;
6460 case FastCapture_Always:
6461 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006462 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006463 break;
6464 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006465 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006466 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6467 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6468 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006469 break;
6470 // case FastCapture_Dynamic:
6471 }
6472
6473 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006474 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006475 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006476 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6477 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006478 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006479 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006480 const sp<MemoryDealer> roHeap(readOnlyHeap());
6481 sp<IMemory> pipeMemory;
6482 if ((roHeap == 0) ||
6483 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006484 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6485 ALOGE("not enough memory for pipe buffer size=%zu; "
6486 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6487 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6488 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006489 goto failed;
6490 }
6491 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6492 memset(pipeBuffer, 0, pipeSize);
6493 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6494 const NBAIO_Format offers[1] = {format};
6495 size_t numCounterOffers = 0;
6496 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6497 ALOG_ASSERT(index == 0);
6498 mPipeSink = pipe;
6499 PipeReader *pipeReader = new PipeReader(*pipe);
6500 numCounterOffers = 0;
6501 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6502 ALOG_ASSERT(index == 0);
6503 mPipeSource = pipeReader;
6504 mPipeFramesP2 = pipeFramesP2;
6505 mPipeMemory = pipeMemory;
6506
6507 // create fast capture
6508 mFastCapture = new FastCapture();
6509 FastCaptureStateQueue *sq = mFastCapture->sq();
6510#ifdef STATE_QUEUE_DUMP
6511 // FIXME
6512#endif
6513 FastCaptureState *state = sq->begin();
6514 state->mCblk = NULL;
6515 state->mInputSource = mInputSource.get();
6516 state->mInputSourceGen++;
6517 state->mPipeSink = pipe;
6518 state->mPipeSinkGen++;
6519 state->mFrameCount = mFrameCount;
6520 state->mCommand = FastCaptureState::COLD_IDLE;
6521 // already done in constructor initialization list
6522 //mFastCaptureFutex = 0;
6523 state->mColdFutexAddr = &mFastCaptureFutex;
6524 state->mColdGen++;
6525 state->mDumpState = &mFastCaptureDumpState;
6526#ifdef TEE_SINK
6527 // FIXME
6528#endif
6529 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6530 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6531 sq->end();
6532 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6533
6534 // start the fast capture
6535 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6536 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006537 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006538 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006539#ifdef AUDIO_WATCHDOG
6540 // FIXME
6541#endif
6542
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006543 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006544 }
Andy Hung8946a282018-04-19 20:04:56 -07006545#ifdef TEE_SINK
6546 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6547 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6548#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006549failed: ;
6550
6551 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006552}
6553
Eric Laurent81784c32012-11-19 14:55:58 -08006554AudioFlinger::RecordThread::~RecordThread()
6555{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006556 if (mFastCapture != 0) {
6557 FastCaptureStateQueue *sq = mFastCapture->sq();
6558 FastCaptureState *state = sq->begin();
6559 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6560 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6561 if (old == -1) {
6562 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6563 }
6564 }
6565 state->mCommand = FastCaptureState::EXIT;
6566 sq->end();
6567 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6568 mFastCapture->join();
6569 mFastCapture.clear();
6570 }
6571 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006572 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006573 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006574}
6575
6576void AudioFlinger::RecordThread::onFirstRef()
6577{
Glenn Kastend7dca052015-03-05 16:05:54 -08006578 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006579}
6580
Eric Laurent555530a2017-02-07 18:17:24 -08006581void AudioFlinger::RecordThread::preExit()
6582{
6583 ALOGV(" preExit()");
6584 Mutex::Autolock _l(mLock);
6585 for (size_t i = 0; i < mTracks.size(); i++) {
6586 sp<RecordTrack> track = mTracks[i];
6587 track->invalidate();
6588 }
6589 mActiveTracks.clear();
6590 mStartStopCond.broadcast();
6591}
6592
Eric Laurent81784c32012-11-19 14:55:58 -08006593bool AudioFlinger::RecordThread::threadLoop()
6594{
Eric Laurent81784c32012-11-19 14:55:58 -08006595 nsecs_t lastWarning = 0;
6596
6597 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006598
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006599reacquire_wakelock:
6600 sp<RecordTrack> activeTrack;
6601 {
6602 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006603 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006604 }
6605
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006606 // used to request a deferred sleep, to be executed later while mutex is unlocked
6607 uint32_t sleepUs = 0;
6608
6609 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006610 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006611 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006612
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006613 // activeTracks accumulates a copy of a subset of mActiveTracks
6614 Vector< sp<RecordTrack> > activeTracks;
6615
Glenn Kasten735f45f2014-08-18 15:51:59 -07006616 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006617 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006618
Glenn Kasten735f45f2014-08-18 15:51:59 -07006619 // reference to a fast track which is about to be removed
6620 sp<RecordTrack> fastTrackToRemove;
6621
Eric Laurent81784c32012-11-19 14:55:58 -08006622 { // scope for mLock
6623 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006624
Eric Laurent021cf962014-05-13 10:18:14 -07006625 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006626
Eric Laurent000a4192014-01-29 15:17:32 -08006627 // check exitPending here because checkForNewParameters_l() and
6628 // checkForNewParameters_l() can temporarily release mLock
6629 if (exitPending()) {
6630 break;
6631 }
6632
Eric Laurent5c25d562016-07-13 17:17:45 -07006633 // sleep with mutex unlocked
6634 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006635 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006636 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6637 ATRACE_END();
6638 sleepUs = 0;
6639 continue;
6640 }
6641
Glenn Kasten2b806402013-11-20 16:37:38 -08006642 // if no active track(s), then standby and release wakelock
6643 size_t size = mActiveTracks.size();
6644 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006645 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006646 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006647 releaseWakeLock_l();
6648 ALOGV("RecordThread: loop stopping");
6649 // go to sleep
6650 mWaitWorkCV.wait(mLock);
6651 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006652 goto reacquire_wakelock;
6653 }
6654
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006655 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006656 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006657 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006658
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006659 activeTrack = mActiveTracks[i];
6660 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006661 if (activeTrack->isFastTrack()) {
6662 ALOG_ASSERT(fastTrackToRemove == 0);
6663 fastTrackToRemove = activeTrack;
6664 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006665 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006666 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006667 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006668 continue;
6669 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006670
6671 TrackBase::track_state activeTrackState = activeTrack->mState;
6672 switch (activeTrackState) {
6673
6674 case TrackBase::PAUSING:
6675 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006676 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006677 doBroadcast = true;
6678 size--;
6679 continue;
6680
6681 case TrackBase::STARTING_1:
6682 sleepUs = 10000;
6683 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006684 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006685 continue;
6686
6687 case TrackBase::STARTING_2:
6688 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006689 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006690 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006691 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006692 break;
6693
6694 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006695 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006696 break;
6697
Andy Hungce685402018-10-05 17:23:27 -07006698 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6699 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6700 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006701 default:
Andy Hungce685402018-10-05 17:23:27 -07006702 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6703 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006704 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006705
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006706 activeTracks.add(activeTrack);
6707 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006708
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006709 if (activeTrack->isFastTrack()) {
6710 ALOG_ASSERT(!mFastTrackAvail);
6711 ALOG_ASSERT(fastTrack == 0);
6712 fastTrack = activeTrack;
6713 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006714 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006715
Andy Hungdae27702016-10-31 14:01:16 -07006716 mActiveTracks.updatePowerState(this);
6717
Kevin Rocard069c2712018-03-29 19:09:14 -07006718 updateMetadata_l();
6719
Eric Laurent5c25d562016-07-13 17:17:45 -07006720 if (allStopped) {
6721 standbyIfNotAlreadyInStandby();
6722 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006723 if (doBroadcast) {
6724 mStartStopCond.broadcast();
6725 }
6726
6727 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006728 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006729 if (sleepUs == 0) {
6730 sleepUs = kRecordThreadSleepUs;
6731 }
6732 continue;
6733 }
6734 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006735
Eric Laurent81784c32012-11-19 14:55:58 -08006736 lockEffectChains_l(effectChains);
6737 }
6738
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006739 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006740
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006741 size_t size = effectChains.size();
6742 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006743 // thread mutex is not locked, but effect chain is locked
6744 effectChains[i]->process_l();
6745 }
6746
Glenn Kasten735f45f2014-08-18 15:51:59 -07006747 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006748 if (mFastCapture != 0) {
6749 FastCaptureStateQueue *sq = mFastCapture->sq();
6750 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006751 bool didModify = false;
6752 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006753 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6754 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6755 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6756 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6757 if (old == -1) {
6758 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6759 }
6760 }
6761 state->mCommand = FastCaptureState::READ_WRITE;
6762#if 0 // FIXME
6763 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006764 FastThreadDumpState::kSamplingNforLowRamDevice :
6765 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006766#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006767 didModify = true;
6768 }
6769 audio_track_cblk_t *cblkOld = state->mCblk;
6770 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6771 if (cblkNew != cblkOld) {
6772 state->mCblk = cblkNew;
6773 // block until acked if removing a fast track
6774 if (cblkOld != NULL) {
6775 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6776 }
6777 didModify = true;
6778 }
jiabin01c8f562018-07-19 17:47:28 -07006779 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
6780 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
6781 if (state->mFastPatchRecordBufferProvider != abp) {
6782 state->mFastPatchRecordBufferProvider = abp;
6783 state->mFastPatchRecordFormat = fastTrack == 0 ?
6784 AUDIO_FORMAT_INVALID : fastTrack->format();
6785 didModify = true;
6786 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07006787 sq->end(didModify);
6788 if (didModify) {
6789 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006790#if 0
6791 if (kUseFastCapture == FastCapture_Dynamic) {
6792 mNormalSource = mPipeSource;
6793 }
6794#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006795 }
6796 }
6797
Glenn Kasten735f45f2014-08-18 15:51:59 -07006798 // now run the fast track destructor with thread mutex unlocked
6799 fastTrackToRemove.clear();
6800
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006801 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6802 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6803 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6804 // If destination is non-contiguous, first read past the nominal end of buffer, then
6805 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006806
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006807 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006808 ssize_t framesRead;
6809
6810 // If an NBAIO source is present, use it to read the normal capture's data
6811 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07006812 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006813
6814 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6815 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6816 // we immediately retry the read() to get data and prevent another overflow.
6817 for (int retries = 0; retries <= 2; ++retries) {
6818 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6819 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6820 framesToRead);
6821 if (framesRead != OVERRUN) break;
6822 }
6823
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006824 const ssize_t availableToRead = mPipeSource->availableToRead();
6825 if (availableToRead >= 0) {
6826 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6827 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6828 "more frames to read than fifo size, %zd > %zu",
6829 availableToRead, mPipeFramesP2);
6830 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6831 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6832 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6833 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006834 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6835 }
6836 if (framesRead < 0) {
6837 status_t status = (status_t) framesRead;
6838 switch (status) {
6839 case OVERRUN:
6840 ALOGW("overrun on read from pipe");
6841 framesRead = 0;
6842 break;
6843 case NEGOTIATE:
6844 ALOGE("re-negotiation is needed");
6845 framesRead = -1; // Will cause an attempt to recover.
6846 break;
6847 default:
6848 ALOGE("unknown error %d on read from pipe", status);
6849 break;
6850 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006851 }
6852 // otherwise use the HAL / AudioStreamIn directly
6853 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006854 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006855 size_t bytesRead;
6856 status_t result = mInput->stream->read(
6857 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006858 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006859 if (result < 0) {
6860 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006861 } else {
6862 framesRead = bytesRead / mFrameSize;
6863 }
6864 }
6865
Andy Hung3f0c9022016-01-15 17:49:46 -08006866 // Update server timestamp with server stats
6867 // systemTime() is optional if the hardware supports timestamps.
6868 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6869 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6870
6871 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006872 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006873 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006874 if (mStandby) {
6875 mTimestampVerifier.discontinuity();
Andy Hungc8fddf32018-08-08 18:32:37 -07006876 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR
6877 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
6878
6879 mTimestampVerifier.add(position, time, mSampleRate);
6880
6881 // Correct timestamps
6882 if (isTimestampCorrectionEnabled()) {
6883 ALOGV("TS_BEFORE: %d %lld %lld",
6884 id(), (long long)time, (long long)position);
6885 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
6886 position = correctedTimestamp.mFrames;
6887 time = correctedTimestamp.mTimeNs;
6888 ALOGV("TS_AFTER: %d %lld %lld",
6889 id(), (long long)time, (long long)position);
6890 }
6891
Andy Hung3f0c9022016-01-15 17:49:46 -08006892 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6893 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6894 // Note: In general record buffers should tend to be empty in
6895 // a properly running pipeline.
6896 //
6897 // Also, it is not advantageous to call get_presentation_position during the read
6898 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006899 } else {
6900 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08006901 }
6902 }
6903 // Use this to track timestamp information
6904 // ALOGD("%s", mTimestamp.toString().c_str());
6905
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006906 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006907 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006908 // Force input into standby so that it tries to recover at next read attempt
6909 inputStandBy();
6910 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006911 }
6912 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006913 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006914 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006915 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07006916 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006917
Andy Hung8946a282018-04-19 20:04:56 -07006918#ifdef TEE_SINK
6919 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6920#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006921 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006922 {
6923 size_t part1 = mRsmpInFramesP2 - rear;
6924 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006925 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006926 (framesRead - part1) * mFrameSize);
6927 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006928 }
6929 rear = mRsmpInRear += framesRead;
6930
6931 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006932
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006933 // loop over each active track
6934 for (size_t i = 0; i < size; i++) {
6935 activeTrack = activeTracks[i];
6936
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006937 // skip fast tracks, as those are handled directly by FastCapture
6938 if (activeTrack->isFastTrack()) {
6939 continue;
6940 }
6941
Andy Hung73c02e42015-03-29 01:13:58 -07006942 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006943 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6944
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006945 enum {
6946 OVERRUN_UNKNOWN,
6947 OVERRUN_TRUE,
6948 OVERRUN_FALSE
6949 } overrun = OVERRUN_UNKNOWN;
6950
6951 // loop over getNextBuffer to handle circular sink
6952 for (;;) {
6953
6954 activeTrack->mSink.frameCount = ~0;
6955 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6956 size_t framesOut = activeTrack->mSink.frameCount;
6957 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6958
Andy Hung73c02e42015-03-29 01:13:58 -07006959 // check available frames and handle overrun conditions
6960 // if the record track isn't draining fast enough.
6961 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006962 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006963 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6964 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006965 overrun = OVERRUN_TRUE;
6966 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006967 if (framesOut == 0 || framesIn == 0) {
6968 break;
6969 }
6970
Andy Hung6770c6f2015-04-07 13:43:36 -07006971 // Don't allow framesOut to be larger than what is possible with resampling
6972 // from framesIn.
6973 // This isn't strictly necessary but helps limit buffer resizing in
6974 // RecordBufferConverter. TODO: remove when no longer needed.
6975 framesOut = min(framesOut,
6976 destinationFramesPossible(
6977 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006978
6979 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10006980 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006981 // straight from RecordThread buffer to RecordTrack buffer.
6982 AudioBufferProvider::Buffer buffer;
6983 buffer.frameCount = framesOut;
6984 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
6985 if (status == OK && buffer.frameCount != 0) {
6986 ALOGV_IF(buffer.frameCount != framesOut,
6987 "%s() read less than expected (%zu vs %zu)",
6988 __func__, buffer.frameCount, framesOut);
6989 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10006990 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006991 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
6992 } else {
6993 framesOut = 0;
6994 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
6995 __func__, status, buffer.frameCount);
6996 }
6997 } else {
6998 // process frames from the RecordThread buffer provider to the RecordTrack
6999 // buffer
7000 framesOut = activeTrack->mRecordBufferConverter->convert(
7001 activeTrack->mSink.raw,
7002 activeTrack->mResamplerBufferProvider,
7003 framesOut);
7004 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007005
7006 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7007 overrun = OVERRUN_FALSE;
7008 }
7009
7010 if (activeTrack->mFramesToDrop == 0) {
7011 if (framesOut > 0) {
7012 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007013 // Sanitize before releasing if the track has no access to the source data
7014 // An idle UID receives silence from non virtual devices until active
7015 if (activeTrack->isSilenced()) {
7016 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
7017 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007018 activeTrack->releaseBuffer(&activeTrack->mSink);
7019 }
7020 } else {
7021 // FIXME could do a partial drop of framesOut
7022 if (activeTrack->mFramesToDrop > 0) {
7023 activeTrack->mFramesToDrop -= framesOut;
7024 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007025 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007026 }
7027 } else {
7028 activeTrack->mFramesToDrop += framesOut;
7029 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7030 activeTrack->mSyncStartEvent->isCancelled()) {
7031 ALOGW("Synced record %s, session %d, trigger session %d",
7032 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7033 activeTrack->sessionId(),
7034 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007035 activeTrack->mSyncStartEvent->triggerSession() :
7036 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007037 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007038 }
7039 }
7040 }
7041
7042 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007043 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007044 }
7045 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007046
7047 switch (overrun) {
7048 case OVERRUN_TRUE:
7049 // client isn't retrieving buffers fast enough
7050 if (!activeTrack->setOverflow()) {
7051 nsecs_t now = systemTime();
7052 // FIXME should lastWarning per track?
7053 if ((now - lastWarning) > kWarningThrottleNs) {
7054 ALOGW("RecordThread: buffer overflow");
7055 lastWarning = now;
7056 }
7057 }
7058 break;
7059 case OVERRUN_FALSE:
7060 activeTrack->clearOverflow();
7061 break;
7062 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007063 break;
7064 }
7065
Andy Hung3f0c9022016-01-15 17:49:46 -08007066 // update frame information and push timestamp out
7067 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007068 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007069 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7070 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007071 }
7072
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007073unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007074 // enable changes in effect chain
7075 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007076 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08007077 }
7078
Glenn Kasten93e471f2013-08-19 08:40:07 -07007079 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007080
7081 {
7082 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007083 for (size_t i = 0; i < mTracks.size(); i++) {
7084 sp<RecordTrack> track = mTracks[i];
7085 track->invalidate();
7086 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007087 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007088 mStartStopCond.broadcast();
7089 }
7090
7091 releaseWakeLock();
7092
7093 ALOGV("RecordThread %p exiting", this);
7094 return false;
7095}
7096
Glenn Kasten93e471f2013-08-19 08:40:07 -07007097void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007098{
7099 if (!mStandby) {
7100 inputStandBy();
7101 mStandby = true;
7102 }
7103}
7104
7105void AudioFlinger::RecordThread::inputStandBy()
7106{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007107 // Idle the fast capture if it's currently running
7108 if (mFastCapture != 0) {
7109 FastCaptureStateQueue *sq = mFastCapture->sq();
7110 FastCaptureState *state = sq->begin();
7111 if (!(state->mCommand & FastCaptureState::IDLE)) {
7112 state->mCommand = FastCaptureState::COLD_IDLE;
7113 state->mColdFutexAddr = &mFastCaptureFutex;
7114 state->mColdGen++;
7115 mFastCaptureFutex = 0;
7116 sq->end();
7117 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7118 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7119#if 0
7120 if (kUseFastCapture == FastCapture_Dynamic) {
7121 // FIXME
7122 }
7123#endif
7124#ifdef AUDIO_WATCHDOG
7125 // FIXME
7126#endif
7127 } else {
7128 sq->end(false /*didModify*/);
7129 }
7130 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007131 status_t result = mInput->stream->standby();
7132 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007133
7134 // If going into standby, flush the pipe source.
7135 if (mPipeSource.get() != nullptr) {
7136 const ssize_t flushed = mPipeSource->flush();
7137 if (flushed > 0) {
7138 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7139 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7140 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7141 }
7142 }
Eric Laurent81784c32012-11-19 14:55:58 -08007143}
7144
Glenn Kasten05997e22014-03-13 15:08:33 -07007145// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007146sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007147 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007148 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007149 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007150 audio_format_t format,
7151 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007152 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007153 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007154 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007155 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007156 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007157 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007158 status_t *status,
7159 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007160{
Glenn Kasten74935e42013-12-19 08:56:45 -08007161 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007162 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007163 sp<RecordTrack> track;
7164 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007165 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007166 audio_input_flags_t requestedFlags = *flags;
7167 uint32_t sampleRate;
7168
7169 lStatus = initCheck();
7170 if (lStatus != NO_ERROR) {
7171 ALOGE("createRecordTrack_l() audio driver not initialized");
7172 goto Exit;
7173 }
7174
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007175 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7176 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7177 lStatus = BAD_VALUE;
7178 goto Exit;
7179 }
7180
Eric Laurentf14db3c2017-12-08 14:20:36 -08007181 if (*pSampleRate == 0) {
7182 *pSampleRate = mSampleRate;
7183 }
7184 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007185
7186 // special case for FAST flag considered OK if fast capture is present
7187 if (hasFastCapture()) {
7188 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7189 }
7190
Eric Laurentf14db3c2017-12-08 14:20:36 -08007191 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007192 if ((*flags & inputFlags) != *flags) {
7193 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7194 " input flags (%08x)",
7195 *flags, inputFlags);
7196 *flags = (audio_input_flags_t)(*flags & inputFlags);
7197 }
Eric Laurent81784c32012-11-19 14:55:58 -08007198
Glenn Kasten90e58b12013-07-31 16:16:02 -07007199 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007200 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007201 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007202 // we formerly checked for a callback handler (non-0 tid),
7203 // but that is no longer required for TRANSFER_OBTAIN mode
7204 //
Glenn Kasten74105912014-07-03 12:28:53 -07007205 // frame count is not specified, or is exactly the pipe depth
7206 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007207 // PCM data
7208 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007209 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007210 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007211 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007212 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007213 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007214 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007215 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007216 hasFastCapture() &&
7217 // there are sufficient fast track slots available
7218 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007219 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007220 // check compatibility with audio effects.
7221 Mutex::Autolock _l(mLock);
7222 // Do not accept FAST flag if the session has software effects
7223 sp<EffectChain> chain = getEffectChain_l(sessionId);
7224 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007225 audio_input_flags_t old = *flags;
7226 chain->checkInputFlagCompatibility(flags);
7227 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007228 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7229 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007230 }
7231 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007232 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007233 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7234 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007235 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007236 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7237 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007238 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007239 this, frameCount, mFrameCount, mPipeFramesP2,
7240 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007241 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007242 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007243 }
7244 }
7245
Eric Laurentf14db3c2017-12-08 14:20:36 -08007246 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7247 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7248 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7249 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7250 lStatus = BAD_TYPE;
7251 goto Exit;
7252 }
7253
Glenn Kasten74105912014-07-03 12:28:53 -07007254 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007255 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007256 // fast track: frame count is exactly the pipe depth
7257 frameCount = mPipeFramesP2;
7258 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007259 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007260 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007261 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7262 // or 20 ms if there is a fast capture
7263 // TODO This could be a roundupRatio inline, and const
7264 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7265 * sampleRate + mSampleRate - 1) / mSampleRate;
7266 // minimum number of notification periods is at least kMinNotifications,
7267 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7268 static const size_t kMinNotifications = 3;
7269 static const uint32_t kMinMs = 30;
7270 // TODO This could be a roundupRatio inline
7271 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7272 // TODO This could be a roundupRatio inline
7273 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7274 maxNotificationFrames;
7275 const size_t minFrameCount = maxNotificationFrames *
7276 max(kMinNotifications, minNotificationsByMs);
7277 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007278 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7279 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007280 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007281 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007282 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007283 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007284
7285 { // scope for mLock
7286 Mutex::Autolock _l(mLock);
7287
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007288 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007289 format, channelMask, frameCount,
7290 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007291 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007292
Glenn Kasten03003332013-08-06 15:40:54 -07007293 lStatus = track->initCheck();
7294 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007295 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007296 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007297 goto Exit;
7298 }
7299 mTracks.add(track);
7300
Eric Laurent05067782016-06-01 18:27:28 -07007301 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007302 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7303 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7304 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007305 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007306 }
Eric Laurent81784c32012-11-19 14:55:58 -08007307 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007308
Eric Laurent81784c32012-11-19 14:55:58 -08007309 lStatus = NO_ERROR;
7310
7311Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007312 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007313 return track;
7314}
7315
7316status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7317 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007318 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007319{
7320 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7321 sp<ThreadBase> strongMe = this;
7322 status_t status = NO_ERROR;
7323
7324 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007325 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007326 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007327 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007328 triggerSession,
7329 recordTrack->sessionId(),
7330 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007331 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007332 // Sync event can be cancelled by the trigger session if the track is not in a
7333 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007334 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007335 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007336 } else {
7337 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007338 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007339 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007340 }
7341 }
7342
7343 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007344 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007345 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007346 if (recordTrack->isInvalid()) {
7347 recordTrack->clearSyncStartEvent();
7348 return INVALID_OPERATION;
7349 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007350 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7351 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007352 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7353 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007354 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007355 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007356 } else {
7357 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007358 }
7359 return status;
7360 }
7361
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007362 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7363 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7364 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007365 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007366 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007367 status_t status = NO_ERROR;
7368 if (recordTrack->isExternalTrack()) {
7369 mLock.unlock();
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08007370 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007371 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007372 if (recordTrack->isInvalid()) {
7373 recordTrack->clearSyncStartEvent();
7374 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7375 recordTrack->mState = TrackBase::STARTING_2;
7376 // STARTING_2 forces destroy to call stopInput.
7377 }
7378 return INVALID_OPERATION;
7379 }
7380 if (recordTrack->mState != TrackBase::STARTING_1) {
7381 ALOGW("%s(%d): unsynchronized mState:%d change",
7382 __func__, recordTrack->id(), recordTrack->mState);
7383 // Someone else has changed state, let them take over,
7384 // leave mState in the new state.
7385 recordTrack->clearSyncStartEvent();
7386 return INVALID_OPERATION;
7387 }
7388 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007389 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007390 ALOGW("%s(%d): startInput failed, status %d",
7391 __func__, recordTrack->id(), status);
7392 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7393 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007394 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007395 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007396 return status;
7397 }
Eric Laurent81784c32012-11-19 14:55:58 -08007398 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007399 // Catch up with current buffer indices if thread is already running.
7400 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7401 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7402 // see previously buffered data before it called start(), but with greater risk of overrun.
7403
Andy Hung73c02e42015-03-29 01:13:58 -07007404 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007405 if (!recordTrack->isDirect()) {
7406 // clear any converter state as new data will be discontinuous
7407 recordTrack->mRecordBufferConverter->reset();
7408 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007409 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007410 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007411 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007412 return status;
7413 }
Eric Laurent81784c32012-11-19 14:55:58 -08007414}
7415
Eric Laurent81784c32012-11-19 14:55:58 -08007416void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7417{
7418 sp<SyncEvent> strongEvent = event.promote();
7419
7420 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007421 sp<RefBase> ptr = strongEvent->cookie().promote();
7422 if (ptr != 0) {
7423 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7424 recordTrack->handleSyncStartEvent(strongEvent);
7425 }
Eric Laurent81784c32012-11-19 14:55:58 -08007426 }
7427}
7428
Glenn Kastena8356f62013-07-25 14:37:52 -07007429bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007430 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007431 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007432 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007433 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007434 return false;
7435 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007436 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007437 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007438
7439 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7440 mWaitWorkCV.broadcast(); // signal thread to stop
7441 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007442 }
Andy Hungce685402018-10-05 17:23:27 -07007443
7444 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007445 ALOGV("Record stopped OK");
7446 return true;
7447 }
Andy Hungce685402018-10-05 17:23:27 -07007448
7449 // don't handle anything - we've been invalidated or restarted and in a different state
7450 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7451 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007452 return false;
7453}
7454
Glenn Kasten0f11b512014-01-31 16:18:54 -08007455bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007456{
7457 return false;
7458}
7459
Glenn Kasten0f11b512014-01-31 16:18:54 -08007460status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007461{
7462#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7463 if (!isValidSyncEvent(event)) {
7464 return BAD_VALUE;
7465 }
7466
Glenn Kastend848eb42016-03-08 13:42:11 -08007467 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007468 status_t ret = NAME_NOT_FOUND;
7469
7470 Mutex::Autolock _l(mLock);
7471
7472 for (size_t i = 0; i < mTracks.size(); i++) {
7473 sp<RecordTrack> track = mTracks[i];
7474 if (eventSession == track->sessionId()) {
7475 (void) track->setSyncEvent(event);
7476 ret = NO_ERROR;
7477 }
7478 }
7479 return ret;
7480#else
7481 return BAD_VALUE;
7482#endif
7483}
7484
jiabin653cc0a2018-01-17 17:54:10 -08007485status_t AudioFlinger::RecordThread::getActiveMicrophones(
7486 std::vector<media::MicrophoneInfo>* activeMicrophones)
7487{
7488 ALOGV("RecordThread::getActiveMicrophones");
7489 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007490 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7491 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007492}
7493
Kevin Rocard069c2712018-03-29 19:09:14 -07007494void AudioFlinger::RecordThread::updateMetadata_l()
7495{
7496 if (mInput == nullptr || mInput->stream == nullptr ||
7497 !mActiveTracks.readAndClearHasChanged()) {
7498 return;
7499 }
7500 StreamInHalInterface::SinkMetadata metadata;
7501 for (const sp<RecordTrack> &track : mActiveTracks) {
7502 // No track is invalid as this is called after prepareTrack_l in the same critical section
7503 metadata.tracks.push_back({
7504 .source = track->attributes().source,
7505 .gain = 1, // capture tracks do not have volumes
7506 });
7507 }
7508 mInput->stream->updateSinkMetadata(metadata);
7509}
7510
Eric Laurent81784c32012-11-19 14:55:58 -08007511// destroyTrack_l() must be called with ThreadBase::mLock held
7512void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7513{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007514 track->terminate();
7515 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007516 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007517 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007518 removeTrack_l(track);
7519 }
7520}
7521
7522void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7523{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007524 String8 result;
7525 track->appendDump(result, false /* active */);
7526 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7527
Eric Laurent81784c32012-11-19 14:55:58 -08007528 mTracks.remove(track);
7529 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007530 if (track->isFastTrack()) {
7531 ALOG_ASSERT(!mFastTrackAvail);
7532 mFastTrackAvail = true;
7533 }
Eric Laurent81784c32012-11-19 14:55:58 -08007534}
7535
7536void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7537{
7538 dumpInternals(fd, args);
7539 dumpTracks(fd, args);
7540 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007541 dprintf(fd, " Local log:\n");
7542 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007543}
7544
7545void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7546{
Glenn Kasten44182c22015-03-05 17:12:23 -08007547 dumpBase(fd, args);
7548
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007549 AudioStreamIn *input = mInput;
7550 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7551 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7552 input, flags, inputFlagsToString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007553 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007554 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007555 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007556 }
Andy Hungbfa64962017-06-12 14:43:19 -07007557
7558 if (input != nullptr) {
7559 dprintf(fd, " Hal stream dump:\n");
7560 (void)input->stream->dump(fd);
7561 }
7562
Mikhail Naganovf4a342a2018-12-04 08:55:41 -08007563 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hung7f39f562018-08-08 17:30:20 -07007564 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
Andy Hung20bd30b2018-06-01 15:39:35 -07007565 if (latencyMs != 0.) {
7566 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7567 } else {
7568 dprintf(fd, " NormalRecord latency ms: unavail\n");
7569 }
7570
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007571 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007572 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007573
Glenn Kasten2f90c512015-12-02 11:40:09 -08007574 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7575 // while we are dumping it. It may be inconsistent, but it won't mutate!
7576 // This is a large object so we place it on the heap.
7577 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007578 const std::unique_ptr<FastCaptureDumpState> copy =
7579 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007580 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007581}
7582
Glenn Kasten0f11b512014-01-31 16:18:54 -08007583void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007584{
Eric Laurent81784c32012-11-19 14:55:58 -08007585 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007586 size_t numtracks = mTracks.size();
7587 size_t numactive = mActiveTracks.size();
7588 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007589 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007590 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007591 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007592 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007593 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007594 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007595 for (size_t i = 0; i < numtracks ; ++i) {
7596 sp<RecordTrack> track = mTracks[i];
7597 if (track != 0) {
7598 bool active = mActiveTracks.indexOf(track) >= 0;
7599 if (active) {
7600 numactiveseen++;
7601 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007602 result.append(prefix);
7603 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007604 }
Eric Laurent81784c32012-11-19 14:55:58 -08007605 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007606 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007607 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007608 }
7609
Marco Nelissenb2208842014-02-07 14:00:50 -08007610 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007611 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007612 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007613 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007614 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007615 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007616 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007617 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007618 result.append(prefix);
7619 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007620 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007621 }
Eric Laurent81784c32012-11-19 14:55:58 -08007622
7623 }
7624 write(fd, result.string(), result.size());
7625}
7626
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007627void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7628{
7629 Mutex::Autolock _l(mLock);
7630 for (size_t i = 0; i < mTracks.size() ; i++) {
7631 sp<RecordTrack> track = mTracks[i];
7632 if (track != 0 && track->uid() == uid) {
7633 track->setSilenced(silenced);
7634 }
7635 }
7636}
Andy Hung73c02e42015-03-29 01:13:58 -07007637
7638void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7639{
7640 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7641 RecordThread *recordThread = (RecordThread *) threadBase.get();
7642 mRsmpInFront = recordThread->mRsmpInRear;
7643 mRsmpInUnrel = 0;
7644}
7645
7646void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7647 size_t *framesAvailable, bool *hasOverrun)
7648{
7649 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7650 RecordThread *recordThread = (RecordThread *) threadBase.get();
7651 const int32_t rear = recordThread->mRsmpInRear;
7652 const int32_t front = mRsmpInFront;
7653 const ssize_t filled = rear - front;
7654
7655 size_t framesIn;
7656 bool overrun = false;
7657 if (filled < 0) {
7658 // should not happen, but treat like a massive overrun and re-sync
7659 framesIn = 0;
7660 mRsmpInFront = rear;
7661 overrun = true;
7662 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7663 framesIn = (size_t) filled;
7664 } else {
7665 // client is not keeping up with server, but give it latest data
7666 framesIn = recordThread->mRsmpInFrames;
7667 mRsmpInFront = /* front = */ rear - framesIn;
7668 overrun = true;
7669 }
7670 if (framesAvailable != NULL) {
7671 *framesAvailable = framesIn;
7672 }
7673 if (hasOverrun != NULL) {
7674 *hasOverrun = overrun;
7675 }
7676}
7677
Eric Laurent81784c32012-11-19 14:55:58 -08007678// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007679status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007680 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007681{
Andy Hung73c02e42015-03-29 01:13:58 -07007682 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007683 if (threadBase == 0) {
7684 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007685 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007686 return NOT_ENOUGH_DATA;
7687 }
7688 RecordThread *recordThread = (RecordThread *) threadBase.get();
7689 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007690 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007691 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007692 // FIXME should not be P2 (don't want to increase latency)
7693 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007694 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007695 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007696 front &= recordThread->mRsmpInFramesP2 - 1;
7697 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007698 if (part1 > (size_t) filled) {
7699 part1 = filled;
7700 }
7701 size_t ask = buffer->frameCount;
7702 ALOG_ASSERT(ask > 0);
7703 if (part1 > ask) {
7704 part1 = ask;
7705 }
7706 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007707 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007708 buffer->raw = NULL;
7709 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007710 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007711 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007712 }
7713
Andy Hung57446612015-04-19 23:56:46 -07007714 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007715 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007716 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007717 return NO_ERROR;
7718}
7719
7720// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007721void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7722 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007723{
Glenn Kasten85948432013-08-19 12:09:05 -07007724 size_t stepCount = buffer->frameCount;
7725 if (stepCount == 0) {
7726 return;
7727 }
Andy Hung73c02e42015-03-29 01:13:58 -07007728 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7729 mRsmpInUnrel -= stepCount;
7730 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007731 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007732 buffer->frameCount = 0;
7733}
7734
Eric Laurentd8365c52017-07-16 15:27:05 -07007735void AudioFlinger::RecordThread::checkBtNrec()
7736{
7737 Mutex::Autolock _l(mLock);
7738 checkBtNrec_l();
7739}
7740
7741void AudioFlinger::RecordThread::checkBtNrec_l()
7742{
7743 // disable AEC and NS if the device is a BT SCO headset supporting those
7744 // pre processings
7745 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7746 mAudioFlinger->btNrecIsOff();
7747 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7748 for (size_t i = 0; i < mEffectChains.size(); i++) {
7749 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7750 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7751 }
7752 }
7753}
7754
Andy Hung97a893e2015-03-29 01:03:07 -07007755
Eric Laurent10351942014-05-08 18:49:52 -07007756bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7757 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007758{
7759 bool reconfig = false;
7760
Eric Laurent10351942014-05-08 18:49:52 -07007761 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007762
Eric Laurent10351942014-05-08 18:49:52 -07007763 audio_format_t reqFormat = mFormat;
7764 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007765 // 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 -07007766 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7767
7768 AudioParameter param = AudioParameter(keyValuePair);
7769 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007770
7771 // scope for AutoPark extends to end of method
7772 AutoPark<FastCapture> park(mFastCapture);
7773
Eric Laurent10351942014-05-08 18:49:52 -07007774 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7775 // channel count change can be requested. Do we mandate the first client defines the
7776 // HAL sampling rate and channel count or do we allow changes on the fly?
7777 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7778 samplingRate = value;
7779 reconfig = true;
7780 }
7781 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007782 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007783 status = BAD_VALUE;
7784 } else {
7785 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007786 reconfig = true;
7787 }
Eric Laurent10351942014-05-08 18:49:52 -07007788 }
7789 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7790 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007791 if (!audio_is_input_channel(mask) ||
7792 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007793 status = BAD_VALUE;
7794 } else {
7795 channelMask = mask;
7796 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007797 }
Eric Laurent10351942014-05-08 18:49:52 -07007798 }
7799 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7800 // do not accept frame count changes if tracks are open as the track buffer
7801 // size depends on frame count and correct behavior would not be guaranteed
7802 // if frame count is changed after track creation
7803 if (mActiveTracks.size() > 0) {
7804 status = INVALID_OPERATION;
7805 } else {
7806 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007807 }
Eric Laurent10351942014-05-08 18:49:52 -07007808 }
7809 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7810 // forward device change to effects that have requested to be
7811 // aware of attached audio device.
7812 for (size_t i = 0; i < mEffectChains.size(); i++) {
7813 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007814 }
Eric Laurent81784c32012-11-19 14:55:58 -08007815
Eric Laurent10351942014-05-08 18:49:52 -07007816 // store input device and output device but do not forward output device to audio HAL.
7817 // Note that status is ignored by the caller for output device
7818 // (see AudioFlinger::setParameters()
7819 if (audio_is_output_devices(value)) {
7820 mOutDevice = value;
7821 status = BAD_VALUE;
7822 } else {
7823 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007824 if (value != AUDIO_DEVICE_NONE) {
7825 mPrevInDevice = value;
7826 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007827 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007828 }
Eric Laurent10351942014-05-08 18:49:52 -07007829 }
7830 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7831 mAudioSource != (audio_source_t)value) {
7832 // forward device change to effects that have requested to be
7833 // aware of attached audio device.
7834 for (size_t i = 0; i < mEffectChains.size(); i++) {
7835 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007836 }
Eric Laurent10351942014-05-08 18:49:52 -07007837 mAudioSource = (audio_source_t)value;
7838 }
Glenn Kastene198c362013-08-13 09:13:36 -07007839
Eric Laurent10351942014-05-08 18:49:52 -07007840 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007841 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007842 if (status == INVALID_OPERATION) {
7843 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007844 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007845 }
7846 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007847 if (status == BAD_VALUE) {
7848 uint32_t sRate;
7849 audio_channel_mask_t channelMask;
7850 audio_format_t format;
7851 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7852 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7853 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7854 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7855 status = NO_ERROR;
7856 }
Eric Laurent81784c32012-11-19 14:55:58 -08007857 }
Eric Laurent10351942014-05-08 18:49:52 -07007858 if (status == NO_ERROR) {
7859 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007860 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007861 }
7862 }
Eric Laurent81784c32012-11-19 14:55:58 -08007863 }
Eric Laurent10351942014-05-08 18:49:52 -07007864
Eric Laurent81784c32012-11-19 14:55:58 -08007865 return reconfig;
7866}
7867
7868String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7869{
Eric Laurent81784c32012-11-19 14:55:58 -08007870 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007871 if (initCheck() == NO_ERROR) {
7872 String8 out_s8;
7873 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7874 return out_s8;
7875 }
Eric Laurent81784c32012-11-19 14:55:58 -08007876 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007877 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007878}
7879
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007880void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007881 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7882
7883 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007884
7885 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007886 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007887 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007888 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007889 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007890 desc->mChannelMask = mChannelMask;
7891 desc->mSamplingRate = mSampleRate;
7892 desc->mFormat = mFormat;
7893 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007894 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007895 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007896 break;
7897
Eric Laurent73e26b62015-04-27 16:55:58 -07007898 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007899 default:
7900 break;
7901 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007902 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007903}
7904
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007905void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007906{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007907 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7908 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07007909 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007910 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
7911 if (audio_is_linear_pcm(mFormat)) {
7912 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
7913 mChannelCount, FCC_8);
7914 } else {
7915 // Can have more that FCC_8 channels in encoded streams.
7916 ALOGI("HAL format %#x is not linear pcm", mFormat);
7917 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007918 result = mInput->stream->getFrameSize(&mFrameSize);
7919 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7920 result = mInput->stream->getBufferSize(&mBufferSize);
7921 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007922 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007923 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7924 "mBufferSize=%lld, mFrameCount=%lld",
7925 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7926 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007927 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007928 // 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 -07007929 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007930 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007931 // A larger value should allow more old data to be read after a track calls start(),
7932 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007933 //
7934 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007935 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007936 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007937 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007938 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007939
7940 // TODO optimize audio capture buffer sizes ...
7941 // Here we calculate the size of the sliding buffer used as a source
7942 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7943 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7944 // be better to have it derived from the pipe depth in the long term.
7945 // The current value is higher than necessary. However it should not add to latency.
7946
Glenn Kasten85948432013-08-19 12:09:05 -07007947 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007948 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7949 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007950 // if posix_memalign fails, will segv here.
7951 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007952
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007953 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7954 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007955}
7956
Glenn Kasten5f972c02014-01-13 09:59:31 -08007957uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007958{
7959 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007960 uint32_t result;
7961 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7962 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007963 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007964 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007965}
7966
Eric Laurent4c415062016-06-17 16:14:16 -07007967// hasAudioSession_l() must be called with ThreadBase::mLock held
7968uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007969{
Eric Laurent81784c32012-11-19 14:55:58 -08007970 uint32_t result = 0;
7971 if (getEffectChain_l(sessionId) != 0) {
7972 result = EFFECT_SESSION;
7973 }
7974
7975 for (size_t i = 0; i < mTracks.size(); ++i) {
7976 if (sessionId == mTracks[i]->sessionId()) {
7977 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007978 if (mTracks[i]->isFastTrack()) {
7979 result |= FAST_SESSION;
7980 }
Eric Laurent81784c32012-11-19 14:55:58 -08007981 break;
7982 }
7983 }
7984
7985 return result;
7986}
7987
Glenn Kastend848eb42016-03-08 13:42:11 -08007988KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007989{
Glenn Kastend848eb42016-03-08 13:42:11 -08007990 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007991 Mutex::Autolock _l(mLock);
7992 for (size_t j = 0; j < mTracks.size(); ++j) {
7993 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007994 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007995 if (ids.indexOfKey(sessionId) < 0) {
7996 ids.add(sessionId, true);
7997 }
7998 }
7999 return ids;
8000}
8001
8002AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8003{
8004 Mutex::Autolock _l(mLock);
8005 AudioStreamIn *input = mInput;
8006 mInput = NULL;
8007 return input;
8008}
8009
8010// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008011sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008012{
8013 if (mInput == NULL) {
8014 return NULL;
8015 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008016 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008017}
8018
8019status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8020{
8021 // only one chain per input thread
Eric Tan39ec8d62018-07-24 09:49:29 -07008022 if (!mEffectChains.isEmpty()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07008023 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08008024 return INVALID_OPERATION;
8025 }
8026 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008027 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008028 chain->setInBuffer(NULL);
8029 chain->setOutBuffer(NULL);
8030
8031 checkSuspendOnAddEffectChain_l(chain);
8032
Eric Laurent1b928682014-10-02 19:41:47 -07008033 // make sure enabled pre processing effects state is communicated to the HAL as we
8034 // just moved them to a new input stream.
8035 chain->syncHalEffectsState();
8036
Eric Laurent81784c32012-11-19 14:55:58 -08008037 mEffectChains.add(chain);
8038
8039 return NO_ERROR;
8040}
8041
8042size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8043{
8044 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
8045 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008046 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08008047 chain.get(), mEffectChains.size(), this);
8048 if (mEffectChains.size() == 1) {
8049 mEffectChains.removeAt(0);
8050 }
8051 return 0;
8052}
8053
Eric Laurent1c333e22014-05-20 10:48:17 -07008054status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8055 audio_patch_handle_t *handle)
8056{
8057 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008058
8059 // store new device and send to effects
8060 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07008061 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07008062 for (size_t i = 0; i < mEffectChains.size(); i++) {
8063 mEffectChains[i]->setDevice_l(mInDevice);
8064 }
8065
Eric Laurentd8365c52017-07-16 15:27:05 -07008066 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008067
8068 // store new source and send to effects
8069 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8070 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008071 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008072 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008073 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008074 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008075
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008076 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008077 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8078 status = hwDevice->createAudioPatch(patch->num_sources,
8079 patch->sources,
8080 patch->num_sinks,
8081 patch->sinks,
8082 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008083 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008084 char *address;
8085 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8086 address = audio_device_address_to_parameter(
8087 patch->sources[0].ext.device.type,
8088 patch->sources[0].ext.device.address);
8089 } else {
8090 address = (char *)calloc(1, 1);
8091 }
8092 AudioParameter param = AudioParameter(String8(address));
8093 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008094 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008095 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008096 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008097 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008098 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008099 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008100 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008101
Eric Laurente8726fe2015-06-26 09:39:24 -07008102 if (mInDevice != mPrevInDevice) {
8103 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8104 mPrevInDevice = mInDevice;
8105 }
Eric Laurent296fb132015-05-01 11:38:42 -07008106
Eric Laurent1c333e22014-05-20 10:48:17 -07008107 return status;
8108}
8109
8110status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8111{
8112 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008113
8114 mInDevice = AUDIO_DEVICE_NONE;
8115
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008116 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008117 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8118 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008119 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008120 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008121 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008122 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008123 }
8124 return status;
8125}
8126
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008127void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008128{
8129 Mutex::Autolock _l(mLock);
8130 mTracks.add(record);
8131}
8132
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008133void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008134{
8135 Mutex::Autolock _l(mLock);
8136 destroyTrack_l(record);
8137}
8138
Mikhail Naganovdc769682018-05-04 15:34:08 -07008139void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008140{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008141 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008142 config->role = AUDIO_PORT_ROLE_SINK;
8143 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8144 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008145 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8146 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8147 config->flags.input = mInput->flags;
8148 }
Eric Laurent83b88082014-06-20 18:31:16 -07008149}
Eric Laurent1c333e22014-05-20 10:48:17 -07008150
Eric Laurent6acd1d42017-01-04 14:23:29 -08008151// ----------------------------------------------------------------------------
8152// Mmap
8153// ----------------------------------------------------------------------------
8154
8155AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8156 : mThread(thread)
8157{
Phil Burk9fabbf82017-08-03 12:02:00 -07008158 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008159}
8160
8161AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8162{
Phil Burk9fabbf82017-08-03 12:02:00 -07008163 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008164}
8165
8166status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8167 struct audio_mmap_buffer_info *info)
8168{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008169 return mThread->createMmapBuffer(minSizeFrames, info);
8170}
8171
8172status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8173{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008174 return mThread->getMmapPosition(position);
8175}
8176
Eric Laurenta54f1282017-07-01 19:39:32 -07008177status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008178 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008179
8180{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008181 return mThread->start(client, handle);
8182}
8183
8184status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8185{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008186 return mThread->stop(handle);
8187}
8188
Eric Laurent18b57012017-02-13 16:23:52 -08008189status_t AudioFlinger::MmapThreadHandle::standby()
8190{
Eric Laurent18b57012017-02-13 16:23:52 -08008191 return mThread->standby();
8192}
8193
Eric Laurent6acd1d42017-01-04 14:23:29 -08008194
8195AudioFlinger::MmapThread::MmapThread(
8196 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8197 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8198 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8199 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008200 mSessionId(AUDIO_SESSION_NONE),
8201 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008202 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008203 mActiveTracks(&this->mLocalLog),
8204 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8205 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008206{
Eric Laurent18b57012017-02-13 16:23:52 -08008207 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008208 readHalParameters_l();
8209}
8210
8211AudioFlinger::MmapThread::~MmapThread()
8212{
Eric Laurent18b57012017-02-13 16:23:52 -08008213 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008214}
8215
8216void AudioFlinger::MmapThread::onFirstRef()
8217{
8218 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8219}
8220
8221void AudioFlinger::MmapThread::disconnect()
8222{
Eric Laurent331679c2018-04-16 17:03:16 -07008223 ActiveTracks<MmapTrack> activeTracks;
8224 {
8225 Mutex::Autolock _l(mLock);
8226 for (const sp<MmapTrack> &t : mActiveTracks) {
8227 activeTracks.add(t);
8228 }
8229 }
8230 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008231 stop(t->portId());
8232 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008233 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008234 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008235 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008236 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008237 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008238 }
8239}
8240
8241
8242void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8243 audio_stream_type_t streamType __unused,
8244 audio_session_t sessionId,
8245 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008246 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008247 audio_port_handle_t portId)
8248{
8249 mAttr = *attr;
8250 mSessionId = sessionId;
8251 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008252 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008253 mPortId = portId;
8254}
8255
8256status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8257 struct audio_mmap_buffer_info *info)
8258{
8259 if (mHalStream == 0) {
8260 return NO_INIT;
8261 }
Eric Laurent18b57012017-02-13 16:23:52 -08008262 mStandby = true;
8263 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008264 return mHalStream->createMmapBuffer(minSizeFrames, info);
8265}
8266
8267status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8268{
8269 if (mHalStream == 0) {
8270 return NO_INIT;
8271 }
8272 return mHalStream->getMmapPosition(position);
8273}
8274
Eric Laurent331679c2018-04-16 17:03:16 -07008275status_t AudioFlinger::MmapThread::exitStandby()
8276{
8277 status_t ret = mHalStream->start();
8278 if (ret != NO_ERROR) {
8279 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8280 return ret;
8281 }
8282 mStandby = false;
8283 return NO_ERROR;
8284}
8285
Eric Laurenta54f1282017-07-01 19:39:32 -07008286status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008287 audio_port_handle_t *handle)
8288{
Eric Laurenta54f1282017-07-01 19:39:32 -07008289 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8290 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008291 if (mHalStream == 0) {
8292 return NO_INIT;
8293 }
8294
8295 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008296
Eric Laurenta54f1282017-07-01 19:39:32 -07008297 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008298 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008299 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008300 }
8301
8302 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8303
8304 audio_io_handle_t io = mId;
8305 if (isOutput()) {
8306 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8307 config.sample_rate = mSampleRate;
8308 config.channel_mask = mChannelMask;
8309 config.format = mFormat;
8310 audio_stream_type_t stream = streamType();
8311 audio_output_flags_t flags =
8312 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008313 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008314 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8315 mSessionId,
8316 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008317 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008318 client.clientUid,
8319 &config,
8320 flags,
8321 &deviceId,
8322 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008323 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008324 audio_config_base_t config;
8325 config.sample_rate = mSampleRate;
8326 config.channel_mask = mChannelMask;
8327 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008328 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008329 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8330 mSessionId,
8331 client.clientPid,
8332 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008333 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008334 &config,
8335 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8336 &deviceId,
8337 &portId);
8338 }
8339 // APM should not chose a different input or output stream for the same set of attributes
8340 // and audo configuration
8341 if (ret != NO_ERROR || io != mId) {
8342 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8343 __FUNCTION__, ret, io, mId);
8344 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008345 }
8346
8347 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008348 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008349 } else {
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08008350 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008351 }
8352
Eric Laurent331679c2018-04-16 17:03:16 -07008353 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008354 // abort if start is rejected by audio policy manager
8355 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008356 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008357 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008358 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008359 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008360 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008361 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008362 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008363 }
Eric Laurent331679c2018-04-16 17:03:16 -07008364 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008365 } else {
8366 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008367 }
8368 return PERMISSION_DENIED;
8369 }
8370
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008371 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8372 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008373 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008374
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08008375 if (isOutput()) {
8376 // force volume update when a new track is added
8377 mHalVolFloat = -1.0f;
8378 } else if (!track->isSilenced_l()) {
8379 for (const sp<MmapTrack> &t : mActiveTracks) {
8380 if (t->isSilenced_l() && t->uid() != client.clientUid)
8381 t->invalidate();
8382 }
8383 }
8384
8385
Eric Laurent6acd1d42017-01-04 14:23:29 -08008386 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008387 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008388 if (chain != 0) {
8389 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8390 chain->incTrackCnt();
8391 chain->incActiveTrackCnt();
8392 }
8393
8394 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008395 broadcast_l();
8396
Eric Laurenta54f1282017-07-01 19:39:32 -07008397 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008398
8399 return NO_ERROR;
8400}
8401
8402status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8403{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008404 ALOGV("%s handle %d", __FUNCTION__, handle);
8405
8406 if (mHalStream == 0) {
8407 return NO_INIT;
8408 }
8409
Eric Laurenta54f1282017-07-01 19:39:32 -07008410 if (handle == mPortId) {
8411 mHalStream->stop();
8412 return NO_ERROR;
8413 }
8414
Eric Laurent331679c2018-04-16 17:03:16 -07008415 Mutex::Autolock _l(mLock);
8416
Eric Laurent6acd1d42017-01-04 14:23:29 -08008417 sp<MmapTrack> track;
8418 for (const sp<MmapTrack> &t : mActiveTracks) {
8419 if (handle == t->portId()) {
8420 track = t;
8421 break;
8422 }
8423 }
8424 if (track == 0) {
8425 return BAD_VALUE;
8426 }
8427
8428 mActiveTracks.remove(track);
8429
Eric Laurent331679c2018-04-16 17:03:16 -07008430 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008431 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008432 AudioSystem::stopOutput(track->portId());
8433 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008434 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008435 AudioSystem::stopInput(track->portId());
8436 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008437 }
Eric Laurent331679c2018-04-16 17:03:16 -07008438 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008439
8440 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8441 if (chain != 0) {
8442 chain->decActiveTrackCnt();
8443 chain->decTrackCnt();
8444 }
8445
8446 broadcast_l();
8447
Eric Laurent6acd1d42017-01-04 14:23:29 -08008448 return NO_ERROR;
8449}
8450
Eric Laurent18b57012017-02-13 16:23:52 -08008451status_t AudioFlinger::MmapThread::standby()
8452{
8453 ALOGV("%s", __FUNCTION__);
8454
8455 if (mHalStream == 0) {
8456 return NO_INIT;
8457 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008458 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008459 return INVALID_OPERATION;
8460 }
8461 mHalStream->standby();
8462 mStandby = true;
8463 releaseWakeLock();
8464 return NO_ERROR;
8465}
8466
Eric Laurent6acd1d42017-01-04 14:23:29 -08008467
8468void AudioFlinger::MmapThread::readHalParameters_l()
8469{
8470 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8471 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8472 mFormat = mHALFormat;
8473 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8474 result = mHalStream->getFrameSize(&mFrameSize);
8475 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8476 result = mHalStream->getBufferSize(&mBufferSize);
8477 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8478 mFrameCount = mBufferSize / mFrameSize;
8479}
8480
8481bool AudioFlinger::MmapThread::threadLoop()
8482{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008483 checkSilentMode_l();
8484
8485 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8486
8487 while (!exitPending())
8488 {
8489 Mutex::Autolock _l(mLock);
8490 Vector< sp<EffectChain> > effectChains;
8491
8492 if (mSignalPending) {
8493 // A signal was raised while we were unlocked
8494 mSignalPending = false;
8495 } else {
8496 if (mConfigEvents.isEmpty()) {
8497 // we're about to wait, flush the binder command buffer
8498 IPCThreadState::self()->flushCommands();
8499
8500 if (exitPending()) {
8501 break;
8502 }
8503
Eric Laurent6acd1d42017-01-04 14:23:29 -08008504 // wait until we have something to do...
8505 ALOGV("%s going to sleep", myName.string());
8506 mWaitWorkCV.wait(mLock);
8507 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008508
8509 checkSilentMode_l();
8510
8511 continue;
8512 }
8513 }
8514
8515 processConfigEvents_l();
8516
8517 processVolume_l();
8518
8519 checkInvalidTracks_l();
8520
8521 mActiveTracks.updatePowerState(this);
8522
Kevin Rocard069c2712018-03-29 19:09:14 -07008523 updateMetadata_l();
8524
Eric Laurent6acd1d42017-01-04 14:23:29 -08008525 lockEffectChains_l(effectChains);
8526 for (size_t i = 0; i < effectChains.size(); i ++) {
8527 effectChains[i]->process_l();
8528 }
8529 // enable changes in effect chain
8530 unlockEffectChains(effectChains);
8531 // Effect chains will be actually deleted here if they were removed from
8532 // mEffectChains list during mixing or effects processing
8533 }
8534
8535 threadLoop_exit();
8536
8537 if (!mStandby) {
8538 threadLoop_standby();
8539 mStandby = true;
8540 }
8541
Eric Laurent6acd1d42017-01-04 14:23:29 -08008542 ALOGV("Thread %p type %d exiting", this, mType);
8543 return false;
8544}
8545
8546// checkForNewParameter_l() must be called with ThreadBase::mLock held
8547bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8548 status_t& status)
8549{
8550 AudioParameter param = AudioParameter(keyValuePair);
8551 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008552 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008553 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008554 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008555 // forward device change to effects that have requested to be
8556 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008557 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008558 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008559 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008560 }
8561 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008562 if (audio_is_output_devices(device)) {
8563 mOutDevice = device;
8564 if (!isOutput()) {
8565 sendToHal = false;
8566 }
8567 } else {
8568 mInDevice = device;
8569 if (device != AUDIO_DEVICE_NONE) {
8570 mPrevInDevice = value;
8571 }
8572 // TODO: implement and call checkBtNrec_l();
8573 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008574 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008575 if (sendToHal) {
8576 status = mHalStream->setParameters(keyValuePair);
8577 } else {
8578 status = NO_ERROR;
8579 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008580
8581 return false;
8582}
8583
8584String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8585{
8586 Mutex::Autolock _l(mLock);
8587 String8 out_s8;
8588 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8589 return out_s8;
8590 }
8591 return String8();
8592}
8593
8594void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8595 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8596
8597 desc->mIoHandle = mId;
8598
8599 switch (event) {
8600 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008601 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008602 case AUDIO_INPUT_CONFIG_CHANGED:
8603 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008604 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008605 case AUDIO_OUTPUT_CONFIG_CHANGED:
8606 desc->mPatch = mPatch;
8607 desc->mChannelMask = mChannelMask;
8608 desc->mSamplingRate = mSampleRate;
8609 desc->mFormat = mFormat;
8610 desc->mFrameCount = mFrameCount;
8611 desc->mFrameCountHAL = mFrameCount;
8612 desc->mLatency = 0;
8613 break;
8614
8615 case AUDIO_INPUT_CLOSED:
8616 case AUDIO_OUTPUT_CLOSED:
8617 default:
8618 break;
8619 }
8620 mAudioFlinger->ioConfigChanged(event, desc, pid);
8621}
8622
8623status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8624 audio_patch_handle_t *handle)
8625{
8626 status_t status = NO_ERROR;
8627
8628 // store new device and send to effects
8629 audio_devices_t type = AUDIO_DEVICE_NONE;
8630 audio_port_handle_t deviceId;
8631 if (isOutput()) {
8632 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8633 type |= patch->sinks[i].ext.device.type;
8634 }
8635 deviceId = patch->sinks[0].id;
8636 } else {
8637 type = patch->sources[0].ext.device.type;
8638 deviceId = patch->sources[0].id;
8639 }
8640
8641 for (size_t i = 0; i < mEffectChains.size(); i++) {
8642 mEffectChains[i]->setDevice_l(type);
8643 }
8644
8645 if (isOutput()) {
8646 mOutDevice = type;
8647 } else {
8648 mInDevice = type;
8649 // store new source and send to effects
8650 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8651 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8652 for (size_t i = 0; i < mEffectChains.size(); i++) {
8653 mEffectChains[i]->setAudioSource_l(mAudioSource);
8654 }
8655 }
8656 }
8657
8658 if (mAudioHwDev->supportsAudioPatches()) {
8659 status = mHalDevice->createAudioPatch(patch->num_sources,
8660 patch->sources,
8661 patch->num_sinks,
8662 patch->sinks,
8663 handle);
8664 } else {
8665 char *address;
8666 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8667 //FIXME: we only support address on first sink with HAL version < 3.0
8668 address = audio_device_address_to_parameter(
8669 patch->sinks[0].ext.device.type,
8670 patch->sinks[0].ext.device.address);
8671 } else {
8672 address = (char *)calloc(1, 1);
8673 }
8674 AudioParameter param = AudioParameter(String8(address));
8675 free(address);
8676 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8677 if (!isOutput()) {
8678 param.addInt(String8(AudioParameter::keyInputSource),
8679 (int)patch->sinks[0].ext.mix.usecase.source);
8680 }
8681 status = mHalStream->setParameters(param.toString());
8682 *handle = AUDIO_PATCH_HANDLE_NONE;
8683 }
8684
8685 if (isOutput() && mPrevOutDevice != mOutDevice) {
8686 mPrevOutDevice = type;
8687 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008688 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008689 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008690 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008691 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008692 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008693 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008694 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008695 }
8696 if (!isOutput() && mPrevInDevice != mInDevice) {
8697 mPrevInDevice = type;
8698 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008699 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008700 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008701 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008702 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008703 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008704 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008705 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008706 }
8707 return status;
8708}
8709
8710status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8711{
8712 status_t status = NO_ERROR;
8713
8714 mInDevice = AUDIO_DEVICE_NONE;
8715
8716 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8717 supportsAudioPatches : false;
8718
8719 if (supportsAudioPatches) {
8720 status = mHalDevice->releaseAudioPatch(handle);
8721 } else {
8722 AudioParameter param;
8723 param.addInt(String8(AudioParameter::keyRouting), 0);
8724 status = mHalStream->setParameters(param.toString());
8725 }
8726 return status;
8727}
8728
Mikhail Naganovdc769682018-05-04 15:34:08 -07008729void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008730{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008731 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008732 if (isOutput()) {
8733 config->role = AUDIO_PORT_ROLE_SOURCE;
8734 config->ext.mix.hw_module = mAudioHwDev->handle();
8735 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8736 } else {
8737 config->role = AUDIO_PORT_ROLE_SINK;
8738 config->ext.mix.hw_module = mAudioHwDev->handle();
8739 config->ext.mix.usecase.source = mAudioSource;
8740 }
8741}
8742
8743status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8744{
8745 audio_session_t session = chain->sessionId();
8746
8747 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8748 // Attach all tracks with same session ID to this chain.
8749 // indicate all active tracks in the chain
8750 for (const sp<MmapTrack> &track : mActiveTracks) {
8751 if (session == track->sessionId()) {
8752 chain->incTrackCnt();
8753 chain->incActiveTrackCnt();
8754 }
8755 }
8756
8757 chain->setThread(this);
8758 chain->setInBuffer(nullptr);
8759 chain->setOutBuffer(nullptr);
8760 chain->syncHalEffectsState();
8761
8762 mEffectChains.add(chain);
8763 checkSuspendOnAddEffectChain_l(chain);
8764 return NO_ERROR;
8765}
8766
8767size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8768{
8769 audio_session_t session = chain->sessionId();
8770
8771 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8772
8773 for (size_t i = 0; i < mEffectChains.size(); i++) {
8774 if (chain == mEffectChains[i]) {
8775 mEffectChains.removeAt(i);
8776 // detach all active tracks from the chain
8777 // detach all tracks with same session ID from this chain
8778 for (const sp<MmapTrack> &track : mActiveTracks) {
8779 if (session == track->sessionId()) {
8780 chain->decActiveTrackCnt();
8781 chain->decTrackCnt();
8782 }
8783 }
8784 break;
8785 }
8786 }
8787 return mEffectChains.size();
8788}
8789
8790// hasAudioSession_l() must be called with ThreadBase::mLock held
8791uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8792{
8793 uint32_t result = 0;
8794 if (getEffectChain_l(sessionId) != 0) {
8795 result = EFFECT_SESSION;
8796 }
8797
8798 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8799 sp<MmapTrack> track = mActiveTracks[i];
8800 if (sessionId == track->sessionId()) {
8801 result |= TRACK_SESSION;
8802 if (track->isFastTrack()) {
8803 result |= FAST_SESSION;
8804 }
8805 break;
8806 }
8807 }
8808
8809 return result;
8810}
8811
8812void AudioFlinger::MmapThread::threadLoop_standby()
8813{
8814 mHalStream->standby();
8815}
8816
8817void AudioFlinger::MmapThread::threadLoop_exit()
8818{
Phil Burk7dce7282017-09-27 13:51:41 -07008819 // Do not call callback->onTearDown() because it is redundant for thread exit
8820 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008821}
8822
8823status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8824{
8825 return BAD_VALUE;
8826}
8827
8828bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8829{
8830 return false;
8831}
8832
8833status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8834 const effect_descriptor_t *desc, audio_session_t sessionId)
8835{
8836 // No global effect sessions on mmap threads
8837 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8838 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8839 desc->name, mThreadName);
8840 return BAD_VALUE;
8841 }
8842
8843 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8844 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8845 desc->name);
8846 return BAD_VALUE;
8847 }
8848 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008849 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8850 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008851 return BAD_VALUE;
8852 }
8853
8854 // Only allow effects without processing load or latency
8855 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8856 return BAD_VALUE;
8857 }
8858
8859 return NO_ERROR;
8860
8861}
8862
8863void AudioFlinger::MmapThread::checkInvalidTracks_l()
8864{
8865 for (const sp<MmapTrack> &track : mActiveTracks) {
8866 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008867 sp<MmapStreamCallback> callback = mCallback.promote();
8868 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008869 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008870 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008871 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008872 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8873 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8874 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008875 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008876 }
8877 }
8878}
8879
8880void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8881{
8882 dumpInternals(fd, args);
8883 dumpTracks(fd, args);
8884 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008885 dprintf(fd, " Local log:\n");
8886 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008887}
8888
8889void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8890{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008891 dumpBase(fd, args);
8892
8893 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8894 mAttr.content_type, mAttr.usage, mAttr.source);
8895 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07008896 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008897 dprintf(fd, " No active clients\n");
8898 }
8899}
8900
8901void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8902{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008903 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008904 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008905 dprintf(fd, " %zu Tracks\n", numtracks);
8906 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008907 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008908 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008909 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008910 for (size_t i = 0; i < numtracks ; ++i) {
8911 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008912 result.append(prefix);
8913 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008914 }
8915 } else {
8916 dprintf(fd, "\n");
8917 }
8918 write(fd, result.string(), result.size());
8919}
8920
8921AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8922 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8923 AudioHwDevice *hwDev, AudioStreamOut *output,
8924 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8925 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8926 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008927 mStreamVolume(1.0),
8928 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008929 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008930{
8931 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8932 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8933 mMasterVolume = audioFlinger->masterVolume_l();
8934 mMasterMute = audioFlinger->masterMute_l();
8935 if (mAudioHwDev) {
8936 if (mAudioHwDev->canSetMasterVolume()) {
8937 mMasterVolume = 1.0;
8938 }
8939
8940 if (mAudioHwDev->canSetMasterMute()) {
8941 mMasterMute = false;
8942 }
8943 }
8944}
8945
8946void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8947 audio_stream_type_t streamType,
8948 audio_session_t sessionId,
8949 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008950 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008951 audio_port_handle_t portId)
8952{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008953 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008954 mStreamType = streamType;
8955}
8956
8957AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8958{
8959 Mutex::Autolock _l(mLock);
8960 AudioStreamOut *output = mOutput;
8961 mOutput = NULL;
8962 return output;
8963}
8964
8965void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8966{
8967 Mutex::Autolock _l(mLock);
8968 // Don't apply master volume in SW if our HAL can do it for us.
8969 if (mAudioHwDev &&
8970 mAudioHwDev->canSetMasterVolume()) {
8971 mMasterVolume = 1.0;
8972 } else {
8973 mMasterVolume = value;
8974 }
8975}
8976
8977void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8978{
8979 Mutex::Autolock _l(mLock);
8980 // Don't apply master mute in SW if our HAL can do it for us.
8981 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8982 mMasterMute = false;
8983 } else {
8984 mMasterMute = muted;
8985 }
8986}
8987
8988void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8989{
8990 Mutex::Autolock _l(mLock);
8991 if (stream == mStreamType) {
8992 mStreamVolume = value;
8993 broadcast_l();
8994 }
8995}
8996
8997float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8998{
8999 Mutex::Autolock _l(mLock);
9000 if (stream == mStreamType) {
9001 return mStreamVolume;
9002 }
9003 return 0.0f;
9004}
9005
9006void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9007{
9008 Mutex::Autolock _l(mLock);
9009 if (stream == mStreamType) {
9010 mStreamMute= muted;
9011 broadcast_l();
9012 }
9013}
9014
9015void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9016{
9017 Mutex::Autolock _l(mLock);
9018 if (streamType == mStreamType) {
9019 for (const sp<MmapTrack> &track : mActiveTracks) {
9020 track->invalidate();
9021 }
9022 broadcast_l();
9023 }
9024}
9025
9026void AudioFlinger::MmapPlaybackThread::processVolume_l()
9027{
9028 float volume;
9029
9030 if (mMasterMute || mStreamMute) {
9031 volume = 0;
9032 } else {
9033 volume = mMasterVolume * mStreamVolume;
9034 }
9035
9036 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009037
9038 // Convert volumes from float to 8.24
9039 uint32_t vol = (uint32_t)(volume * (1 << 24));
9040
9041 // Delegate volume control to effect in track effect chain if needed
9042 // only one effect chain can be present on DirectOutputThread, so if
9043 // there is one, the track is connected to it
9044 if (!mEffectChains.isEmpty()) {
9045 mEffectChains[0]->setVolume_l(&vol, &vol);
9046 volume = (float)vol / (1 << 24);
9047 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009048 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009049 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9050 mHalVolFloat = volume; // HW volume control worked, so update value.
9051 mNoCallbackWarningCount = 0;
9052 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009053 sp<MmapStreamCallback> callback = mCallback.promote();
9054 if (callback != 0) {
9055 int channelCount;
9056 if (isOutput()) {
9057 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9058 } else {
9059 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9060 }
9061 Vector<float> values;
9062 for (int i = 0; i < channelCount; i++) {
9063 values.add(volume);
9064 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009065 mHalVolFloat = volume; // SW volume control worked, so update value.
9066 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009067 mLock.unlock();
9068 callback->onVolumeChanged(mChannelMask, values);
9069 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009070 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009071 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9072 ALOGW("Could not set MMAP stream volume: no volume callback!");
9073 mNoCallbackWarningCount++;
9074 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009075 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009076 }
9077 }
9078}
9079
Kevin Rocard069c2712018-03-29 19:09:14 -07009080void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9081{
9082 if (mOutput == nullptr || mOutput->stream == nullptr ||
9083 !mActiveTracks.readAndClearHasChanged()) {
9084 return;
9085 }
9086 StreamOutHalInterface::SourceMetadata metadata;
9087 for (const sp<MmapTrack> &track : mActiveTracks) {
9088 // No track is invalid as this is called after prepareTrack_l in the same critical section
9089 metadata.tracks.push_back({
9090 .usage = track->attributes().usage,
9091 .content_type = track->attributes().content_type,
9092 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9093 });
9094 }
9095 mOutput->stream->updateSourceMetadata(metadata);
9096}
9097
Eric Laurent6acd1d42017-01-04 14:23:29 -08009098void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9099{
9100 if (!mMasterMute) {
9101 char value[PROPERTY_VALUE_MAX];
9102 if (property_get("ro.audio.silent", value, "0") > 0) {
9103 char *endptr;
9104 unsigned long ul = strtoul(value, &endptr, 0);
9105 if (*endptr == '\0' && ul != 0) {
9106 ALOGD("Silence is golden");
9107 // The setprop command will not allow a property to be changed after
9108 // the first time it is set, so we don't have to worry about un-muting.
9109 setMasterMute_l(true);
9110 }
9111 }
9112 }
9113}
9114
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009115void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9116{
9117 MmapThread::toAudioPortConfig(config);
9118 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9119 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9120 config->flags.output = mOutput->flags;
9121 }
9122}
9123
Eric Laurent6acd1d42017-01-04 14:23:29 -08009124void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9125{
9126 MmapThread::dumpInternals(fd, args);
9127
Glenn Kastend3bb6452016-12-05 18:14:37 -08009128 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9129 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009130 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9131}
9132
9133AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9134 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9135 AudioHwDevice *hwDev, AudioStreamIn *input,
9136 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9137 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9138 mInput(input)
9139{
9140 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9141 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9142}
9143
Eric Laurent331679c2018-04-16 17:03:16 -07009144status_t AudioFlinger::MmapCaptureThread::exitStandby()
9145{
9146 mInput->stream->setGain(1.0f);
9147 return MmapThread::exitStandby();
9148}
9149
Eric Laurent6acd1d42017-01-04 14:23:29 -08009150AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9151{
9152 Mutex::Autolock _l(mLock);
9153 AudioStreamIn *input = mInput;
9154 mInput = NULL;
9155 return input;
9156}
Kevin Rocard069c2712018-03-29 19:09:14 -07009157
Eric Laurent331679c2018-04-16 17:03:16 -07009158
9159void AudioFlinger::MmapCaptureThread::processVolume_l()
9160{
9161 bool changed = false;
9162 bool silenced = false;
9163
9164 sp<MmapStreamCallback> callback = mCallback.promote();
9165 if (callback == 0) {
9166 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9167 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9168 mNoCallbackWarningCount++;
9169 }
9170 }
9171
9172 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9173 // track is silenced and unmute otherwise
9174 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9175 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9176 changed = true;
9177 silenced = mActiveTracks[i]->isSilenced_l();
9178 }
9179 }
9180
9181 if (changed) {
9182 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9183 }
9184}
9185
Kevin Rocard069c2712018-03-29 19:09:14 -07009186void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9187{
9188 if (mInput == nullptr || mInput->stream == nullptr ||
9189 !mActiveTracks.readAndClearHasChanged()) {
9190 return;
9191 }
9192 StreamInHalInterface::SinkMetadata metadata;
9193 for (const sp<MmapTrack> &track : mActiveTracks) {
9194 // No track is invalid as this is called after prepareTrack_l in the same critical section
9195 metadata.tracks.push_back({
9196 .source = track->attributes().source,
9197 .gain = 1, // capture tracks do not have volumes
9198 });
9199 }
9200 mInput->stream->updateSinkMetadata(metadata);
9201}
9202
Eric Laurent331679c2018-04-16 17:03:16 -07009203void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9204{
9205 Mutex::Autolock _l(mLock);
9206 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9207 if (mActiveTracks[i]->uid() == uid) {
9208 mActiveTracks[i]->setSilenced_l(silenced);
9209 broadcast_l();
9210 }
9211 }
9212}
9213
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009214void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9215{
9216 MmapThread::toAudioPortConfig(config);
9217 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9218 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9219 config->flags.input = mInput->flags;
9220 }
9221}
9222
Glenn Kasten63238ef2015-03-02 15:50:29 -08009223} // namespace android