blob: 5555acfb1fe07309fd587626538ed148c1b3968b [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
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002416void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002417 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2418 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002419
Eric Laurent73e26b62015-04-27 16:55:58 -07002420 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002421
2422 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002423 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002424 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002425 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002426 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002427 desc->mChannelMask = mChannelMask;
2428 desc->mSamplingRate = mSampleRate;
2429 desc->mFormat = mFormat;
2430 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002431 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002432 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002433 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002434 break;
2435
Eric Laurent73e26b62015-04-27 16:55:58 -07002436 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002437 default:
2438 break;
2439 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002440 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002441}
2442
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002443void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002444{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002445 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002446}
2447
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002448void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002449{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002450 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002451}
2452
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002453void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002454{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002455 mCallbackThread->setAsyncError();
2456}
2457
Eric Laurent3b4529e2013-09-05 18:09:19 -07002458void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459{
2460 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002461 // reject out of sequence requests
2462 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2463 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002464 mWaitWorkCV.signal();
2465 }
2466}
2467
Eric Laurent3b4529e2013-09-05 18:09:19 -07002468void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002469{
2470 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002471 // reject out of sequence requests
2472 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002473 // Register discontinuity when HW drain is completed because that can cause
2474 // the timestamp frame position to reset to 0 for direct and offload threads.
2475 // (Out of sequence requests are ignored, since the discontinuity would be handled
2476 // elsewhere, e.g. in flush).
2477 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002478 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002479 mWaitWorkCV.signal();
2480 }
2481}
2482
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002483void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002484{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002485 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002486 mSampleRate = mOutput->getSampleRate();
2487 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002488 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002489 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002490 }
Andy Hung9a592762014-07-21 21:56:01 -07002491 if ((mType == MIXER || mType == DUPLICATING)
2492 && !isValidPcmSinkChannelMask(mChannelMask)) {
2493 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2494 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002495 }
Andy Hunge5412692014-05-16 11:25:07 -07002496 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002497
2498 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002499 status_t result = mOutput->stream->getFormat(&mHALFormat);
2500 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002501 // Get format from the shim, which will be different than the HAL format
2502 // if playing compressed audio over HDMI passthrough.
2503 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002504 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002505 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002506 }
Andy Hung6146c082014-03-18 11:56:15 -07002507 if ((mType == MIXER || mType == DUPLICATING)
2508 && !isValidPcmSinkFormat(mFormat)) {
2509 LOG_FATAL("HAL format %#x not supported for mixed output",
2510 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002511 }
Phil Burk062e67a2015-02-11 13:40:50 -08002512 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002513 result = mOutput->stream->getBufferSize(&mBufferSize);
2514 LOG_ALWAYS_FATAL_IF(result != OK,
2515 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002516 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002517 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002518 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002519 mFrameCount);
2520 }
2521
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002522 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2523 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002524 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002525 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002526 }
2527 }
2528
Eric Laurentd1f69b02014-12-15 14:33:13 -08002529 mHwSupportsPause = false;
2530 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002531 bool supportsPause = false, supportsResume = false;
2532 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2533 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002534 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002535 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002536 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002537 } else if (supportsResume) {
2538 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002539 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002540 }
2541 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002542 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2543 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2544 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002545
Andy Hungfbfc3952015-01-15 13:33:51 -08002546 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2547 // For best precision, we use float instead of the associated output
2548 // device format (typically PCM 16 bit).
2549
2550 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2551 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2552 mBufferSize = mFrameSize * mFrameCount;
2553
2554 // TODO: We currently use the associated output device channel mask and sample rate.
2555 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2556 // (if a valid mask) to avoid premature downmix.
2557 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2558 // instead of the output device sample rate to avoid loss of high frequency information.
2559 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2560 }
2561
Andy Hung09a50072014-02-27 14:30:47 -08002562 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002563 double multiplier = 1.0;
2564 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2565 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002566 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2567 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002568
Eric Laurent81784c32012-11-19 14:55:58 -08002569 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2570 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2571 maxNormalFrameCount = maxNormalFrameCount & ~15;
2572 if (maxNormalFrameCount < minNormalFrameCount) {
2573 maxNormalFrameCount = minNormalFrameCount;
2574 }
2575 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2576 if (multiplier <= 1.0) {
2577 multiplier = 1.0;
2578 } else if (multiplier <= 2.0) {
2579 if (2 * mFrameCount <= maxNormalFrameCount) {
2580 multiplier = 2.0;
2581 } else {
2582 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2583 }
2584 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002585 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002586 }
2587 }
2588 mNormalFrameCount = multiplier * mFrameCount;
2589 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002590 if (mType == MIXER || mType == DUPLICATING) {
2591 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2592 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002593 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002594 mNormalFrameCount);
2595
Andy Hung08fb1742015-05-31 23:22:10 -07002596 // Check if we want to throttle the processing to no more than 2x normal rate
2597 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002598 mThreadThrottleTimeMs = 0;
2599 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002600 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2601
Andy Hung010a1a12014-03-13 13:57:33 -07002602 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2603 // Originally this was int16_t[] array, need to remove legacy implications.
2604 free(mSinkBuffer);
2605 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002606 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2607 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2608 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002609 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002610
Andy Hung69aed5f2014-02-25 17:24:40 -08002611 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2612 // drives the output.
2613 free(mMixerBuffer);
2614 mMixerBuffer = NULL;
2615 if (mMixerBufferEnabled) {
2616 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2617 mMixerBufferSize = mNormalFrameCount * mChannelCount
2618 * audio_bytes_per_sample(mMixerBufferFormat);
2619 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2620 }
Andy Hung98ef9782014-03-04 14:46:50 -08002621 free(mEffectBuffer);
2622 mEffectBuffer = NULL;
2623 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002624 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002625 mEffectBufferSize = mNormalFrameCount * mChannelCount
2626 * audio_bytes_per_sample(mEffectBufferFormat);
2627 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2628 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002629
Eric Laurent81784c32012-11-19 14:55:58 -08002630 // force reconfiguration of effect chains and engines to take new buffer size and audio
2631 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002632 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002633 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2634 // matter.
2635 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2636 Vector< sp<EffectChain> > effectChains = mEffectChains;
2637 for (size_t i = 0; i < effectChains.size(); i ++) {
2638 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2639 }
2640}
2641
Kevin Rocard069c2712018-03-29 19:09:14 -07002642void AudioFlinger::PlaybackThread::updateMetadata_l()
2643{
Kevin Rocard12381092018-04-11 09:19:59 -07002644 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2645 return; // That should not happen
2646 }
2647 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2648 for (const sp<Track> &track : mActiveTracks) {
2649 // Do not short-circuit as all hasChanged states must be reset
2650 // as all the metadata are going to be sent
2651 hasChanged |= track->readAndClearHasChanged();
2652 }
2653 if (!hasChanged) {
2654 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002655 }
2656 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002657 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002658 for (const sp<Track> &track : mActiveTracks) {
2659 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002660 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002661 }
Kevin Rocard12381092018-04-11 09:19:59 -07002662 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002663}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002664
Kevin Rocard12381092018-04-11 09:19:59 -07002665void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2666 const StreamOutHalInterface::SourceMetadata& metadata)
2667{
2668 mOutput->stream->updateSourceMetadata(metadata);
2669};
2670
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002671status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002672{
2673 if (halFrames == NULL || dspFrames == NULL) {
2674 return BAD_VALUE;
2675 }
2676 Mutex::Autolock _l(mLock);
2677 if (initCheck() != NO_ERROR) {
2678 return INVALID_OPERATION;
2679 }
Andy Hung818e7a32016-02-16 18:08:07 -08002680 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002681 *halFrames = framesWritten;
2682
2683 if (isSuspended()) {
2684 // return an estimation of rendered frames when the output is suspended
2685 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002686 *dspFrames = (uint32_t)
2687 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002688 return NO_ERROR;
2689 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002690 status_t status;
2691 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002692 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002693 *dspFrames = (size_t)frames;
2694 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002695 }
2696}
2697
Eric Laurent4c415062016-06-17 16:14:16 -07002698// hasAudioSession_l() must be called with ThreadBase::mLock held
2699uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002700{
Eric Laurent81784c32012-11-19 14:55:58 -08002701 uint32_t result = 0;
2702 if (getEffectChain_l(sessionId) != 0) {
2703 result = EFFECT_SESSION;
2704 }
2705
2706 for (size_t i = 0; i < mTracks.size(); ++i) {
2707 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002708 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002709 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002710 if (track->isFastTrack()) {
2711 result |= FAST_SESSION;
2712 }
Eric Laurent81784c32012-11-19 14:55:58 -08002713 break;
2714 }
2715 }
2716
2717 return result;
2718}
2719
Glenn Kastend848eb42016-03-08 13:42:11 -08002720uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002721{
2722 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2723 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2724 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2725 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2726 }
2727 for (size_t i = 0; i < mTracks.size(); i++) {
2728 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002729 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002730 return AudioSystem::getStrategyForStream(track->streamType());
2731 }
2732 }
2733 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2734}
2735
2736
Phil Burk062e67a2015-02-11 13:40:50 -08002737AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002738{
2739 Mutex::Autolock _l(mLock);
2740 return mOutput;
2741}
2742
Phil Burk062e67a2015-02-11 13:40:50 -08002743AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002744{
2745 Mutex::Autolock _l(mLock);
2746 AudioStreamOut *output = mOutput;
2747 mOutput = NULL;
2748 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2749 // must push a NULL and wait for ack
2750 mOutputSink.clear();
2751 mPipeSink.clear();
2752 mNormalSink.clear();
2753 return output;
2754}
2755
2756// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002757sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002758{
2759 if (mOutput == NULL) {
2760 return NULL;
2761 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002762 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002763}
2764
2765uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2766{
2767 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2768}
2769
2770status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2771{
2772 if (!isValidSyncEvent(event)) {
2773 return BAD_VALUE;
2774 }
2775
2776 Mutex::Autolock _l(mLock);
2777
2778 for (size_t i = 0; i < mTracks.size(); ++i) {
2779 sp<Track> track = mTracks[i];
2780 if (event->triggerSession() == track->sessionId()) {
2781 (void) track->setSyncEvent(event);
2782 return NO_ERROR;
2783 }
2784 }
2785
2786 return NAME_NOT_FOUND;
2787}
2788
2789bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2790{
2791 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2792}
2793
2794void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2795 const Vector< sp<Track> >& tracksToRemove)
2796{
Andy Hungfe726a62018-09-27 15:17:25 -07002797 // Miscellaneous track cleanup when removed from the active list,
2798 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002799#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002800 for (const auto& track : tracksToRemove) {
2801 if (track->isExternalTrack()) {
2802 // to track the speaker usage
2803 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002804 }
2805 }
Andy Hungfe726a62018-09-27 15:17:25 -07002806#else
2807 (void)tracksToRemove; // suppress unused warning
2808#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002809}
2810
2811void AudioFlinger::PlaybackThread::checkSilentMode_l()
2812{
2813 if (!mMasterMute) {
2814 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002815 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2816 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2817 return;
2818 }
Eric Laurent81784c32012-11-19 14:55:58 -08002819 if (property_get("ro.audio.silent", value, "0") > 0) {
2820 char *endptr;
2821 unsigned long ul = strtoul(value, &endptr, 0);
2822 if (*endptr == '\0' && ul != 0) {
2823 ALOGD("Silence is golden");
2824 // The setprop command will not allow a property to be changed after
2825 // the first time it is set, so we don't have to worry about un-muting.
2826 setMasterMute_l(true);
2827 }
2828 }
2829 }
2830}
2831
2832// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002833ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002834{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002835 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002836 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002837 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002838 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002839
2840 // If an NBAIO sink is present, use it to write the normal mixer's submix
2841 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002842
Andy Hung010a1a12014-03-13 13:57:33 -07002843 const size_t count = mBytesRemaining / mFrameSize;
2844
Simon Wilson2d590962012-11-29 15:18:50 -08002845 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002846 // update the setpoint when AudioFlinger::mScreenState changes
2847 uint32_t screenState = AudioFlinger::mScreenState;
2848 if (screenState != mScreenState) {
2849 mScreenState = screenState;
2850 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2851 if (pipe != NULL) {
2852 pipe->setAvgFrames((mScreenState & 1) ?
2853 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2854 }
2855 }
Andy Hung010a1a12014-03-13 13:57:33 -07002856 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002857 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002858 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002859 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002860#ifdef TEE_SINK
2861 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2862#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002863 } else {
2864 bytesWritten = framesWritten;
2865 }
2866 // otherwise use the HAL / AudioStreamOut directly
2867 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002869
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002871 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2872 mWriteAckSequence += 2;
2873 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002875 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002876 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002877 // FIXME We should have an implementation of timestamps for direct output threads.
2878 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002879 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002880
Eric Laurentbfb1b832013-01-07 09:53:42 -08002881 if (mUseAsyncWrite &&
2882 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2883 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002884 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002886 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 }
Eric Laurent81784c32012-11-19 14:55:58 -08002888 }
2889
Eric Laurent81784c32012-11-19 14:55:58 -08002890 mNumWrites++;
2891 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002892 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 return bytesWritten;
2894}
2895
2896void AudioFlinger::PlaybackThread::threadLoop_drain()
2897{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002898 bool supportsDrain = false;
2899 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002900 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2901 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002902 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2903 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002905 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002906 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002907 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002908 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002909 }
2910}
2911
2912void AudioFlinger::PlaybackThread::threadLoop_exit()
2913{
Eric Laurent275e8e92014-11-30 15:14:47 -08002914 {
2915 Mutex::Autolock _l(mLock);
2916 for (size_t i = 0; i < mTracks.size(); i++) {
2917 sp<Track> track = mTracks[i];
2918 track->invalidate();
2919 }
Andy Hungdae27702016-10-31 14:01:16 -07002920 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2921 // After we exit there are no more track changes sent to BatteryNotifier
2922 // because that requires an active threadLoop.
2923 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2924 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002925 }
Eric Laurent81784c32012-11-19 14:55:58 -08002926}
2927
2928/*
2929The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002930 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002931 - mActiveSleepTimeUs from activeSleepTimeUs()
2932 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002933 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2934 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002935 - maxPeriod from frame count and sample rate (MIXER only)
2936
2937The parameters that affect these derived values are:
2938 - frame count
2939 - frame size
2940 - sample rate
2941 - device type: A2DP or not
2942 - device latency
2943 - format: PCM or not
2944 - active sleep time
2945 - idle sleep time
2946*/
2947
2948void AudioFlinger::PlaybackThread::cacheParameters_l()
2949{
Andy Hung25c2dac2014-02-27 14:56:00 -08002950 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002951 mActiveSleepTimeUs = activeSleepTimeUs();
2952 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002953
2954 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2955 // truncating audio when going to standby.
2956 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2957 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2958 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2959 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2960 }
2961 }
Eric Laurent81784c32012-11-19 14:55:58 -08002962}
2963
Eric Laurent13084622016-05-17 10:51:49 -07002964bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002965{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002966 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002967 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002968 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002969 size_t size = mTracks.size();
2970 for (size_t i = 0; i < size; i++) {
2971 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002972 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002973 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002974 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002975 }
2976 }
Eric Laurent13084622016-05-17 10:51:49 -07002977 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002978}
2979
Haynes Mathew George05317d22016-05-03 16:34:26 -07002980void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2981{
2982 Mutex::Autolock _l(mLock);
2983 invalidateTracks_l(streamType);
2984}
2985
Eric Laurent81784c32012-11-19 14:55:58 -08002986status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2987{
Glenn Kastend848eb42016-03-08 13:42:11 -08002988 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002989 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002990 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08002991 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2992 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2993 &halInBuffer);
2994 if (result != OK) return result;
2995 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07002996 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002997 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002998 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002999 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003000 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003001 if (mType != DIRECT) {
3002 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003003 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003004 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003005 &halInBuffer);
3006 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003007#ifdef FLOAT_EFFECT_CHAIN
3008 buffer = halInBuffer->audioBuffer()->f32;
3009#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003010 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003011#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003012 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3013 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003014 }
3015
3016 // Attach all tracks with same session ID to this chain.
3017 for (size_t i = 0; i < mTracks.size(); ++i) {
3018 sp<Track> track = mTracks[i];
3019 if (session == track->sessionId()) {
3020 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3021 buffer);
3022 track->setMainBuffer(buffer);
3023 chain->incTrackCnt();
3024 }
3025 }
3026
3027 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003028 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003029 if (session == track->sessionId()) {
3030 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3031 chain->incActiveTrackCnt();
3032 }
3033 }
3034 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003035 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003036 chain->setInBuffer(halInBuffer);
3037 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003038 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003039 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003040 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3041 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003042 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003043 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003044 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003045 // Effect chain for other sessions are inserted at beginning of effect
3046 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003047 // sessions is not important.
3048 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3049 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3050 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003051 size_t size = mEffectChains.size();
3052 size_t i = 0;
3053 for (i = 0; i < size; i++) {
3054 if (mEffectChains[i]->sessionId() < session) {
3055 break;
3056 }
3057 }
3058 mEffectChains.insertAt(chain, i);
3059 checkSuspendOnAddEffectChain_l(chain);
3060
3061 return NO_ERROR;
3062}
3063
3064size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3065{
Glenn Kastend848eb42016-03-08 13:42:11 -08003066 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003067
3068 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3069
3070 for (size_t i = 0; i < mEffectChains.size(); i++) {
3071 if (chain == mEffectChains[i]) {
3072 mEffectChains.removeAt(i);
3073 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003074 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003075 if (session == track->sessionId()) {
3076 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3077 chain.get(), session);
3078 chain->decActiveTrackCnt();
3079 }
3080 }
3081
3082 // detach all tracks with same session ID from this chain
3083 for (size_t i = 0; i < mTracks.size(); ++i) {
3084 sp<Track> track = mTracks[i];
3085 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003086 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003087 chain->decTrackCnt();
3088 }
3089 }
3090 break;
3091 }
3092 }
3093 return mEffectChains.size();
3094}
3095
3096status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003097 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003098{
3099 Mutex::Autolock _l(mLock);
3100 return attachAuxEffect_l(track, EffectId);
3101}
3102
3103status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003104 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003105{
3106 status_t status = NO_ERROR;
3107
3108 if (EffectId == 0) {
3109 track->setAuxBuffer(0, NULL);
3110 } else {
3111 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3112 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3113 if (effect != 0) {
3114 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3115 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3116 } else {
3117 status = INVALID_OPERATION;
3118 }
3119 } else {
3120 status = BAD_VALUE;
3121 }
3122 }
3123 return status;
3124}
3125
3126void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3127{
3128 for (size_t i = 0; i < mTracks.size(); ++i) {
3129 sp<Track> track = mTracks[i];
3130 if (track->auxEffectId() == effectId) {
3131 attachAuxEffect_l(track, 0);
3132 }
3133 }
3134}
3135
3136bool AudioFlinger::PlaybackThread::threadLoop()
3137{
Glenn Kasten388d5712017-04-07 14:38:41 -07003138 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003139
Eric Laurent81784c32012-11-19 14:55:58 -08003140 Vector< sp<Track> > tracksToRemove;
3141
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003142 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003143 nsecs_t lastWriteFinished = -1; // time last server write completed
3144 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003145
3146 // MIXER
3147 nsecs_t lastWarning = 0;
3148
3149 // DUPLICATING
3150 // FIXME could this be made local to while loop?
3151 writeFrames = 0;
3152
3153 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003154 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003155
3156 if (mType == MIXER) {
3157 sleepTimeShift = 0;
3158 }
3159
3160 CpuStats cpuStats;
3161 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3162
3163 acquireWakeLock();
3164
Glenn Kasteneef598c2017-04-03 14:41:13 -07003165 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3166 // thread associated with this PlaybackThread.
3167 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3168 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003169 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3170 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003171 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003172 const char *logString = NULL;
3173
rago1bb90822017-05-02 18:31:48 -07003174 // Estimated time for next buffer to be written to hal. This is used only on
3175 // suspended mode (for now) to help schedule the wait time until next iteration.
3176 nsecs_t timeLoopNextNs = 0;
3177
Eric Laurent664539d2013-09-23 18:24:31 -07003178 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003179
Andy Hungf3234512018-07-03 14:51:47 -07003180 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3181 // TODO: add confirmation checks:
3182 // 1) DIRECT threads and linear PCM format really resets to 0?
3183 // 2) Is frame count really valid if not linear pcm?
3184 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3185 if (mType == OFFLOAD || mType == DIRECT) {
3186 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3187 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003188 audio_utils::Statistics<double> downstreamLatencyStatMs(0.999 /* alpha */);
3189 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003190
Eric Laurent81784c32012-11-19 14:55:58 -08003191 while (!exitPending())
3192 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003193 // Log merge requests are performed during AudioFlinger binder transactions, but
3194 // that does not cover audio playback. It's requested here for that reason.
3195 mAudioFlinger->requestLogMerge();
3196
Eric Laurent81784c32012-11-19 14:55:58 -08003197 cpuStats.sample(myName);
3198
3199 Vector< sp<EffectChain> > effectChains;
3200
Andy Hung2dbffc22018-08-08 18:50:41 -07003201 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3202 //
3203 // Note: we access outDevice() outside of mLock.
3204 if (isMsdDevice() && (outDevice() & AUDIO_DEVICE_OUT_BUS) != 0) {
3205 // Here, we try for the AF lock, but do not block on it as the latency
3206 // is more informational.
3207 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3208 std::vector<PatchPanel::SoftwarePatch> swPatches;
3209 double latencyMs;
3210 status_t status = INVALID_OPERATION;
3211 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3212 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3213 && swPatches.size() > 0) {
3214 status = swPatches[0].getLatencyMs_l(&latencyMs);
3215 downstreamPatchHandle = swPatches[0].getPatchHandle();
3216 }
3217 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
3218 downstreamLatencyStatMs.reset();
3219 lastDownstreamPatchHandle = downstreamPatchHandle;
3220 }
3221 if (status == OK) {
3222 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003223 // latency of 5 seconds).
3224 const double minLatency = 0., maxLatency = 5000.;
3225 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003226 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003227 } else {
3228 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003229 if (latencyMs < minLatency) latencyMs = minLatency;
3230 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003231 }
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003232 downstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003233 }
3234 mAudioFlinger->mLock.unlock();
3235 }
3236 } else {
3237 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3238 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
3239 downstreamLatencyStatMs.reset();
3240 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3241 }
3242 }
3243
Eric Laurent81784c32012-11-19 14:55:58 -08003244 { // scope for mLock
3245
3246 Mutex::Autolock _l(mLock);
3247
Eric Laurent021cf962014-05-13 10:18:14 -07003248 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003249
Glenn Kasteneef598c2017-04-03 14:41:13 -07003250 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003251 if (logString != NULL) {
3252 mNBLogWriter->logTimestamp();
3253 mNBLogWriter->log(logString);
3254 logString = NULL;
3255 }
3256
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003257 // Collect timestamp statistics for the Playback Thread types that support it.
3258 if (mType == MIXER
3259 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003260 || mType == DIRECT
3261 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003262 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003263 // and associate with the sink frames written out. We need
3264 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003265 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003266 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003267 if (mStandby) {
3268 mTimestampVerifier.discontinuity();
3269 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3270 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3271 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3272 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003273
3274 if (isTimestampCorrectionEnabled()) {
3275 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3276 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3277 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3278 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3279 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3280 = correctedTimestamp.mFrames;
3281 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3282 = correctedTimestamp.mTimeNs;
3283 ALOGV("TS_AFTER: %d %lld %lld", id(),
3284 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3285 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003286
3287 // Note: Downstream latency only added if timestamp correction enabled.
3288 if (downstreamLatencyStatMs.getN() > 0) { // we have latency info.
3289 const int64_t newPosition =
3290 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3291 - int64_t(downstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3292 // prevent retrograde
3293 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3294 newPosition,
3295 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3296 - mSuspendedFrames));
3297 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003298 }
3299
Andy Hung818e7a32016-02-16 18:08:07 -08003300 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003301 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003302
3303 // We keep track of the last valid kernel position in case we are in underrun
3304 // and the normal mixer period is the same as the fast mixer period, or there
3305 // is some error from the HAL.
3306 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3307 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3308 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3309 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3310 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3311
3312 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3313 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3314 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3315 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003316 }
3317
3318 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3319 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003320 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003321 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003322 }
3323
Andy Hung818e7a32016-02-16 18:08:07 -08003324 // copy over kernel info
3325 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003326 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3327 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003328 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3329 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003330 } else {
3331 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003332 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003333
Andy Hungc54b1ff2016-02-23 14:07:07 -08003334 // mFramesWritten for non-offloaded tracks are contiguous
3335 // even after standby() is called. This is useful for the track frame
3336 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003337 bool serverLocationUpdate = false;
3338 if (mFramesWritten != lastFramesWritten) {
3339 serverLocationUpdate = true;
3340 lastFramesWritten = mFramesWritten;
3341 }
3342 // Only update timestamps if there is a meaningful change.
3343 // Either the kernel timestamp must be valid or we have written something.
3344 if (kernelLocationUpdate || serverLocationUpdate) {
3345 if (serverLocationUpdate) {
3346 // use the time before we called the HAL write - it is a bit more accurate
3347 // to when the server last read data than the current time here.
3348 //
3349 // If we haven't written anything, mLastWriteTime will be -1
3350 // and we use systemTime().
3351 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3352 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3353 ? systemTime() : mLastWriteTime;
3354 }
Andy Hungdae27702016-10-31 14:01:16 -07003355
3356 for (const sp<Track> &t : mActiveTracks) {
3357 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003358 t->updateTrackFrameInfo(
3359 t->mAudioTrackServerProxy->framesReleased(),
3360 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003361 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003362 mTimestamp);
3363 }
Andy Hunge10393e2015-06-12 13:59:33 -07003364 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003365 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003366 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003367#if 0
3368 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003369 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003370 timespec ts;
3371 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003372 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003373 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003374 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003375 }
3376 ++z;
3377#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003378 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003379 if (mSignalPending) {
3380 // A signal was raised while we were unlocked
3381 mSignalPending = false;
3382 } else if (waitingAsyncCallback_l()) {
3383 if (exitPending()) {
3384 break;
3385 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003386 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003387 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003388 releaseWakeLock_l();
3389 released = true;
3390 }
Andy Hung10cbff12017-02-21 17:30:14 -08003391
3392 const int64_t waitNs = computeWaitTimeNs_l();
3393 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3394 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3395 if (status == TIMED_OUT) {
3396 mSignalPending = true; // if timeout recheck everything
3397 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003398 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003399 if (released) {
3400 acquireWakeLock_l();
3401 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003402 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3403 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003404
3405 continue;
3406 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003407 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003408 isSuspended()) {
3409 // put audio hardware into standby after short delay
3410 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003411
3412 threadLoop_standby();
3413
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003414 // This is where we go into standby
3415 if (!mStandby) {
3416 LOG_AUDIO_STATE();
3417 }
Eric Laurent81784c32012-11-19 14:55:58 -08003418 mStandby = true;
3419 }
3420
Eric Tan39ec8d62018-07-24 09:49:29 -07003421 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003422 // we're about to wait, flush the binder command buffer
3423 IPCThreadState::self()->flushCommands();
3424
3425 clearOutputTracks();
3426
3427 if (exitPending()) {
3428 break;
3429 }
3430
3431 releaseWakeLock_l();
3432 // wait until we have something to do...
3433 ALOGV("%s going to sleep", myName.string());
3434 mWaitWorkCV.wait(mLock);
3435 ALOGV("%s waking up", myName.string());
3436 acquireWakeLock_l();
3437
3438 mMixerStatus = MIXER_IDLE;
3439 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3440 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003441 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003442 checkSilentMode_l();
3443
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003444 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3445 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003446 if (mType == MIXER) {
3447 sleepTimeShift = 0;
3448 }
3449
3450 continue;
3451 }
3452 }
Eric Laurent81784c32012-11-19 14:55:58 -08003453 // mMixerStatusIgnoringFastTracks is also updated internally
3454 mMixerStatus = prepareTracks_l(&tracksToRemove);
3455
Andy Hungdae27702016-10-31 14:01:16 -07003456 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003457
Kevin Rocard069c2712018-03-29 19:09:14 -07003458 updateMetadata_l();
3459
Eric Laurent81784c32012-11-19 14:55:58 -08003460 // prevent any changes in effect chain list and in each effect chain
3461 // during mixing and effect process as the audio buffers could be deleted
3462 // or modified if an effect is created or deleted
3463 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003464 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003465
Eric Laurentbfb1b832013-01-07 09:53:42 -08003466 if (mBytesRemaining == 0) {
3467 mCurrentWriteLength = 0;
3468 if (mMixerStatus == MIXER_TRACKS_READY) {
3469 // threadLoop_mix() sets mCurrentWriteLength
3470 threadLoop_mix();
3471 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3472 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003473 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003474 // must be written to HAL
3475 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003476 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003477 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003478 }
3479 }
Andy Hung98ef9782014-03-04 14:46:50 -08003480 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003481 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003482 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3483 // or mSinkBuffer (if there are no effects).
3484 //
3485 // This is done pre-effects computation; if effects change to
3486 // support higher precision, this needs to move.
3487 //
3488 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003489 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003490 if (mMixerBufferValid) {
3491 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3492 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3493
Andy Hung2ddee192015-12-18 17:34:44 -08003494 // mono blend occurs for mixer threads only (not direct or offloaded)
3495 // and is handled here if we're going directly to the sink.
3496 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003497 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3498 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003499 }
3500
Andy Hung98ef9782014-03-04 14:46:50 -08003501 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3502 mNormalFrameCount * mChannelCount);
3503 }
3504
Eric Laurentbfb1b832013-01-07 09:53:42 -08003505 mBytesRemaining = mCurrentWriteLength;
3506 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003507 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3508 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3509 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3510 mBytesWritten += mBytesRemaining;
3511 mFramesWritten += framesRemaining;
3512 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003513 mBytesRemaining = 0;
3514 }
Eric Laurent81784c32012-11-19 14:55:58 -08003515
Eric Laurentbfb1b832013-01-07 09:53:42 -08003516 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003517 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003518 for (size_t i = 0; i < effectChains.size(); i ++) {
3519 effectChains[i]->process_l();
3520 }
Eric Laurent81784c32012-11-19 14:55:58 -08003521 }
3522 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003523 // Process effect chains for offloaded thread even if no audio
3524 // was read from audio track: process only updates effect state
3525 // and thus does have to be synchronized with audio writes but may have
3526 // to be called while waiting for async write callback
3527 if (mType == OFFLOAD) {
3528 for (size_t i = 0; i < effectChains.size(); i ++) {
3529 effectChains[i]->process_l();
3530 }
3531 }
Eric Laurent81784c32012-11-19 14:55:58 -08003532
Andy Hung98ef9782014-03-04 14:46:50 -08003533 // Only if the Effects buffer is enabled and there is data in the
3534 // Effects buffer (buffer valid), we need to
3535 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003536 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003537 if (mEffectBufferValid) {
3538 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003539
3540 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003541 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3542 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003543 }
3544
Andy Hung98ef9782014-03-04 14:46:50 -08003545 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3546 mNormalFrameCount * mChannelCount);
3547 }
3548
Eric Laurent81784c32012-11-19 14:55:58 -08003549 // enable changes in effect chain
3550 unlockEffectChains(effectChains);
3551
Eric Laurentbfb1b832013-01-07 09:53:42 -08003552 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003553 // mSleepTimeUs == 0 means we must write to audio hardware
3554 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003555 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003556 // We save lastWriteFinished here, as previousLastWriteFinished,
3557 // for throttling. On thread start, previousLastWriteFinished will be
3558 // set to -1, which properly results in no throttling after the first write.
3559 nsecs_t previousLastWriteFinished = lastWriteFinished;
3560 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003561 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003562 // FIXME rewrite to reduce number of system calls
3563 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003564 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003565 lastWriteFinished = systemTime();
3566 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003567 if (ret < 0) {
3568 mBytesRemaining = 0;
3569 } else {
3570 mBytesWritten += ret;
3571 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003572 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003573 }
3574 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3575 (mMixerStatus == MIXER_DRAIN_ALL)) {
3576 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003577 }
Andy Hung08fb1742015-05-31 23:22:10 -07003578 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003579 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003580 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003581 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003582 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003583 ATRACE_NAME("underrun");
3584 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003585 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003586 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003587 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003588 }
Andy Hung08fb1742015-05-31 23:22:10 -07003589
3590 if (mThreadThrottle
3591 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3592 && ret > 0) { // we wrote something
3593 // Limit MixerThread data processing to no more than twice the
3594 // expected processing rate.
3595 //
3596 // This helps prevent underruns with NuPlayer and other applications
3597 // which may set up buffers that are close to the minimum size, or use
3598 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3599 //
3600 // The throttle smooths out sudden large data drains from the device,
3601 // e.g. when it comes out of standby, which often causes problems with
3602 // (1) mixer threads without a fast mixer (which has its own warm-up)
3603 // (2) minimum buffer sized tracks (even if the track is full,
3604 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003605 //
3606 // Total time spent in last processing cycle equals time spent in
3607 // 1. threadLoop_write, as well as time spent in
3608 // 2. threadLoop_mix (significant for heavy mixing, especially
3609 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003610
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003611 // it's OK if deltaMs (and deltaNs) is an overestimate.
3612 nsecs_t deltaNs;
3613 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3614 __builtin_sub_overflow(
3615 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3616 const int32_t deltaMs = deltaNs / 1000000;
3617
Ivan Lozanoea04d392017-11-07 14:37:07 -08003618 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003619 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3620 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003621 // notify of throttle start on verbose log
3622 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3623 "mixer(%p) throttle begin:"
3624 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003625 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003626 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003627 // Throttle must be attributed to the previous mixer loop's write time
3628 // to allow back-to-back throttling.
3629 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003630 } else {
3631 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3632 if (diff > 0) {
3633 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003634 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003635 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3636 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003637 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003638 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3639 }
Andy Hung08fb1742015-05-31 23:22:10 -07003640 }
3641 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003642 }
Eric Laurent81784c32012-11-19 14:55:58 -08003643
Eric Laurentbfb1b832013-01-07 09:53:42 -08003644 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003645 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003646 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003647 // suspended requires accurate metering of sleep time.
3648 if (isSuspended()) {
3649 // advance by expected sleepTime
3650 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3651 const nsecs_t nowNs = systemTime();
3652
3653 // compute expected next time vs current time.
3654 // (negative deltas are treated as delays).
3655 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3656 if (deltaNs < -kMaxNextBufferDelayNs) {
3657 // Delays longer than the max allowed trigger a reset.
3658 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3659 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3660 timeLoopNextNs = nowNs + deltaNs;
3661 } else if (deltaNs < 0) {
3662 // Delays within the max delay allowed: zero the delta/sleepTime
3663 // to help the system catch up in the next iteration(s)
3664 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3665 deltaNs = 0;
3666 }
3667 // update sleep time (which is >= 0)
3668 mSleepTimeUs = deltaNs / 1000;
3669 }
Eric Laurente93cc032016-05-05 10:15:10 -07003670 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3671 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003672 }
Glenn Kastene7754022014-10-31 12:11:26 -07003673 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003674 }
Eric Laurent81784c32012-11-19 14:55:58 -08003675 }
3676
3677 // Finally let go of removed track(s), without the lock held
3678 // since we can't guarantee the destructors won't acquire that
3679 // same lock. This will also mutate and push a new fast mixer state.
3680 threadLoop_removeTracks(tracksToRemove);
3681 tracksToRemove.clear();
3682
3683 // FIXME I don't understand the need for this here;
3684 // it was in the original code but maybe the
3685 // assignment in saveOutputTracks() makes this unnecessary?
3686 clearOutputTracks();
3687
3688 // Effect chains will be actually deleted here if they were removed from
3689 // mEffectChains list during mixing or effects processing
3690 effectChains.clear();
3691
3692 // FIXME Note that the above .clear() is no longer necessary since effectChains
3693 // is now local to this block, but will keep it for now (at least until merge done).
3694 }
3695
Eric Laurentbfb1b832013-01-07 09:53:42 -08003696 threadLoop_exit();
3697
Eric Laurentcf817a22014-08-04 20:36:31 -07003698 if (!mStandby) {
3699 threadLoop_standby();
3700 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003701 }
3702
3703 releaseWakeLock();
3704
3705 ALOGV("Thread %p type %d exiting", this, mType);
3706 return false;
3707}
3708
Eric Laurentbfb1b832013-01-07 09:53:42 -08003709// removeTracks_l() must be called with ThreadBase::mLock held
3710void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3711{
Andy Hungfe726a62018-09-27 15:17:25 -07003712 for (const auto& track : tracksToRemove) {
3713 mActiveTracks.remove(track);
3714 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3715 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3716 if (chain != 0) {
3717 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3718 __func__, track->id(), chain.get(), track->sessionId());
3719 chain->decActiveTrackCnt();
3720 }
3721 // If an external client track, inform APM we're no longer active, and remove if needed.
3722 // We do this under lock so that the state is consistent if the Track is destroyed.
3723 if (track->isExternalTrack()) {
3724 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003725 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003726 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003727 }
3728 }
Andy Hungfe726a62018-09-27 15:17:25 -07003729 if (track->isTerminated()) {
3730 // remove from our tracks vector
3731 removeTrack_l(track);
3732 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003733 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003734}
Eric Laurent81784c32012-11-19 14:55:58 -08003735
Eric Laurentaccc1472013-09-20 09:36:34 -07003736status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3737{
3738 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003739 ExtendedTimestamp ets;
3740 status_t status = mNormalSink->getTimestamp(ets);
3741 if (status == NO_ERROR) {
3742 status = ets.getBestTimestamp(&timestamp);
3743 }
3744 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003745 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003746 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003747 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003748 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003749 timestamp.mPosition = (uint32_t)position64;
3750 return NO_ERROR;
3751 }
3752 }
3753 return INVALID_OPERATION;
3754}
Eric Laurent1c333e22014-05-20 10:48:17 -07003755
Eric Laurent054d9d32015-04-24 08:48:48 -07003756status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3757 audio_patch_handle_t *handle)
3758{
Andy Hungf60abce2016-08-26 11:37:54 -07003759 status_t status;
3760 if (property_get_bool("af.patch_park", false /* default_value */)) {
3761 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3762 // or if HAL does not properly lock against access.
3763 AutoPark<FastMixer> park(mFastMixer);
3764 status = PlaybackThread::createAudioPatch_l(patch, handle);
3765 } else {
3766 status = PlaybackThread::createAudioPatch_l(patch, handle);
3767 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003768 return status;
3769}
3770
Eric Laurent1c333e22014-05-20 10:48:17 -07003771status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3772 audio_patch_handle_t *handle)
3773{
3774 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003775
3776 // store new device and send to effects
3777 audio_devices_t type = AUDIO_DEVICE_NONE;
3778 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3779 type |= patch->sinks[i].ext.device.type;
3780 }
3781
3782#ifdef ADD_BATTERY_DATA
3783 // when changing the audio output device, call addBatteryData to notify
3784 // the change
3785 if (mOutDevice != type) {
3786 uint32_t params = 0;
3787 // check whether speaker is on
3788 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3789 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003790 }
3791
Eric Laurent054d9d32015-04-24 08:48:48 -07003792 audio_devices_t deviceWithoutSpeaker
3793 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3794 // check if any other device (except speaker) is on
3795 if (type & deviceWithoutSpeaker) {
3796 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3797 }
3798
3799 if (params != 0) {
3800 addBatteryData(params);
3801 }
3802 }
3803#endif
3804
3805 for (size_t i = 0; i < mEffectChains.size(); i++) {
3806 mEffectChains[i]->setDevice_l(type);
3807 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003808
3809 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3810 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3811 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003812 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003813 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003814
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003815 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003816 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3817 status = hwDevice->createAudioPatch(patch->num_sources,
3818 patch->sources,
3819 patch->num_sinks,
3820 patch->sinks,
3821 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003822 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003823 char *address;
3824 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3825 //FIXME: we only support address on first sink with HAL version < 3.0
3826 address = audio_device_address_to_parameter(
3827 patch->sinks[0].ext.device.type,
3828 patch->sinks[0].ext.device.address);
3829 } else {
3830 address = (char *)calloc(1, 1);
3831 }
3832 AudioParameter param = AudioParameter(String8(address));
3833 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003834 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003835 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003836 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003837 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003838 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003839 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003840 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3841 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003842 return status;
3843}
3844
Eric Laurent054d9d32015-04-24 08:48:48 -07003845status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3846{
Andy Hungf60abce2016-08-26 11:37:54 -07003847 status_t status;
3848 if (property_get_bool("af.patch_park", false /* default_value */)) {
3849 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3850 // or if HAL does not properly lock against access.
3851 AutoPark<FastMixer> park(mFastMixer);
3852 status = PlaybackThread::releaseAudioPatch_l(handle);
3853 } else {
3854 status = PlaybackThread::releaseAudioPatch_l(handle);
3855 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003856 return status;
3857}
3858
Eric Laurent1c333e22014-05-20 10:48:17 -07003859status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3860{
3861 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003862
3863 mOutDevice = AUDIO_DEVICE_NONE;
3864
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003865 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003866 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3867 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003868 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003869 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003870 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003871 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003872 }
3873 return status;
3874}
3875
Eric Laurent83b88082014-06-20 18:31:16 -07003876void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3877{
3878 Mutex::Autolock _l(mLock);
3879 mTracks.add(track);
3880}
3881
3882void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3883{
3884 Mutex::Autolock _l(mLock);
3885 destroyTrack_l(track);
3886}
3887
Mikhail Naganovdc769682018-05-04 15:34:08 -07003888void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003889{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003890 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003891 config->role = AUDIO_PORT_ROLE_SOURCE;
3892 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3893 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003894 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3895 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3896 config->flags.output = mOutput->flags;
3897 }
Eric Laurent83b88082014-06-20 18:31:16 -07003898}
3899
Eric Laurent81784c32012-11-19 14:55:58 -08003900// ----------------------------------------------------------------------------
3901
3902AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003903 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3904 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003905 // mAudioMixer below
3906 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003907 mFastMixerFutex(0),
3908 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003909 // mOutputSink below
3910 // mPipeSink below
3911 // mNormalSink below
3912{
3913 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003914 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003915 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003916 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3917 mNormalFrameCount);
3918 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3919
Andy Hungfbfc3952015-01-15 13:33:51 -08003920 if (type == DUPLICATING) {
3921 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3922 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3923 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3924 return;
3925 }
Eric Laurent81784c32012-11-19 14:55:58 -08003926 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003927 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003928 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003929 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003930#if !LOG_NDEBUG
3931 ssize_t index =
3932#else
3933 (void)
3934#endif
3935 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003936 ALOG_ASSERT(index == 0);
3937
3938 // initialize fast mixer depending on configuration
3939 bool initFastMixer;
3940 switch (kUseFastMixer) {
3941 case FastMixer_Never:
3942 initFastMixer = false;
3943 break;
3944 case FastMixer_Always:
3945 initFastMixer = true;
3946 break;
3947 case FastMixer_Static:
3948 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003949 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3950 // where the period is less than an experimentally determined threshold that can be
3951 // scheduled reliably with CFS. However, the BT A2DP HAL is
3952 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3953 initFastMixer = mFrameCount < mNormalFrameCount
3954 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003955 break;
3956 }
Andy Hungfda69402017-02-15 14:33:12 -08003957 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3958 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3959 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003960 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003961 audio_format_t fastMixerFormat;
3962 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3963 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3964 } else {
3965 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3966 }
3967 if (mFormat != fastMixerFormat) {
3968 // change our Sink format to accept our intermediate precision
3969 mFormat = fastMixerFormat;
3970 free(mSinkBuffer);
3971 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3972 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3973 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3974 }
Eric Laurent81784c32012-11-19 14:55:58 -08003975
3976 // create a MonoPipe to connect our submix to FastMixer
3977 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07003978
Andy Hung1258c1a2014-05-23 21:22:17 -07003979 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003980 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003981 format.mFormat = fastMixerFormat;
3982 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3983
Eric Laurent81784c32012-11-19 14:55:58 -08003984 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3985 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3986 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3987 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3988 const NBAIO_Format offers[1] = {format};
3989 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07003990#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003991 ssize_t index =
3992#else
3993 (void)
3994#endif
3995 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003996 ALOG_ASSERT(index == 0);
3997 monoPipe->setAvgFrames((mScreenState & 1) ?
3998 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3999 mPipeSink = monoPipe;
4000
Eric Laurent81784c32012-11-19 14:55:58 -08004001 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004002 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004003 FastMixerStateQueue *sq = mFastMixer->sq();
4004#ifdef STATE_QUEUE_DUMP
4005 sq->setObserverDump(&mStateQueueObserverDump);
4006 sq->setMutatorDump(&mStateQueueMutatorDump);
4007#endif
4008 FastMixerState *state = sq->begin();
4009 FastTrack *fastTrack = &state->mFastTracks[0];
4010 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4011 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4012 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004013 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
4014 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08004015 fastTrack->mGeneration++;
4016 state->mFastTracksGen++;
4017 state->mTrackMask = 1;
4018 // fast mixer will use the HAL output sink
4019 state->mOutputSink = mOutputSink.get();
4020 state->mOutputSinkGen++;
4021 state->mFrameCount = mFrameCount;
4022 state->mCommand = FastMixerState::COLD_IDLE;
4023 // already done in constructor initialization list
4024 //mFastMixerFutex = 0;
4025 state->mColdFutexAddr = &mFastMixerFutex;
4026 state->mColdGen++;
4027 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004028 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4029 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004030 sq->end();
4031 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4032
Eric Tan0513b5d2018-09-17 10:32:48 -07004033 NBLog::thread_info_t info;
4034 info.id = mId;
4035 info.type = NBLog::FASTMIXER;
4036 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4037
Eric Laurent81784c32012-11-19 14:55:58 -08004038 // start the fast mixer
4039 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4040 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004041 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004042 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004043
4044#ifdef AUDIO_WATCHDOG
4045 // create and start the watchdog
4046 mAudioWatchdog = new AudioWatchdog();
4047 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4048 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4049 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004050 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004051#endif
Andy Hung8946a282018-04-19 20:04:56 -07004052 } else {
4053#ifdef TEE_SINK
4054 // Only use the MixerThread tee if there is no FastMixer.
4055 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4056 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4057#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004058 }
4059
4060 switch (kUseFastMixer) {
4061 case FastMixer_Never:
4062 case FastMixer_Dynamic:
4063 mNormalSink = mOutputSink;
4064 break;
4065 case FastMixer_Always:
4066 mNormalSink = mPipeSink;
4067 break;
4068 case FastMixer_Static:
4069 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4070 break;
4071 }
4072}
4073
4074AudioFlinger::MixerThread::~MixerThread()
4075{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004076 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004077 FastMixerStateQueue *sq = mFastMixer->sq();
4078 FastMixerState *state = sq->begin();
4079 if (state->mCommand == FastMixerState::COLD_IDLE) {
4080 int32_t old = android_atomic_inc(&mFastMixerFutex);
4081 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004082 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004083 }
4084 }
4085 state->mCommand = FastMixerState::EXIT;
4086 sq->end();
4087 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4088 mFastMixer->join();
4089 // Though the fast mixer thread has exited, it's state queue is still valid.
4090 // We'll use that extract the final state which contains one remaining fast track
4091 // corresponding to our sub-mix.
4092 state = sq->begin();
4093 ALOG_ASSERT(state->mTrackMask == 1);
4094 FastTrack *fastTrack = &state->mFastTracks[0];
4095 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4096 delete fastTrack->mBufferProvider;
4097 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004098 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004099#ifdef AUDIO_WATCHDOG
4100 if (mAudioWatchdog != 0) {
4101 mAudioWatchdog->requestExit();
4102 mAudioWatchdog->requestExitAndWait();
4103 mAudioWatchdog.clear();
4104 }
4105#endif
4106 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004107 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004108 delete mAudioMixer;
4109}
4110
4111
4112uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4113{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004114 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004115 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4116 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4117 }
4118 return latency;
4119}
4120
Eric Laurentbfb1b832013-01-07 09:53:42 -08004121ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004122{
4123 // FIXME we should only do one push per cycle; confirm this is true
4124 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004125 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004126 FastMixerStateQueue *sq = mFastMixer->sq();
4127 FastMixerState *state = sq->begin();
4128 if (state->mCommand != FastMixerState::MIX_WRITE &&
4129 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4130 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004131
4132 // FIXME workaround for first HAL write being CPU bound on some devices
4133 ATRACE_BEGIN("write");
4134 mOutput->write((char *)mSinkBuffer, 0);
4135 ATRACE_END();
4136
Eric Laurent81784c32012-11-19 14:55:58 -08004137 int32_t old = android_atomic_inc(&mFastMixerFutex);
4138 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004139 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004140 }
4141#ifdef AUDIO_WATCHDOG
4142 if (mAudioWatchdog != 0) {
4143 mAudioWatchdog->resume();
4144 }
4145#endif
4146 }
4147 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004148#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004149 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004150 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004151#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004152 sq->end();
4153 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4154 if (kUseFastMixer == FastMixer_Dynamic) {
4155 mNormalSink = mPipeSink;
4156 }
4157 } else {
4158 sq->end(false /*didModify*/);
4159 }
4160 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004161 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004162}
4163
4164void AudioFlinger::MixerThread::threadLoop_standby()
4165{
4166 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004167 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004168 FastMixerStateQueue *sq = mFastMixer->sq();
4169 FastMixerState *state = sq->begin();
4170 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004171 // Report any frames trapped in the Monopipe
4172 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4173 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4174 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4175 "monoPipeWritten:%lld monoPipeLeft:%lld",
4176 (long long)mFramesWritten, (long long)mSuspendedFrames,
4177 (long long)mPipeSink->framesWritten(), pipeFrames);
4178 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4179
Eric Laurent81784c32012-11-19 14:55:58 -08004180 state->mCommand = FastMixerState::COLD_IDLE;
4181 state->mColdFutexAddr = &mFastMixerFutex;
4182 state->mColdGen++;
4183 mFastMixerFutex = 0;
4184 sq->end();
4185 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4186 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4187 if (kUseFastMixer == FastMixer_Dynamic) {
4188 mNormalSink = mOutputSink;
4189 }
4190#ifdef AUDIO_WATCHDOG
4191 if (mAudioWatchdog != 0) {
4192 mAudioWatchdog->pause();
4193 }
4194#endif
4195 } else {
4196 sq->end(false /*didModify*/);
4197 }
4198 }
4199 PlaybackThread::threadLoop_standby();
4200}
4201
Eric Laurentbfb1b832013-01-07 09:53:42 -08004202bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4203{
4204 return false;
4205}
4206
4207bool AudioFlinger::PlaybackThread::shouldStandby_l()
4208{
4209 return !mStandby;
4210}
4211
4212bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4213{
4214 Mutex::Autolock _l(mLock);
4215 return waitingAsyncCallback_l();
4216}
4217
Eric Laurent81784c32012-11-19 14:55:58 -08004218// shared by MIXER and DIRECT, overridden by DUPLICATING
4219void AudioFlinger::PlaybackThread::threadLoop_standby()
4220{
4221 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004222 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004223 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004224 // discard any pending drain or write ack by incrementing sequence
4225 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4226 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004227 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004228 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4229 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004230 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004231 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004232}
4233
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004234void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4235{
4236 ALOGV("signal playback thread");
4237 broadcast_l();
4238}
4239
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004240void AudioFlinger::PlaybackThread::onAsyncError()
4241{
4242 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4243 invalidateTracks((audio_stream_type_t)i);
4244 }
4245}
4246
Eric Laurent81784c32012-11-19 14:55:58 -08004247void AudioFlinger::MixerThread::threadLoop_mix()
4248{
Eric Laurent81784c32012-11-19 14:55:58 -08004249 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004250 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004251 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004252 // increase sleep time progressively when application underrun condition clears.
4253 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4254 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4255 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004256 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004257 sleepTimeShift--;
4258 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004259 mSleepTimeUs = 0;
4260 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004261 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004262
Eric Laurent81784c32012-11-19 14:55:58 -08004263}
4264
4265void AudioFlinger::MixerThread::threadLoop_sleepTime()
4266{
4267 // If no tracks are ready, sleep once for the duration of an output
4268 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004269 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004270 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004271 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4272 // Using the Monopipe availableToWrite, we estimate the
4273 // sleep time to retry for more data (before we underrun).
4274 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4275 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4276 const size_t pipeFrames = monoPipe->maxFrames();
4277 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4278 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4279 const size_t framesDelay = std::min(
4280 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4281 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4282 pipeFrames, framesLeft, framesDelay);
4283 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4284 } else {
4285 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4286 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4287 mSleepTimeUs = kMinThreadSleepTimeUs;
4288 }
4289 // reduce sleep time in case of consecutive application underruns to avoid
4290 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4291 // duration we would end up writing less data than needed by the audio HAL if
4292 // the condition persists.
4293 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4294 sleepTimeShift++;
4295 }
Eric Laurent81784c32012-11-19 14:55:58 -08004296 }
4297 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004298 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004299 }
4300 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004301 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4302 // before effects processing or output.
4303 if (mMixerBufferValid) {
4304 memset(mMixerBuffer, 0, mMixerBufferSize);
4305 } else {
4306 memset(mSinkBuffer, 0, mSinkBufferSize);
4307 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004308 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004309 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4310 "anticipated start");
4311 }
4312 // TODO add standby time extension fct of effect tail
4313}
4314
4315// prepareTracks_l() must be called with ThreadBase::mLock held
4316AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4317 Vector< sp<Track> > *tracksToRemove)
4318{
Andy Hungc0691382018-09-12 18:01:57 -07004319 // clean up deleted track ids in AudioMixer before allocating new tracks
4320 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4321 // for each trackId, destroy it in the AudioMixer
4322 if (mAudioMixer->exists(trackId)) {
4323 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004324 }
4325 });
Andy Hungc0691382018-09-12 18:01:57 -07004326 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004327
4328 mixer_state mixerStatus = MIXER_IDLE;
4329 // find out which tracks need to be processed
4330 size_t count = mActiveTracks.size();
4331 size_t mixedTracks = 0;
4332 size_t tracksWithEffect = 0;
4333 // counts only _active_ fast tracks
4334 size_t fastTracks = 0;
4335 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4336
4337 float masterVolume = mMasterVolume;
4338 bool masterMute = mMasterMute;
4339
4340 if (masterMute) {
4341 masterVolume = 0;
4342 }
4343 // Delegate master volume control to effect in output mix effect chain if needed
4344 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4345 if (chain != 0) {
4346 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4347 chain->setVolume_l(&v, &v);
4348 masterVolume = (float)((v + (1 << 23)) >> 24);
4349 chain.clear();
4350 }
4351
4352 // prepare a new state to push
4353 FastMixerStateQueue *sq = NULL;
4354 FastMixerState *state = NULL;
4355 bool didModify = false;
4356 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004357 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004358 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004359 sq = mFastMixer->sq();
4360 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004361 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004362 }
4363
Andy Hung69aed5f2014-02-25 17:24:40 -08004364 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004365 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004366
Andy Hungbd3b2b02018-05-21 10:53:11 -07004367 // DeferredOperations handles statistics after setting mixerStatus.
4368 class DeferredOperations {
4369 public:
4370 DeferredOperations(mixer_state *mixerStatus)
4371 : mMixerStatus(mixerStatus) { }
4372
4373 // when leaving scope, tally frames properly.
4374 ~DeferredOperations() {
4375 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4376 // because that is when the underrun occurs.
4377 // We do not distinguish between FastTracks and NormalTracks here.
4378 if (*mMixerStatus == MIXER_TRACKS_READY) {
4379 for (const auto &underrun : mUnderrunFrames) {
4380 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4381 underrun.second);
4382 }
4383 }
4384 }
4385
4386 // tallyUnderrunFrames() is called to update the track counters
4387 // with the number of underrun frames for a particular mixer period.
4388 // We defer tallying until we know the final mixer status.
4389 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4390 mUnderrunFrames.emplace_back(track, underrunFrames);
4391 }
4392
4393 private:
4394 const mixer_state * const mMixerStatus;
4395 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4396 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4397
Eric Laurent81784c32012-11-19 14:55:58 -08004398 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004399 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004400
4401 // this const just means the local variable doesn't change
4402 Track* const track = t.get();
4403
4404 // process fast tracks
4405 if (track->isFastTrack()) {
4406
4407 // It's theoretically possible (though unlikely) for a fast track to be created
4408 // and then removed within the same normal mix cycle. This is not a problem, as
4409 // the track never becomes active so it's fast mixer slot is never touched.
4410 // The converse, of removing an (active) track and then creating a new track
4411 // at the identical fast mixer slot within the same normal mix cycle,
4412 // is impossible because the slot isn't marked available until the end of each cycle.
4413 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004414 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004415 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4416 FastTrack *fastTrack = &state->mFastTracks[j];
4417
4418 // Determine whether the track is currently in underrun condition,
4419 // and whether it had a recent underrun.
4420 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4421 FastTrackUnderruns underruns = ftDump->mUnderruns;
4422 uint32_t recentFull = (underruns.mBitFields.mFull -
4423 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4424 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4425 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4426 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4427 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4428 uint32_t recentUnderruns = recentPartial + recentEmpty;
4429 track->mObservedUnderruns = underruns;
4430 // don't count underruns that occur while stopping or pausing
4431 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004432 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004433 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4434 recentUnderruns > 0) {
4435 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004436 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004437 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004438 // Immediately account for FastTrack underruns.
4439 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004440
4441 // This is similar to the state machine for normal tracks,
4442 // with a few modifications for fast tracks.
4443 bool isActive = true;
4444 switch (track->mState) {
4445 case TrackBase::STOPPING_1:
4446 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004447 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004448 track->mState = TrackBase::STOPPING_2;
4449 }
4450 break;
4451 case TrackBase::PAUSING:
4452 // ramp down is not yet implemented
4453 track->setPaused();
4454 break;
4455 case TrackBase::RESUMING:
4456 // ramp up is not yet implemented
4457 track->mState = TrackBase::ACTIVE;
4458 break;
4459 case TrackBase::ACTIVE:
4460 if (recentFull > 0 || recentPartial > 0) {
4461 // track has provided at least some frames recently: reset retry count
4462 track->mRetryCount = kMaxTrackRetries;
4463 }
4464 if (recentUnderruns == 0) {
4465 // no recent underruns: stay active
4466 break;
4467 }
4468 // there has recently been an underrun of some kind
4469 if (track->sharedBuffer() == 0) {
4470 // were any of the recent underruns "empty" (no frames available)?
4471 if (recentEmpty == 0) {
4472 // no, then ignore the partial underruns as they are allowed indefinitely
4473 break;
4474 }
4475 // there has recently been an "empty" underrun: decrement the retry counter
4476 if (--(track->mRetryCount) > 0) {
4477 break;
4478 }
4479 // indicate to client process that the track was disabled because of underrun;
4480 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004481 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004482 // remove from active list, but state remains ACTIVE [confusing but true]
4483 isActive = false;
4484 break;
4485 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004486 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004487 case TrackBase::STOPPING_2:
4488 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004489 case TrackBase::STOPPED:
4490 case TrackBase::FLUSHED: // flush() while active
4491 // Check for presentation complete if track is inactive
4492 // We have consumed all the buffers of this track.
4493 // This would be incomplete if we auto-paused on underrun
4494 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004495 uint32_t latency = 0;
4496 status_t result = mOutput->stream->getLatency(&latency);
4497 ALOGE_IF(result != OK,
4498 "Error when retrieving output stream latency: %d", result);
4499 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004500 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004501 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4502 // track stays in active list until presentation is complete
4503 break;
4504 }
4505 }
4506 if (track->isStopping_2()) {
4507 track->mState = TrackBase::STOPPED;
4508 }
4509 if (track->isStopped()) {
4510 // Can't reset directly, as fast mixer is still polling this track
4511 // track->reset();
4512 // So instead mark this track as needing to be reset after push with ack
4513 resetMask |= 1 << i;
4514 }
4515 isActive = false;
4516 break;
4517 case TrackBase::IDLE:
4518 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004519 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004520 }
4521
4522 if (isActive) {
4523 // was it previously inactive?
4524 if (!(state->mTrackMask & (1 << j))) {
4525 ExtendedAudioBufferProvider *eabp = track;
4526 VolumeProvider *vp = track;
4527 fastTrack->mBufferProvider = eabp;
4528 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004529 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004530 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004531 fastTrack->mGeneration++;
4532 state->mTrackMask |= 1 << j;
4533 didModify = true;
4534 // no acknowledgement required for newly active tracks
4535 }
Kevin Rocard12381092018-04-11 09:19:59 -07004536 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004537 // cache the combined master volume and stream type volume for fast mixer; this
4538 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004539 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004540 proxy->framesReleased()).first;
4541 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004542 * mStreamTypes[track->streamType()].volume
4543 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004544 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004545 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4546 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4547 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4548 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004549 ++fastTracks;
4550 } else {
4551 // was it previously active?
4552 if (state->mTrackMask & (1 << j)) {
4553 fastTrack->mBufferProvider = NULL;
4554 fastTrack->mGeneration++;
4555 state->mTrackMask &= ~(1 << j);
4556 didModify = true;
4557 // If any fast tracks were removed, we must wait for acknowledgement
4558 // because we're about to decrement the last sp<> on those tracks.
4559 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4560 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004561 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4562 // AudioTrack may start (which may not be with a start() but with a write()
4563 // after underrun) and immediately paused or released. In that case the
4564 // FastTrack state hasn't had time to update.
4565 // TODO Remove the ALOGW when this theory is confirmed.
4566 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004567 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4568 j, track->mState, state->mTrackMask, recentUnderruns,
4569 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004570 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004571 }
4572 tracksToRemove->add(track);
4573 // Avoids a misleading display in dumpsys
4574 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4575 }
4576 continue;
4577 }
4578
4579 { // local variable scope to avoid goto warning
4580
4581 audio_track_cblk_t* cblk = track->cblk();
4582
4583 // The first time a track is added we wait
4584 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004585 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004586
4587 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004588 // use the trackId as the AudioMixer name.
4589 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004590 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004591 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004592 track->mChannelMask,
4593 track->mFormat,
4594 track->mSessionId);
4595 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004596 ALOGW("%s(): AudioMixer cannot create track(%d)"
4597 " mask %#x, format %#x, sessionId %d",
4598 __func__, trackId,
4599 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004600 tracksToRemove->add(track);
4601 track->invalidate(); // consider it dead.
4602 continue;
4603 }
4604 }
4605
Eric Laurent81784c32012-11-19 14:55:58 -08004606 // make sure that we have enough frames to mix one full buffer.
4607 // enforce this condition only once to enable draining the buffer in case the client
4608 // app does not call stop() and relies on underrun to stop:
4609 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4610 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004611 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004612 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004613 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004614
4615 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004616 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004617 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4618 // add frames already consumed but not yet released by the resampler
4619 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004620 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004621
Eric Laurent81784c32012-11-19 14:55:58 -08004622 uint32_t minFrames = 1;
4623 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4624 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004625 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004626 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004627
4628 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004629 if (ATRACE_ENABLED()) {
4630 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004631 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004632 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004633 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004634 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004635 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004636 !track->isPaused() && !track->isTerminated())
4637 {
Andy Hungc0691382018-09-12 18:01:57 -07004638 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004639
4640 mixedTracks++;
4641
Andy Hung69aed5f2014-02-25 17:24:40 -08004642 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4643 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004644 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004645 if (track->mainBuffer() != mSinkBuffer &&
4646 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004647 if (mEffectBufferEnabled) {
4648 mEffectBufferValid = true; // Later can set directly.
4649 }
Eric Laurent81784c32012-11-19 14:55:58 -08004650 chain = getEffectChain_l(track->sessionId());
4651 // Delegate volume control to effect in track effect chain if needed
4652 if (chain != 0) {
4653 tracksWithEffect++;
4654 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004655 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004656 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004657 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004658 }
4659 }
4660
4661
4662 int param = AudioMixer::VOLUME;
4663 if (track->mFillingUpStatus == Track::FS_FILLED) {
4664 // no ramp for the first volume setting
4665 track->mFillingUpStatus = Track::FS_ACTIVE;
4666 if (track->mState == TrackBase::RESUMING) {
4667 track->mState = TrackBase::ACTIVE;
4668 param = AudioMixer::RAMP_VOLUME;
4669 }
Andy Hungc0691382018-09-12 18:01:57 -07004670 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004671 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004672 // FIXME should not make a decision based on mServer
4673 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004674 // If the track is stopped before the first frame was mixed,
4675 // do not apply ramp
4676 param = AudioMixer::RAMP_VOLUME;
4677 }
4678
4679 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004680 uint32_t vl, vr; // in U8.24 integer format
4681 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004682 // read original volumes with volume control
4683 float typeVolume = mStreamTypes[track->streamType()].volume;
4684 float v = masterVolume * typeVolume;
4685
Glenn Kastene4756fe2012-11-29 13:38:14 -08004686 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004687 vl = vr = 0;
4688 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004689 if (track->isPausing()) {
4690 track->setPaused();
4691 }
4692 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004693 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004694 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004695 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4696 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004697 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004698 if (vlf > GAIN_FLOAT_UNITY) {
4699 ALOGV("Track left volume out of range: %.3g", vlf);
4700 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004701 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004702 if (vrf > GAIN_FLOAT_UNITY) {
4703 ALOGV("Track right volume out of range: %.3g", vrf);
4704 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004705 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004706 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004707 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004708 // now apply the master volume and stream type volume and shaper volume
4709 vlf *= v * vh;
4710 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004711 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004712 // then derive vl and vr as U8.24 versions for the effect chain
4713 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4714 vl = (uint32_t) (scaleto8_24 * vlf);
4715 vr = (uint32_t) (scaleto8_24 * vrf);
4716 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004717 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004718 // send level comes from shared memory and so may be corrupt
4719 if (sendLevel > MAX_GAIN_INT) {
4720 ALOGV("Track send level out of range: %04X", sendLevel);
4721 sendLevel = MAX_GAIN_INT;
4722 }
Andy Hung6be49402014-05-30 10:42:03 -07004723 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4724 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004725 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004726
Kevin Rocard12381092018-04-11 09:19:59 -07004727 track->setFinalVolume((vrf + vlf) / 2.f);
4728
Eric Laurent81784c32012-11-19 14:55:58 -08004729 // Delegate volume control to effect in track effect chain if needed
4730 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4731 // Do not ramp volume if volume is controlled by effect
4732 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004733 // Update remaining floating point volume levels
4734 vlf = (float)vl / (1 << 24);
4735 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004736 track->mHasVolumeController = true;
4737 } else {
4738 // force no volume ramp when volume controller was just disabled or removed
4739 // from effect chain to avoid volume spike
4740 if (track->mHasVolumeController) {
4741 param = AudioMixer::VOLUME;
4742 }
4743 track->mHasVolumeController = false;
4744 }
4745
Eric Laurent7c29ec92017-09-20 17:54:22 -07004746 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4747 // still applied by the mixer.
4748 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4749 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4750 if (v != mLeftVolFloat) {
4751 status_t result = mOutput->stream->setVolume(v, v);
4752 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4753 if (result == OK) {
4754 mLeftVolFloat = v;
4755 }
4756 }
4757 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4758 // remove stream volume contribution from software volume.
4759 if (v != 0.0f && mLeftVolFloat == v) {
4760 vlf = min(1.0f, vlf / v);
4761 vrf = min(1.0f, vrf / v);
4762 vaf = min(1.0f, vaf / v);
4763 }
4764 }
Eric Laurent81784c32012-11-19 14:55:58 -08004765 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07004766 mAudioMixer->setBufferProvider(trackId, track);
4767 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004768
Andy Hungc0691382018-09-12 18:01:57 -07004769 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
4770 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
4771 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004772 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004773 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004774 AudioMixer::TRACK,
4775 AudioMixer::FORMAT, (void *)track->format());
4776 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004777 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004778 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004779 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004780 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004781 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07004782 AudioMixer::TRACK,
4783 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004784 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004785 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004786 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004787 if (reqSampleRate == 0) {
4788 reqSampleRate = mSampleRate;
4789 } else if (reqSampleRate > maxSampleRate) {
4790 reqSampleRate = maxSampleRate;
4791 }
Eric Laurent81784c32012-11-19 14:55:58 -08004792 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004793 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004794 AudioMixer::RESAMPLE,
4795 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004796 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004797
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004798 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004799 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004800 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07004801 AudioMixer::TIMESTRETCH,
4802 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004803 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004804
Andy Hung69aed5f2014-02-25 17:24:40 -08004805 /*
4806 * Select the appropriate output buffer for the track.
4807 *
Andy Hung98ef9782014-03-04 14:46:50 -08004808 * Tracks with effects go into their own effects chain buffer
4809 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004810 *
4811 * Other tracks can use mMixerBuffer for higher precision
4812 * channel accumulation. If this buffer is enabled
4813 * (mMixerBufferEnabled true), then selected tracks will accumulate
4814 * into it.
4815 *
4816 */
4817 if (mMixerBufferEnabled
4818 && (track->mainBuffer() == mSinkBuffer
4819 || track->mainBuffer() == mMixerBuffer)) {
4820 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004821 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004822 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004823 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004824 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004825 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004826 AudioMixer::TRACK,
4827 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4828 // TODO: override track->mainBuffer()?
4829 mMixerBufferValid = true;
4830 } else {
4831 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004832 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004833 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004834 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004835 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004836 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004837 AudioMixer::TRACK,
4838 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4839 }
Eric Laurent81784c32012-11-19 14:55:58 -08004840 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004841 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004842 AudioMixer::TRACK,
4843 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4844
4845 // reset retry count
4846 track->mRetryCount = kMaxTrackRetries;
4847
4848 // If one track is ready, set the mixer ready if:
4849 // - the mixer was not ready during previous round OR
4850 // - no other track is not ready
4851 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4852 mixerStatus != MIXER_TRACKS_ENABLED) {
4853 mixerStatus = MIXER_TRACKS_READY;
4854 }
4855 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004856 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004857 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07004858 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
4859 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004860 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004861 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004862 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004863
Eric Laurent81784c32012-11-19 14:55:58 -08004864 // clear effect chain input buffer if an active track underruns to avoid sending
4865 // previous audio buffer again to effects
4866 chain = getEffectChain_l(track->sessionId());
4867 if (chain != 0) {
4868 chain->clearInputBuffer();
4869 }
4870
Andy Hungc0691382018-09-12 18:01:57 -07004871 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004872 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4873 track->isStopped() || track->isPaused()) {
4874 // We have consumed all the buffers of this track.
4875 // Remove it from the list of active tracks.
4876 // TODO: use actual buffer filling status instead of latency when available from
4877 // audio HAL
4878 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004879 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004880 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4881 if (track->isStopped()) {
4882 track->reset();
4883 }
4884 tracksToRemove->add(track);
4885 }
4886 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004887 // No buffers for this track. Give it a few chances to
4888 // fill a buffer, then remove it from active list.
4889 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07004890 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
4891 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004892 tracksToRemove->add(track);
4893 // indicate to client process that the track was disabled because of underrun;
4894 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004895 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004896 // If one track is not ready, mark the mixer also not ready if:
4897 // - the mixer was ready during previous round OR
4898 // - no other track is ready
4899 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4900 mixerStatus != MIXER_TRACKS_READY) {
4901 mixerStatus = MIXER_TRACKS_ENABLED;
4902 }
4903 }
Andy Hungc0691382018-09-12 18:01:57 -07004904 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004905 }
4906
4907 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004908
4909 }
4910
4911 // Push the new FastMixer state if necessary
4912 bool pauseAudioWatchdog = false;
4913 if (didModify) {
4914 state->mFastTracksGen++;
4915 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4916 if (kUseFastMixer == FastMixer_Dynamic &&
4917 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4918 state->mCommand = FastMixerState::COLD_IDLE;
4919 state->mColdFutexAddr = &mFastMixerFutex;
4920 state->mColdGen++;
4921 mFastMixerFutex = 0;
4922 if (kUseFastMixer == FastMixer_Dynamic) {
4923 mNormalSink = mOutputSink;
4924 }
4925 // If we go into cold idle, need to wait for acknowledgement
4926 // so that fast mixer stops doing I/O.
4927 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4928 pauseAudioWatchdog = true;
4929 }
Eric Laurent81784c32012-11-19 14:55:58 -08004930 }
4931 if (sq != NULL) {
4932 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004933 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4934 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4935 // when bringing the output sink into standby.)
4936 //
4937 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4938 //
4939 // This occurs with BT suspend when we idle the FastMixer with
4940 // active tracks, which may be added or removed.
4941 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004942 }
4943#ifdef AUDIO_WATCHDOG
4944 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4945 mAudioWatchdog->pause();
4946 }
4947#endif
4948
4949 // Now perform the deferred reset on fast tracks that have stopped
4950 while (resetMask != 0) {
4951 size_t i = __builtin_ctz(resetMask);
4952 ALOG_ASSERT(i < count);
4953 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004954 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004955 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4956 track->reset();
4957 }
4958
Andy Hung80d03d22018-04-10 10:32:11 -07004959 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4960 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4961 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4962 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4963 // See also the implementation of destroyTrack_l().
4964 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07004965 const int trackId = track->id();
4966 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
4967 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07004968 }
4969 }
4970
Eric Laurent81784c32012-11-19 14:55:58 -08004971 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004972 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004973
Eric Laurent97d547d2014-09-02 14:45:53 -07004974 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4975 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004976 }
4977
4978 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004979 // as long as there are effects we should clear the effects buffer, to avoid
4980 // passing a non-clean buffer to the effect chain
4981 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004982 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004983 // sink or mix buffer must be cleared if all tracks are connected to an
4984 // effect chain as in this case the mixer will not write to the sink or mix buffer
4985 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004986 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4987 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004988 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004989 if (mMixerBufferValid) {
4990 memset(mMixerBuffer, 0, mMixerBufferSize);
4991 // TODO: In testing, mSinkBuffer below need not be cleared because
4992 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4993 // after mixing.
4994 //
4995 // To enforce this guarantee:
4996 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4997 // (mixedTracks == 0 && fastTracks > 0))
4998 // must imply MIXER_TRACKS_READY.
4999 // Later, we may clear buffers regardless, and skip much of this logic.
5000 }
Andy Hung98ef9782014-03-04 14:46:50 -08005001 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005002 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005003 }
5004
5005 // if any fast tracks, then status is ready
5006 mMixerStatusIgnoringFastTracks = mixerStatus;
5007 if (fastTracks > 0) {
5008 mixerStatus = MIXER_TRACKS_READY;
5009 }
5010 return mixerStatus;
5011}
5012
Eric Laurentad7dd962016-09-22 12:38:37 -07005013// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005014uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005015{
5016 uint32_t trackCount = 0;
5017 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005018 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005019 trackCount++;
5020 }
5021 }
5022 return trackCount;
5023}
5024
Andy Hung1bc088a2018-02-09 15:57:31 -08005025// isTrackAllowed_l() must be called with ThreadBase::mLock held
5026bool AudioFlinger::MixerThread::isTrackAllowed_l(
5027 audio_channel_mask_t channelMask, audio_format_t format,
5028 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005029{
Andy Hung1bc088a2018-02-09 15:57:31 -08005030 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5031 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005032 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005033 // Check validity as we don't call AudioMixer::create() here.
5034 if (!AudioMixer::isValidFormat(format)) {
5035 ALOGW("%s: invalid format: %#x", __func__, format);
5036 return false;
5037 }
5038 if (!AudioMixer::isValidChannelMask(channelMask)) {
5039 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5040 return false;
5041 }
5042 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005043}
5044
Eric Laurent10351942014-05-08 18:49:52 -07005045// checkForNewParameter_l() must be called with ThreadBase::mLock held
5046bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5047 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005048{
Eric Laurent81784c32012-11-19 14:55:58 -08005049 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005050 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005051
Eric Laurent10351942014-05-08 18:49:52 -07005052 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005053
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005054 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005055
Eric Laurent10351942014-05-08 18:49:52 -07005056 AudioParameter param = AudioParameter(keyValuePair);
5057 int value;
5058 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5059 reconfig = true;
5060 }
5061 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005062 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005063 status = BAD_VALUE;
5064 } else {
5065 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005066 reconfig = true;
5067 }
Eric Laurent10351942014-05-08 18:49:52 -07005068 }
5069 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005070 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005071 status = BAD_VALUE;
5072 } else {
5073 // no need to save value, since it's constant
5074 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005075 }
Eric Laurent10351942014-05-08 18:49:52 -07005076 }
5077 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5078 // do not accept frame count changes if tracks are open as the track buffer
5079 // size depends on frame count and correct behavior would not be guaranteed
5080 // if frame count is changed after track creation
5081 if (!mTracks.isEmpty()) {
5082 status = INVALID_OPERATION;
5083 } else {
5084 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005085 }
Eric Laurent10351942014-05-08 18:49:52 -07005086 }
5087 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005088#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005089 // when changing the audio output device, call addBatteryData to notify
5090 // the change
5091 if (mOutDevice != value) {
5092 uint32_t params = 0;
5093 // check whether speaker is on
5094 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5095 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005096 }
Eric Laurent10351942014-05-08 18:49:52 -07005097
5098 audio_devices_t deviceWithoutSpeaker
5099 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5100 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005101 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005102 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5103 }
5104
5105 if (params != 0) {
5106 addBatteryData(params);
5107 }
5108 }
Eric Laurent81784c32012-11-19 14:55:58 -08005109#endif
5110
Eric Laurent10351942014-05-08 18:49:52 -07005111 // forward device change to effects that have requested to be
5112 // aware of attached audio device.
5113 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005114 a2dpDeviceChanged =
5115 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005116 mOutDevice = value;
5117 for (size_t i = 0; i < mEffectChains.size(); i++) {
5118 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005119 }
5120 }
Eric Laurent10351942014-05-08 18:49:52 -07005121 }
Eric Laurent81784c32012-11-19 14:55:58 -08005122
Eric Laurent10351942014-05-08 18:49:52 -07005123 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005124 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005125 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005126 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005127 mStandby = true;
5128 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005129 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005130 }
Eric Laurent10351942014-05-08 18:49:52 -07005131 if (status == NO_ERROR && reconfig) {
5132 readOutputParameters_l();
5133 delete mAudioMixer;
5134 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005135 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005136 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005137 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005138 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005139 track->mChannelMask,
5140 track->mFormat,
5141 track->mSessionId);
5142 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005143 "%s(): AudioMixer cannot create track(%d)"
5144 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005145 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005146 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005147 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005148 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005149 }
Eric Laurent81784c32012-11-19 14:55:58 -08005150 }
5151
Eric Laurent42537be2016-01-08 17:16:42 -08005152 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005153}
5154
5155
5156void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5157{
Eric Laurent81784c32012-11-19 14:55:58 -08005158 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005159 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005160 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005161 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005162 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005163 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005164 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005165 } else {
5166 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005167 }
Eric Laurent81784c32012-11-19 14:55:58 -08005168
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005169 if (hasFastMixer()) {
5170 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5171
5172 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5173 // while we are dumping it. It may be inconsistent, but it won't mutate!
5174 // This is a large object so we place it on the heap.
5175 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005176 const std::unique_ptr<FastMixerDumpState> copy =
5177 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005178 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005179
5180#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005181 // Similar for state queue
5182 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5183 observerCopy.dump(fd);
5184 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5185 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005186#endif
5187
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005188#ifdef AUDIO_WATCHDOG
5189 if (mAudioWatchdog != 0) {
5190 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5191 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5192 wdCopy.dump(fd);
5193 }
5194#endif
5195
5196 } else {
5197 dprintf(fd, " No FastMixer\n");
5198 }
Eric Laurent81784c32012-11-19 14:55:58 -08005199}
5200
5201uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5202{
5203 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5204}
5205
5206uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5207{
5208 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5209}
5210
5211void AudioFlinger::MixerThread::cacheParameters_l()
5212{
5213 PlaybackThread::cacheParameters_l();
5214
5215 // FIXME: Relaxed timing because of a certain device that can't meet latency
5216 // Should be reduced to 2x after the vendor fixes the driver issue
5217 // increase threshold again due to low power audio mode. The way this warning
5218 // threshold is calculated and its usefulness should be reconsidered anyway.
5219 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5220}
5221
5222// ----------------------------------------------------------------------------
5223
5224AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005225 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5226 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005227{
5228}
5229
Eric Laurentbfb1b832013-01-07 09:53:42 -08005230AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5231 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005232 ThreadBase::type_t type, bool systemReady)
5233 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005234 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235{
5236}
5237
Eric Laurent81784c32012-11-19 14:55:58 -08005238AudioFlinger::DirectOutputThread::~DirectOutputThread()
5239{
5240}
5241
Eric Laurent5850c4c2016-11-10 13:04:31 -08005242void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005243{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005244 float left, right;
5245
5246 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5247 left = right = 0;
5248 } else {
5249 float typeVolume = mStreamTypes[track->streamType()].volume;
5250 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005251 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005252
Andy Hung10cbff12017-02-21 17:30:14 -08005253 // Get volumeshaper scaling
5254 std::pair<float /* volume */, bool /* active */>
5255 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005256 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005257 v *= vh.first;
5258 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005259
Glenn Kastenc56f3422014-03-21 17:53:17 -07005260 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5261 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5262 if (left > GAIN_FLOAT_UNITY) {
5263 left = GAIN_FLOAT_UNITY;
5264 }
5265 left *= v;
5266 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5267 if (right > GAIN_FLOAT_UNITY) {
5268 right = GAIN_FLOAT_UNITY;
5269 }
5270 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005271 }
5272
5273 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005274 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005275 if (left != mLeftVolFloat || right != mRightVolFloat) {
5276 mLeftVolFloat = left;
5277 mRightVolFloat = right;
5278
Eric Laurentbfb1b832013-01-07 09:53:42 -08005279 // Delegate volume control to effect in track effect chain if needed
5280 // only one effect chain can be present on DirectOutputThread, so if
5281 // there is one, the track is connected to it
5282 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005283 // if effect chain exists, volume is handled by it.
5284 // Convert volumes from float to 8.24
5285 uint32_t vl = (uint32_t)(left * (1 << 24));
5286 uint32_t vr = (uint32_t)(right * (1 << 24));
5287 // Direct/Offload effect chains set output volume in setVolume_l().
5288 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5289 } else {
5290 // otherwise we directly set the volume.
5291 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005292 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005293 }
5294 }
5295}
5296
Phil Burk43b4dcc2015-06-09 16:53:44 -07005297void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5298{
5299 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005300 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005301
Eric Laurent0f0631e2015-07-06 18:01:25 -07005302 if (previousTrack != 0 && latestTrack != 0) {
5303 if (mType == DIRECT) {
5304 if (previousTrack.get() != latestTrack.get()) {
5305 mFlushPending = true;
5306 }
5307 } else /* mType == OFFLOAD */ {
5308 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5309 mFlushPending = true;
5310 }
5311 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005312 }
5313 PlaybackThread::onAddNewTrack_l();
5314}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005315
Eric Laurent81784c32012-11-19 14:55:58 -08005316AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5317 Vector< sp<Track> > *tracksToRemove
5318)
5319{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005320 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005321 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005322 bool doHwPause = false;
5323 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005324
5325 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005326 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005327 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005328 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005329 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005330 continue;
5331 }
5332
Eric Laurent5850c4c2016-11-10 13:04:31 -08005333 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005334#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005335 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005336#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005337 // Only consider last track started for volume and mixer state control.
5338 // In theory an older track could underrun and restart after the new one starts
5339 // but as we only care about the transition phase between two tracks on a
5340 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005341 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005342 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005343
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005344 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005345 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005346 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005347 doHwPause = true;
5348 mHwPaused = true;
5349 }
5350 tracksToRemove->add(track);
5351 } else if (track->isFlushPending()) {
5352 track->flushAck();
5353 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005354 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005355 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005356 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005357 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005358 if (last) {
5359 mLeftVolFloat = mRightVolFloat = -1.0;
5360 if (mHwPaused) {
5361 doHwResume = true;
5362 mHwPaused = false;
5363 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005364 }
5365 }
5366
Eric Laurent81784c32012-11-19 14:55:58 -08005367 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005368 // for all its buffers to be filled before processing it.
5369 // Allow draining the buffer in case the client
5370 // app does not call stop() and relies on underrun to stop:
5371 // hence the test on (track->mRetryCount > 1).
5372 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005373 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005374 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005375 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005376 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005377 minFrames = mNormalFrameCount;
5378 } else {
5379 minFrames = 1;
5380 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005381
Eric Laurentab5cdba2014-06-09 17:22:27 -07005382 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5383 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005384 {
Andy Hungc0691382018-09-12 18:01:57 -07005385 ALOGVV("track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005386
5387 if (track->mFillingUpStatus == Track::FS_FILLED) {
5388 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005389 if (last) {
5390 // make sure processVolume_l() will apply new volume even if 0
5391 mLeftVolFloat = mRightVolFloat = -1.0;
5392 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005393 if (!mHwSupportsPause) {
5394 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005395 }
5396 }
5397
5398 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005399 processVolume_l(track, last);
5400 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005401 sp<Track> previousTrack = mPreviousTrack.promote();
5402 if (previousTrack != 0) {
5403 if (track != previousTrack.get()) {
5404 // Flush any data still being written from last track
5405 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005406 // Invalidate previous track to force a seek when resuming.
5407 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005408 }
5409 }
5410 mPreviousTrack = track;
5411
Eric Laurentd595b7c2013-04-03 17:27:56 -07005412 // reset retry count
5413 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005414 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005415 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005416 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005417 doHwResume = true;
5418 mHwPaused = false;
5419 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005420 }
Eric Laurent81784c32012-11-19 14:55:58 -08005421 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005422 // clear effect chain input buffer if the last active track started underruns
5423 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005424 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005425 mEffectChains[0]->clearInputBuffer();
5426 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005427 if (track->isStopping_1()) {
5428 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005429 if (last && mHwPaused) {
5430 doHwResume = true;
5431 mHwPaused = false;
5432 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005433 }
5434 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5435 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005436 // We have consumed all the buffers of this track.
5437 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005438 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005439 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005440 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5441 } else {
5442 audioHALFrames = 0;
5443 }
5444
Andy Hung818e7a32016-02-16 18:08:07 -08005445 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005446 if (mStandby || !last ||
5447 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005448 if (track->isStopping_2()) {
5449 track->mState = TrackBase::STOPPED;
5450 }
Eric Laurent81784c32012-11-19 14:55:58 -08005451 if (track->isStopped()) {
5452 track->reset();
5453 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005454 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005455 }
5456 } else {
5457 // No buffers for this track. Give it a few chances to
5458 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005459 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005460 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005461 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", track->id());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005462 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005463 // indicate to client process that the track was disabled because of underrun;
5464 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005465 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005466 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005467 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5468 "minFrames = %u, mFormat = %#x",
5469 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005470 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005471 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005472 doHwPause = true;
5473 mHwPaused = true;
5474 }
Eric Laurent81784c32012-11-19 14:55:58 -08005475 }
5476 }
5477 }
5478 }
5479
Eric Laurentd1f69b02014-12-15 14:33:13 -08005480 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005481 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005482 for (size_t i = 0; i < mTracks.size(); i++) {
5483 if (mTracks[i]->isFlushPending()) {
5484 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005485 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005486 }
5487 }
5488 }
5489
5490 // make sure the pause/flush/resume sequence is executed in the right order.
5491 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5492 // before flush and then resume HW. This can happen in case of pause/flush/resume
5493 // if resume is received before pause is executed.
5494 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005495 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005496 status_t result = mOutput->stream->pause();
5497 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005498 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005499 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005500 flushHw_l();
5501 }
5502 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005503 status_t result = mOutput->stream->resume();
5504 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005505 }
Eric Laurent81784c32012-11-19 14:55:58 -08005506 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005507 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005508
5509 return mixerStatus;
5510}
5511
5512void AudioFlinger::DirectOutputThread::threadLoop_mix()
5513{
Eric Laurent81784c32012-11-19 14:55:58 -08005514 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005515 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005516 // output audio to hardware
5517 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005518 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005519 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005520 status_t status = mActiveTrack->getNextBuffer(&buffer);
5521 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005522 // no need to pad with 0 for compressed audio
5523 if (audio_has_proportional_frames(mFormat)) {
5524 memset(curBuf, 0, frameCount * mFrameSize);
5525 }
Eric Laurent81784c32012-11-19 14:55:58 -08005526 break;
5527 }
5528 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5529 frameCount -= buffer.frameCount;
5530 curBuf += buffer.frameCount * mFrameSize;
5531 mActiveTrack->releaseBuffer(&buffer);
5532 }
Andy Hung2098f272014-02-27 14:00:06 -08005533 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005534 mSleepTimeUs = 0;
5535 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005536 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005537}
5538
5539void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5540{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005541 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005542 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005543 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005544 return;
5545 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005546 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005547 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005548 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005549 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005550 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005551 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005552 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005553 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005554 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005555 }
5556}
5557
Eric Laurentd1f69b02014-12-15 14:33:13 -08005558void AudioFlinger::DirectOutputThread::threadLoop_exit()
5559{
5560 {
5561 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005562 for (size_t i = 0; i < mTracks.size(); i++) {
5563 if (mTracks[i]->isFlushPending()) {
5564 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005565 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005566 }
5567 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005568 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005569 flushHw_l();
5570 }
5571 }
5572 PlaybackThread::threadLoop_exit();
5573}
5574
5575// must be called with thread mutex locked
5576bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5577{
5578 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005579 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005580
vivek mehta9cd7ad12016-03-17 00:18:29 -07005581 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5582 return !mStandby;
5583 }
5584
Eric Laurentd1f69b02014-12-15 14:33:13 -08005585 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5586 // after a timeout and we will enter standby then.
5587 if (mTracks.size() > 0) {
5588 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005589 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5590 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005591 }
5592
Eric Laurent5cff4032015-05-26 13:49:58 -07005593 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005594}
5595
Eric Laurent10351942014-05-08 18:49:52 -07005596// checkForNewParameter_l() must be called with ThreadBase::mLock held
5597bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5598 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005599{
5600 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005601 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005602
Eric Laurent10351942014-05-08 18:49:52 -07005603 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005604
Eric Laurent10351942014-05-08 18:49:52 -07005605 AudioParameter param = AudioParameter(keyValuePair);
5606 int value;
5607 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5608 // forward device change to effects that have requested to be
5609 // aware of attached audio device.
5610 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005611 a2dpDeviceChanged =
5612 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005613 mOutDevice = value;
5614 for (size_t i = 0; i < mEffectChains.size(); i++) {
5615 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005616 }
5617 }
Eric Laurent81784c32012-11-19 14:55:58 -08005618 }
Eric Laurent10351942014-05-08 18:49:52 -07005619 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5620 // do not accept frame count changes if tracks are open as the track buffer
5621 // size depends on frame count and correct behavior would not be garantied
5622 // if frame count is changed after track creation
5623 if (!mTracks.isEmpty()) {
5624 status = INVALID_OPERATION;
5625 } else {
5626 reconfig = true;
5627 }
5628 }
5629 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005630 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005631 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005632 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005633 mStandby = true;
5634 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005635 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005636 }
5637 if (status == NO_ERROR && reconfig) {
5638 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005639 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005640 }
5641 }
5642
Eric Laurent42537be2016-01-08 17:16:42 -08005643 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005644}
5645
5646uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5647{
5648 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005649 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005650 time = PlaybackThread::activeSleepTimeUs();
5651 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005652 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005653 }
5654 return time;
5655}
5656
5657uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5658{
5659 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005660 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005661 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5662 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005663 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005664 }
5665 return time;
5666}
5667
5668uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5669{
5670 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005671 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005672 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5673 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005674 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005675 }
5676 return time;
5677}
5678
5679void AudioFlinger::DirectOutputThread::cacheParameters_l()
5680{
5681 PlaybackThread::cacheParameters_l();
5682
5683 // use shorter standby delay as on normal output to release
5684 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005685 // no delay on outputs with HW A/V sync
5686 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005687 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005688 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005689 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005690 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005691 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005692 }
Eric Laurent81784c32012-11-19 14:55:58 -08005693}
5694
Eric Laurente659ef42014-09-29 13:06:46 -07005695void AudioFlinger::DirectOutputThread::flushHw_l()
5696{
Phil Burk062e67a2015-02-11 13:40:50 -08005697 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005698 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005699 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005700 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005701}
5702
Andy Hung10cbff12017-02-21 17:30:14 -08005703int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5704 // If a VolumeShaper is active, we must wake up periodically to update volume.
5705 const int64_t NS_PER_MS = 1000000;
5706 return mVolumeShaperActive ?
5707 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5708}
5709
Eric Laurent81784c32012-11-19 14:55:58 -08005710// ----------------------------------------------------------------------------
5711
Eric Laurentbfb1b832013-01-07 09:53:42 -08005712AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005713 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005714 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005715 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005716 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005717 mDrainSequence(0),
5718 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005719{
5720}
5721
5722AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5723{
5724}
5725
5726void AudioFlinger::AsyncCallbackThread::onFirstRef()
5727{
5728 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5729}
5730
5731bool AudioFlinger::AsyncCallbackThread::threadLoop()
5732{
5733 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005734 uint32_t writeAckSequence;
5735 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005736 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005737
5738 {
5739 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005740 while (!((mWriteAckSequence & 1) ||
5741 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005742 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005743 exitPending())) {
5744 mWaitWorkCV.wait(mLock);
5745 }
5746
Eric Laurentbfb1b832013-01-07 09:53:42 -08005747 if (exitPending()) {
5748 break;
5749 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005750 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5751 mWriteAckSequence, mDrainSequence);
5752 writeAckSequence = mWriteAckSequence;
5753 mWriteAckSequence &= ~1;
5754 drainSequence = mDrainSequence;
5755 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005756 asyncError = mAsyncError;
5757 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005758 }
5759 {
Eric Laurent4de95592013-09-26 15:28:21 -07005760 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5761 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005762 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005763 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005764 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005765 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005766 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005767 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005768 if (asyncError) {
5769 playbackThread->onAsyncError();
5770 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005771 }
5772 }
5773 }
5774 return false;
5775}
5776
5777void AudioFlinger::AsyncCallbackThread::exit()
5778{
5779 ALOGV("AsyncCallbackThread::exit");
5780 Mutex::Autolock _l(mLock);
5781 requestExit();
5782 mWaitWorkCV.broadcast();
5783}
5784
Eric Laurent3b4529e2013-09-05 18:09:19 -07005785void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005786{
5787 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005788 // bit 0 is cleared
5789 mWriteAckSequence = sequence << 1;
5790}
5791
5792void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5793{
5794 Mutex::Autolock _l(mLock);
5795 // ignore unexpected callbacks
5796 if (mWriteAckSequence & 2) {
5797 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005798 mWaitWorkCV.signal();
5799 }
5800}
5801
Eric Laurent3b4529e2013-09-05 18:09:19 -07005802void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005803{
5804 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005805 // bit 0 is cleared
5806 mDrainSequence = sequence << 1;
5807}
5808
5809void AudioFlinger::AsyncCallbackThread::resetDraining()
5810{
5811 Mutex::Autolock _l(mLock);
5812 // ignore unexpected callbacks
5813 if (mDrainSequence & 2) {
5814 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005815 mWaitWorkCV.signal();
5816 }
5817}
5818
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005819void AudioFlinger::AsyncCallbackThread::setAsyncError()
5820{
5821 Mutex::Autolock _l(mLock);
5822 mAsyncError = true;
5823 mWaitWorkCV.signal();
5824}
5825
Eric Laurentbfb1b832013-01-07 09:53:42 -08005826
5827// ----------------------------------------------------------------------------
5828AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005829 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5830 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005831 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5832 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005833{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005834 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005835 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005836 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005837}
5838
Eric Laurentbfb1b832013-01-07 09:53:42 -08005839void AudioFlinger::OffloadThread::threadLoop_exit()
5840{
5841 if (mFlushPending || mHwPaused) {
5842 // If a flush is pending or track was paused, just discard buffered data
5843 flushHw_l();
5844 } else {
5845 mMixerStatus = MIXER_DRAIN_ALL;
5846 threadLoop_drain();
5847 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005848 if (mUseAsyncWrite) {
5849 ALOG_ASSERT(mCallbackThread != 0);
5850 mCallbackThread->exit();
5851 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005852 PlaybackThread::threadLoop_exit();
5853}
5854
5855AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5856 Vector< sp<Track> > *tracksToRemove
5857)
5858{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005859 size_t count = mActiveTracks.size();
5860
5861 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005862 bool doHwPause = false;
5863 bool doHwResume = false;
5864
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005865 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005866
Eric Laurentbfb1b832013-01-07 09:53:42 -08005867 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005868 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005869 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005870#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005871 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005872#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005873 // Only consider last track started for volume and mixer state control.
5874 // In theory an older track could underrun and restart after the new one starts
5875 // but as we only care about the transition phase between two tracks on a
5876 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005877 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005878 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005879
Haynes Mathew George7844f672014-01-15 12:32:55 -08005880 if (track->isInvalid()) {
5881 ALOGW("An invalidated track shouldn't be in active list");
5882 tracksToRemove->add(track);
5883 continue;
5884 }
5885
5886 if (track->mState == TrackBase::IDLE) {
5887 ALOGW("An idle track shouldn't be in active list");
5888 continue;
5889 }
5890
Eric Laurentbfb1b832013-01-07 09:53:42 -08005891 if (track->isPausing()) {
5892 track->setPaused();
5893 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005894 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005895 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005896 mHwPaused = true;
5897 }
5898 // If we were part way through writing the mixbuffer to
5899 // the HAL we must save this until we resume
5900 // BUG - this will be wrong if a different track is made active,
5901 // in that case we want to discard the pending data in the
5902 // mixbuffer and tell the client to present it again when the
5903 // track is resumed
5904 mPausedWriteLength = mCurrentWriteLength;
5905 mPausedBytesRemaining = mBytesRemaining;
5906 mBytesRemaining = 0; // stop writing
5907 }
5908 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005909 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005910 if (track->isStopping_1()) {
5911 track->mRetryCount = kMaxTrackStopRetriesOffload;
5912 } else {
5913 track->mRetryCount = kMaxTrackRetriesOffload;
5914 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005915 track->flushAck();
5916 if (last) {
5917 mFlushPending = true;
5918 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005919 } else if (track->isResumePending()){
5920 track->resumeAck();
5921 if (last) {
5922 if (mPausedBytesRemaining) {
5923 // Need to continue write that was interrupted
5924 mCurrentWriteLength = mPausedWriteLength;
5925 mBytesRemaining = mPausedBytesRemaining;
5926 mPausedBytesRemaining = 0;
5927 }
5928 if (mHwPaused) {
5929 doHwResume = true;
5930 mHwPaused = false;
5931 // threadLoop_mix() will handle the case that we need to
5932 // resume an interrupted write
5933 }
5934 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005935 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005936
Eric Laurent3df841a2016-07-15 15:15:40 -07005937 mLeftVolFloat = mRightVolFloat = -1.0;
5938
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005939 // Do not handle new data in this iteration even if track->framesReady()
5940 mixerStatus = MIXER_TRACKS_ENABLED;
5941 }
5942 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005943 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07005944 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005945 if (track->mFillingUpStatus == Track::FS_FILLED) {
5946 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005947 if (last) {
5948 // make sure processVolume_l() will apply new volume even if 0
5949 mLeftVolFloat = mRightVolFloat = -1.0;
5950 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005951 }
5952
5953 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005954 sp<Track> previousTrack = mPreviousTrack.promote();
5955 if (previousTrack != 0) {
5956 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005957 // Flush any data still being written from last track
5958 mBytesRemaining = 0;
5959 if (mPausedBytesRemaining) {
5960 // Last track was paused so we also need to flush saved
5961 // mixbuffer state and invalidate track so that it will
5962 // re-submit that unwritten data when it is next resumed
5963 mPausedBytesRemaining = 0;
5964 // Invalidate is a bit drastic - would be more efficient
5965 // to have a flag to tell client that some of the
5966 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005967 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005968 }
5969 // flush data already sent to the DSP if changing audio session as audio
5970 // comes from a different source. Also invalidate previous track to force a
5971 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005972 if (previousTrack->sessionId() != track->sessionId()) {
5973 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005974 }
5975 }
5976 }
5977 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005978 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005979 if (track->isStopping_1()) {
5980 track->mRetryCount = kMaxTrackStopRetriesOffload;
5981 } else {
5982 track->mRetryCount = kMaxTrackRetriesOffload;
5983 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005984 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005985 mixerStatus = MIXER_TRACKS_READY;
5986 }
5987 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005988 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005989 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005990 if (--(track->mRetryCount) <= 0) {
5991 // Hardware buffer can hold a large amount of audio so we must
5992 // wait for all current track's data to drain before we say
5993 // that the track is stopped.
5994 if (mBytesRemaining == 0) {
5995 // Only start draining when all data in mixbuffer
5996 // has been written
5997 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5998 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5999 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6000 if (last && !mStandby) {
6001 // do not modify drain sequence if we are already draining. This happens
6002 // when resuming from pause after drain.
6003 if ((mDrainSequence & 1) == 0) {
6004 mSleepTimeUs = 0;
6005 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6006 mixerStatus = MIXER_DRAIN_TRACK;
6007 mDrainSequence += 2;
6008 }
6009 if (mHwPaused) {
6010 // It is possible to move from PAUSED to STOPPING_1 without
6011 // a resume so we must ensure hardware is running
6012 doHwResume = true;
6013 mHwPaused = false;
6014 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006015 }
6016 }
Eric Laurente93cc032016-05-05 10:15:10 -07006017 } else if (last) {
6018 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6019 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006020 }
6021 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006022 // Drain has completed or we are in standby, signal presentation complete
6023 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006024 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006025 uint32_t latency = 0;
6026 status_t result = mOutput->stream->getLatency(&latency);
6027 ALOGE_IF(result != OK,
6028 "Error when retrieving output stream latency: %d", result);
6029 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006030 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006031 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006032 track->presentationComplete(framesWritten, audioHALFrames);
6033 track->reset();
6034 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006035 // DIRECT and OFFLOADED stop resets frame counts.
6036 if (!mUseAsyncWrite) {
6037 // If we don't get explicit drain notification we must
6038 // register discontinuity regardless of whether this is
6039 // the previous (!last) or the upcoming (last) track
6040 // to avoid skipping the discontinuity.
6041 mTimestampVerifier.discontinuity();
6042 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006043 }
6044 } else {
6045 // No buffers for this track. Give it a few chances to
6046 // fill a buffer, then remove it from active list.
6047 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006048 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006049 uint64_t position = 0;
6050 struct timespec unused;
6051 // The running check restarts the retry counter at least once.
6052 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6053 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6054 running = true;
6055 mOffloadUnderrunPosition = position;
6056 }
6057 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006058 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6059 (long long)position, (long long)mOffloadUnderrunPosition);
6060 }
6061 if (running) { // still running, give us more time.
6062 track->mRetryCount = kMaxTrackRetriesOffload;
6063 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006064 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6065 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006066 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006067 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006068 // it will then automatically call start() when data is available
6069 track->disable();
6070 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006071 } else if (last){
6072 mixerStatus = MIXER_TRACKS_ENABLED;
6073 }
6074 }
6075 }
6076 // compute volume for this track
6077 processVolume_l(track, last);
6078 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006079
Eric Laurentea0fade2013-10-04 16:23:48 -07006080 // make sure the pause/flush/resume sequence is executed in the right order.
6081 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6082 // before flush and then resume HW. This can happen in case of pause/flush/resume
6083 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006084 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006085 status_t result = mOutput->stream->pause();
6086 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006087 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006088 if (mFlushPending) {
6089 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006090 }
Eric Laurentfd477972013-10-25 18:10:40 -07006091 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006092 status_t result = mOutput->stream->resume();
6093 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006094 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006095
Eric Laurentbfb1b832013-01-07 09:53:42 -08006096 // remove all the tracks that need to be...
6097 removeTracks_l(*tracksToRemove);
6098
6099 return mixerStatus;
6100}
6101
Eric Laurentbfb1b832013-01-07 09:53:42 -08006102// must be called with thread mutex locked
6103bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6104{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006105 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6106 mWriteAckSequence, mDrainSequence);
6107 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006108 return true;
6109 }
6110 return false;
6111}
6112
Eric Laurentbfb1b832013-01-07 09:53:42 -08006113bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6114{
6115 Mutex::Autolock _l(mLock);
6116 return waitingAsyncCallback_l();
6117}
6118
6119void AudioFlinger::OffloadThread::flushHw_l()
6120{
Eric Laurente659ef42014-09-29 13:06:46 -07006121 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006122 // Flush anything still waiting in the mixbuffer
6123 mCurrentWriteLength = 0;
6124 mBytesRemaining = 0;
6125 mPausedWriteLength = 0;
6126 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006127 // reset bytes written count to reflect that DSP buffers are empty after flush.
6128 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006129 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006130
Eric Laurentbfb1b832013-01-07 09:53:42 -08006131 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006132 // discard any pending drain or write ack by incrementing sequence
6133 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6134 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006135 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006136 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6137 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006138 }
6139}
6140
Haynes Mathew George05317d22016-05-03 16:34:26 -07006141void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6142{
6143 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006144 if (PlaybackThread::invalidateTracks_l(streamType)) {
6145 mFlushPending = true;
6146 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006147}
6148
Eric Laurentbfb1b832013-01-07 09:53:42 -08006149// ----------------------------------------------------------------------------
6150
Eric Laurent81784c32012-11-19 14:55:58 -08006151AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006152 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006153 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006154 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006155 mWaitTimeMs(UINT_MAX)
6156{
6157 addOutputTrack(mainThread);
6158}
6159
6160AudioFlinger::DuplicatingThread::~DuplicatingThread()
6161{
6162 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6163 mOutputTracks[i]->destroy();
6164 }
6165}
6166
6167void AudioFlinger::DuplicatingThread::threadLoop_mix()
6168{
6169 // mix buffers...
6170 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006171 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006172 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006173 if (mMixerBufferValid) {
6174 memset(mMixerBuffer, 0, mMixerBufferSize);
6175 } else {
6176 memset(mSinkBuffer, 0, mSinkBufferSize);
6177 }
Eric Laurent81784c32012-11-19 14:55:58 -08006178 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006179 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006180 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006181 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006182 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006183}
6184
6185void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6186{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006187 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006188 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006189 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006190 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006191 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006192 }
6193 } else if (mBytesWritten != 0) {
6194 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6195 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006196 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006197 } else {
6198 // flush remaining overflow buffers in output tracks
6199 writeFrames = 0;
6200 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006201 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006202 }
6203}
6204
Eric Laurentbfb1b832013-01-07 09:53:42 -08006205ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006206{
6207 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006208 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6209
6210 // Consider the first OutputTrack for timestamp and frame counting.
6211
6212 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6213 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6214 // we always claim success.
6215 if (i == 0) {
6216 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6217 ALOGD_IF(correction != 0 && writeFrames != 0,
6218 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6219 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6220 mFramesWritten -= correction;
6221 }
6222
6223 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006224 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006225 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006226 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006227}
6228
6229void AudioFlinger::DuplicatingThread::threadLoop_standby()
6230{
6231 // DuplicatingThread implements standby by stopping all tracks
6232 for (size_t i = 0; i < outputTracks.size(); i++) {
6233 outputTracks[i]->stop();
6234 }
6235}
6236
Andy Hung1bc088a2018-02-09 15:57:31 -08006237void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6238{
6239 MixerThread::dumpInternals(fd, args);
6240
6241 std::stringstream ss;
6242 const size_t numTracks = mOutputTracks.size();
6243 ss << " " << numTracks << " OutputTracks";
6244 if (numTracks > 0) {
6245 ss << ":";
6246 for (const auto &track : mOutputTracks) {
6247 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006248 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006249 if (thread.get() != nullptr) {
6250 ss << thread.get() << ", " << thread->id();
6251 } else {
6252 ss << "null";
6253 }
6254 ss << ")";
6255 }
6256 }
6257 ss << "\n";
6258 std::string result = ss.str();
6259 write(fd, result.c_str(), result.size());
6260}
6261
Eric Laurent81784c32012-11-19 14:55:58 -08006262void AudioFlinger::DuplicatingThread::saveOutputTracks()
6263{
6264 outputTracks = mOutputTracks;
6265}
6266
6267void AudioFlinger::DuplicatingThread::clearOutputTracks()
6268{
6269 outputTracks.clear();
6270}
6271
6272void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6273{
6274 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006275 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6276 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6277 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6278 const size_t frameCount =
6279 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6280 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6281 // from different OutputTracks and their associated MixerThreads (e.g. one may
6282 // nearly empty and the other may be dropping data).
6283
6284 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006285 this,
6286 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006287 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006288 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006289 frameCount,
6290 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006291 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6292 if (status != NO_ERROR) {
6293 ALOGE("addOutputTrack() initCheck failed %d", status);
6294 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006295 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006296 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6297 mOutputTracks.add(outputTrack);
6298 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6299 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006300}
6301
6302void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6303{
6304 Mutex::Autolock _l(mLock);
6305 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6306 if (mOutputTracks[i]->thread() == thread) {
6307 mOutputTracks[i]->destroy();
6308 mOutputTracks.removeAt(i);
6309 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006310 if (thread->getOutput() == mOutput) {
6311 mOutput = NULL;
6312 }
Eric Laurent81784c32012-11-19 14:55:58 -08006313 return;
6314 }
6315 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006316 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006317}
6318
6319// caller must hold mLock
6320void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6321{
6322 mWaitTimeMs = UINT_MAX;
6323 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6324 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6325 if (strong != 0) {
6326 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6327 if (waitTimeMs < mWaitTimeMs) {
6328 mWaitTimeMs = waitTimeMs;
6329 }
6330 }
6331 }
6332}
6333
6334
6335bool AudioFlinger::DuplicatingThread::outputsReady(
6336 const SortedVector< sp<OutputTrack> > &outputTracks)
6337{
6338 for (size_t i = 0; i < outputTracks.size(); i++) {
6339 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6340 if (thread == 0) {
6341 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6342 outputTracks[i].get());
6343 return false;
6344 }
6345 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6346 // see note at standby() declaration
6347 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6348 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6349 thread.get());
6350 return false;
6351 }
6352 }
6353 return true;
6354}
6355
Kevin Rocard12381092018-04-11 09:19:59 -07006356void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6357 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006358{
Kevin Rocard12381092018-04-11 09:19:59 -07006359 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6360 outputTrack->setMetadatas(metadata.tracks);
6361 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006362}
6363
Eric Laurent81784c32012-11-19 14:55:58 -08006364uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6365{
6366 return (mWaitTimeMs * 1000) / 2;
6367}
6368
6369void AudioFlinger::DuplicatingThread::cacheParameters_l()
6370{
6371 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6372 updateWaitTime_l();
6373
6374 MixerThread::cacheParameters_l();
6375}
6376
Eric Laurent6acd1d42017-01-04 14:23:29 -08006377
Eric Laurent81784c32012-11-19 14:55:58 -08006378// ----------------------------------------------------------------------------
6379// Record
6380// ----------------------------------------------------------------------------
6381
6382AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6383 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006384 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006385 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006386 audio_devices_t inDevice,
6387 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006388 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006389 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006390 mInput(input),
6391 mActiveTracks(&this->mLocalLog),
6392 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006393 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006394 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006395 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6396 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006397 // mFastCapture below
6398 , mFastCaptureFutex(0)
6399 // mInputSource
6400 // mPipeSink
6401 // mPipeSource
6402 , mPipeFramesP2(0)
6403 // mPipeMemory
6404 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006405 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006406 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006407{
Glenn Kastend7dca052015-03-05 16:05:54 -08006408 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6409 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006410
Andy Hungc8fddf32018-08-08 18:32:37 -07006411 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6412 mIsMsdDevice = strcmp(
6413 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6414 }
6415
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006416 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006417
Andy Hungc8fddf32018-08-08 18:32:37 -07006418 // TODO: We may also match on address as well as device type for
6419 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
6420 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
6421 "audio.timestamp.corrected_input_devices",
6422 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6423 : AUDIO_DEVICE_NONE));
6424
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006425 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006426 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006427 size_t numCounterOffers = 0;
6428 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006429#if !LOG_NDEBUG
6430 ssize_t index =
6431#else
6432 (void)
6433#endif
6434 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006435 ALOG_ASSERT(index == 0);
6436
6437 // initialize fast capture depending on configuration
6438 bool initFastCapture;
6439 switch (kUseFastCapture) {
6440 case FastCapture_Never:
6441 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006442 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006443 break;
6444 case FastCapture_Always:
6445 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006446 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006447 break;
6448 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006449 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006450 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6451 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6452 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006453 break;
6454 // case FastCapture_Dynamic:
6455 }
6456
6457 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006458 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006459 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006460 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6461 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006462 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006463 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006464 const sp<MemoryDealer> roHeap(readOnlyHeap());
6465 sp<IMemory> pipeMemory;
6466 if ((roHeap == 0) ||
6467 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006468 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6469 ALOGE("not enough memory for pipe buffer size=%zu; "
6470 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6471 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6472 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006473 goto failed;
6474 }
6475 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6476 memset(pipeBuffer, 0, pipeSize);
6477 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6478 const NBAIO_Format offers[1] = {format};
6479 size_t numCounterOffers = 0;
6480 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6481 ALOG_ASSERT(index == 0);
6482 mPipeSink = pipe;
6483 PipeReader *pipeReader = new PipeReader(*pipe);
6484 numCounterOffers = 0;
6485 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6486 ALOG_ASSERT(index == 0);
6487 mPipeSource = pipeReader;
6488 mPipeFramesP2 = pipeFramesP2;
6489 mPipeMemory = pipeMemory;
6490
6491 // create fast capture
6492 mFastCapture = new FastCapture();
6493 FastCaptureStateQueue *sq = mFastCapture->sq();
6494#ifdef STATE_QUEUE_DUMP
6495 // FIXME
6496#endif
6497 FastCaptureState *state = sq->begin();
6498 state->mCblk = NULL;
6499 state->mInputSource = mInputSource.get();
6500 state->mInputSourceGen++;
6501 state->mPipeSink = pipe;
6502 state->mPipeSinkGen++;
6503 state->mFrameCount = mFrameCount;
6504 state->mCommand = FastCaptureState::COLD_IDLE;
6505 // already done in constructor initialization list
6506 //mFastCaptureFutex = 0;
6507 state->mColdFutexAddr = &mFastCaptureFutex;
6508 state->mColdGen++;
6509 state->mDumpState = &mFastCaptureDumpState;
6510#ifdef TEE_SINK
6511 // FIXME
6512#endif
6513 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6514 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6515 sq->end();
6516 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6517
6518 // start the fast capture
6519 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6520 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006521 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006522 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006523#ifdef AUDIO_WATCHDOG
6524 // FIXME
6525#endif
6526
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006527 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006528 }
Andy Hung8946a282018-04-19 20:04:56 -07006529#ifdef TEE_SINK
6530 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6531 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6532#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006533failed: ;
6534
6535 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006536}
6537
Eric Laurent81784c32012-11-19 14:55:58 -08006538AudioFlinger::RecordThread::~RecordThread()
6539{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006540 if (mFastCapture != 0) {
6541 FastCaptureStateQueue *sq = mFastCapture->sq();
6542 FastCaptureState *state = sq->begin();
6543 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6544 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6545 if (old == -1) {
6546 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6547 }
6548 }
6549 state->mCommand = FastCaptureState::EXIT;
6550 sq->end();
6551 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6552 mFastCapture->join();
6553 mFastCapture.clear();
6554 }
6555 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006556 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006557 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006558}
6559
6560void AudioFlinger::RecordThread::onFirstRef()
6561{
Glenn Kastend7dca052015-03-05 16:05:54 -08006562 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006563}
6564
Eric Laurent555530a2017-02-07 18:17:24 -08006565void AudioFlinger::RecordThread::preExit()
6566{
6567 ALOGV(" preExit()");
6568 Mutex::Autolock _l(mLock);
6569 for (size_t i = 0; i < mTracks.size(); i++) {
6570 sp<RecordTrack> track = mTracks[i];
6571 track->invalidate();
6572 }
6573 mActiveTracks.clear();
6574 mStartStopCond.broadcast();
6575}
6576
Eric Laurent81784c32012-11-19 14:55:58 -08006577bool AudioFlinger::RecordThread::threadLoop()
6578{
Eric Laurent81784c32012-11-19 14:55:58 -08006579 nsecs_t lastWarning = 0;
6580
6581 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006582
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006583reacquire_wakelock:
6584 sp<RecordTrack> activeTrack;
6585 {
6586 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006587 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006588 }
6589
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006590 // used to request a deferred sleep, to be executed later while mutex is unlocked
6591 uint32_t sleepUs = 0;
6592
6593 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006594 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006595 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006596
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006597 // activeTracks accumulates a copy of a subset of mActiveTracks
6598 Vector< sp<RecordTrack> > activeTracks;
6599
Glenn Kasten735f45f2014-08-18 15:51:59 -07006600 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006601 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006602
Glenn Kasten735f45f2014-08-18 15:51:59 -07006603 // reference to a fast track which is about to be removed
6604 sp<RecordTrack> fastTrackToRemove;
6605
Eric Laurent81784c32012-11-19 14:55:58 -08006606 { // scope for mLock
6607 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006608
Eric Laurent021cf962014-05-13 10:18:14 -07006609 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006610
Eric Laurent000a4192014-01-29 15:17:32 -08006611 // check exitPending here because checkForNewParameters_l() and
6612 // checkForNewParameters_l() can temporarily release mLock
6613 if (exitPending()) {
6614 break;
6615 }
6616
Eric Laurent5c25d562016-07-13 17:17:45 -07006617 // sleep with mutex unlocked
6618 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006619 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006620 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6621 ATRACE_END();
6622 sleepUs = 0;
6623 continue;
6624 }
6625
Glenn Kasten2b806402013-11-20 16:37:38 -08006626 // if no active track(s), then standby and release wakelock
6627 size_t size = mActiveTracks.size();
6628 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006629 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006630 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006631 releaseWakeLock_l();
6632 ALOGV("RecordThread: loop stopping");
6633 // go to sleep
6634 mWaitWorkCV.wait(mLock);
6635 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006636 goto reacquire_wakelock;
6637 }
6638
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006639 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006640 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006641 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006642
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006643 activeTrack = mActiveTracks[i];
6644 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006645 if (activeTrack->isFastTrack()) {
6646 ALOG_ASSERT(fastTrackToRemove == 0);
6647 fastTrackToRemove = activeTrack;
6648 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006649 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006650 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006651 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006652 continue;
6653 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006654
6655 TrackBase::track_state activeTrackState = activeTrack->mState;
6656 switch (activeTrackState) {
6657
6658 case TrackBase::PAUSING:
6659 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006660 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006661 doBroadcast = true;
6662 size--;
6663 continue;
6664
6665 case TrackBase::STARTING_1:
6666 sleepUs = 10000;
6667 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006668 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006669 continue;
6670
6671 case TrackBase::STARTING_2:
6672 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006673 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006674 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006675 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006676 break;
6677
6678 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006679 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006680 break;
6681
Andy Hungce685402018-10-05 17:23:27 -07006682 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6683 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6684 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006685 default:
Andy Hungce685402018-10-05 17:23:27 -07006686 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6687 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006688 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006689
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006690 activeTracks.add(activeTrack);
6691 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006692
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006693 if (activeTrack->isFastTrack()) {
6694 ALOG_ASSERT(!mFastTrackAvail);
6695 ALOG_ASSERT(fastTrack == 0);
6696 fastTrack = activeTrack;
6697 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006698 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006699
Andy Hungdae27702016-10-31 14:01:16 -07006700 mActiveTracks.updatePowerState(this);
6701
Kevin Rocard069c2712018-03-29 19:09:14 -07006702 updateMetadata_l();
6703
Eric Laurent5c25d562016-07-13 17:17:45 -07006704 if (allStopped) {
6705 standbyIfNotAlreadyInStandby();
6706 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006707 if (doBroadcast) {
6708 mStartStopCond.broadcast();
6709 }
6710
6711 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006712 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006713 if (sleepUs == 0) {
6714 sleepUs = kRecordThreadSleepUs;
6715 }
6716 continue;
6717 }
6718 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006719
Eric Laurent81784c32012-11-19 14:55:58 -08006720 lockEffectChains_l(effectChains);
6721 }
6722
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006723 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006724
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006725 size_t size = effectChains.size();
6726 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006727 // thread mutex is not locked, but effect chain is locked
6728 effectChains[i]->process_l();
6729 }
6730
Glenn Kasten735f45f2014-08-18 15:51:59 -07006731 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006732 if (mFastCapture != 0) {
6733 FastCaptureStateQueue *sq = mFastCapture->sq();
6734 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006735 bool didModify = false;
6736 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006737 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6738 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6739 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6740 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6741 if (old == -1) {
6742 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6743 }
6744 }
6745 state->mCommand = FastCaptureState::READ_WRITE;
6746#if 0 // FIXME
6747 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006748 FastThreadDumpState::kSamplingNforLowRamDevice :
6749 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006750#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006751 didModify = true;
6752 }
6753 audio_track_cblk_t *cblkOld = state->mCblk;
6754 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6755 if (cblkNew != cblkOld) {
6756 state->mCblk = cblkNew;
6757 // block until acked if removing a fast track
6758 if (cblkOld != NULL) {
6759 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6760 }
6761 didModify = true;
6762 }
jiabin01c8f562018-07-19 17:47:28 -07006763 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
6764 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
6765 if (state->mFastPatchRecordBufferProvider != abp) {
6766 state->mFastPatchRecordBufferProvider = abp;
6767 state->mFastPatchRecordFormat = fastTrack == 0 ?
6768 AUDIO_FORMAT_INVALID : fastTrack->format();
6769 didModify = true;
6770 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07006771 sq->end(didModify);
6772 if (didModify) {
6773 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006774#if 0
6775 if (kUseFastCapture == FastCapture_Dynamic) {
6776 mNormalSource = mPipeSource;
6777 }
6778#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006779 }
6780 }
6781
Glenn Kasten735f45f2014-08-18 15:51:59 -07006782 // now run the fast track destructor with thread mutex unlocked
6783 fastTrackToRemove.clear();
6784
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006785 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6786 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6787 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6788 // If destination is non-contiguous, first read past the nominal end of buffer, then
6789 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006790
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006791 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006792 ssize_t framesRead;
6793
6794 // If an NBAIO source is present, use it to read the normal capture's data
6795 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07006796 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006797
6798 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6799 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6800 // we immediately retry the read() to get data and prevent another overflow.
6801 for (int retries = 0; retries <= 2; ++retries) {
6802 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6803 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6804 framesToRead);
6805 if (framesRead != OVERRUN) break;
6806 }
6807
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006808 const ssize_t availableToRead = mPipeSource->availableToRead();
6809 if (availableToRead >= 0) {
6810 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6811 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6812 "more frames to read than fifo size, %zd > %zu",
6813 availableToRead, mPipeFramesP2);
6814 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6815 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6816 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6817 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006818 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6819 }
6820 if (framesRead < 0) {
6821 status_t status = (status_t) framesRead;
6822 switch (status) {
6823 case OVERRUN:
6824 ALOGW("overrun on read from pipe");
6825 framesRead = 0;
6826 break;
6827 case NEGOTIATE:
6828 ALOGE("re-negotiation is needed");
6829 framesRead = -1; // Will cause an attempt to recover.
6830 break;
6831 default:
6832 ALOGE("unknown error %d on read from pipe", status);
6833 break;
6834 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006835 }
6836 // otherwise use the HAL / AudioStreamIn directly
6837 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006838 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006839 size_t bytesRead;
6840 status_t result = mInput->stream->read(
6841 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006842 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006843 if (result < 0) {
6844 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006845 } else {
6846 framesRead = bytesRead / mFrameSize;
6847 }
6848 }
6849
Andy Hung3f0c9022016-01-15 17:49:46 -08006850 // Update server timestamp with server stats
6851 // systemTime() is optional if the hardware supports timestamps.
6852 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6853 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6854
6855 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006856 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006857 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006858 if (mStandby) {
6859 mTimestampVerifier.discontinuity();
Andy Hungc8fddf32018-08-08 18:32:37 -07006860 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR
6861 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
6862
6863 mTimestampVerifier.add(position, time, mSampleRate);
6864
6865 // Correct timestamps
6866 if (isTimestampCorrectionEnabled()) {
6867 ALOGV("TS_BEFORE: %d %lld %lld",
6868 id(), (long long)time, (long long)position);
6869 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
6870 position = correctedTimestamp.mFrames;
6871 time = correctedTimestamp.mTimeNs;
6872 ALOGV("TS_AFTER: %d %lld %lld",
6873 id(), (long long)time, (long long)position);
6874 }
6875
Andy Hung3f0c9022016-01-15 17:49:46 -08006876 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6877 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6878 // Note: In general record buffers should tend to be empty in
6879 // a properly running pipeline.
6880 //
6881 // Also, it is not advantageous to call get_presentation_position during the read
6882 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006883 } else {
6884 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08006885 }
6886 }
6887 // Use this to track timestamp information
6888 // ALOGD("%s", mTimestamp.toString().c_str());
6889
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006890 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006891 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006892 // Force input into standby so that it tries to recover at next read attempt
6893 inputStandBy();
6894 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006895 }
6896 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006897 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006898 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006899 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07006900 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006901
Andy Hung8946a282018-04-19 20:04:56 -07006902#ifdef TEE_SINK
6903 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6904#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006905 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006906 {
6907 size_t part1 = mRsmpInFramesP2 - rear;
6908 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006909 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006910 (framesRead - part1) * mFrameSize);
6911 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006912 }
6913 rear = mRsmpInRear += framesRead;
6914
6915 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006916
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006917 // loop over each active track
6918 for (size_t i = 0; i < size; i++) {
6919 activeTrack = activeTracks[i];
6920
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006921 // skip fast tracks, as those are handled directly by FastCapture
6922 if (activeTrack->isFastTrack()) {
6923 continue;
6924 }
6925
Andy Hung73c02e42015-03-29 01:13:58 -07006926 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006927 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6928
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006929 enum {
6930 OVERRUN_UNKNOWN,
6931 OVERRUN_TRUE,
6932 OVERRUN_FALSE
6933 } overrun = OVERRUN_UNKNOWN;
6934
6935 // loop over getNextBuffer to handle circular sink
6936 for (;;) {
6937
6938 activeTrack->mSink.frameCount = ~0;
6939 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6940 size_t framesOut = activeTrack->mSink.frameCount;
6941 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6942
Andy Hung73c02e42015-03-29 01:13:58 -07006943 // check available frames and handle overrun conditions
6944 // if the record track isn't draining fast enough.
6945 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006946 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006947 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6948 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006949 overrun = OVERRUN_TRUE;
6950 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006951 if (framesOut == 0 || framesIn == 0) {
6952 break;
6953 }
6954
Andy Hung6770c6f2015-04-07 13:43:36 -07006955 // Don't allow framesOut to be larger than what is possible with resampling
6956 // from framesIn.
6957 // This isn't strictly necessary but helps limit buffer resizing in
6958 // RecordBufferConverter. TODO: remove when no longer needed.
6959 framesOut = min(framesOut,
6960 destinationFramesPossible(
6961 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006962
6963 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10006964 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006965 // straight from RecordThread buffer to RecordTrack buffer.
6966 AudioBufferProvider::Buffer buffer;
6967 buffer.frameCount = framesOut;
6968 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
6969 if (status == OK && buffer.frameCount != 0) {
6970 ALOGV_IF(buffer.frameCount != framesOut,
6971 "%s() read less than expected (%zu vs %zu)",
6972 __func__, buffer.frameCount, framesOut);
6973 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10006974 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006975 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
6976 } else {
6977 framesOut = 0;
6978 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
6979 __func__, status, buffer.frameCount);
6980 }
6981 } else {
6982 // process frames from the RecordThread buffer provider to the RecordTrack
6983 // buffer
6984 framesOut = activeTrack->mRecordBufferConverter->convert(
6985 activeTrack->mSink.raw,
6986 activeTrack->mResamplerBufferProvider,
6987 framesOut);
6988 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006989
6990 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6991 overrun = OVERRUN_FALSE;
6992 }
6993
6994 if (activeTrack->mFramesToDrop == 0) {
6995 if (framesOut > 0) {
6996 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006997 // Sanitize before releasing if the track has no access to the source data
6998 // An idle UID receives silence from non virtual devices until active
6999 if (activeTrack->isSilenced()) {
7000 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
7001 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007002 activeTrack->releaseBuffer(&activeTrack->mSink);
7003 }
7004 } else {
7005 // FIXME could do a partial drop of framesOut
7006 if (activeTrack->mFramesToDrop > 0) {
7007 activeTrack->mFramesToDrop -= framesOut;
7008 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007009 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007010 }
7011 } else {
7012 activeTrack->mFramesToDrop += framesOut;
7013 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7014 activeTrack->mSyncStartEvent->isCancelled()) {
7015 ALOGW("Synced record %s, session %d, trigger session %d",
7016 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7017 activeTrack->sessionId(),
7018 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007019 activeTrack->mSyncStartEvent->triggerSession() :
7020 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007021 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007022 }
7023 }
7024 }
7025
7026 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007027 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007028 }
7029 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007030
7031 switch (overrun) {
7032 case OVERRUN_TRUE:
7033 // client isn't retrieving buffers fast enough
7034 if (!activeTrack->setOverflow()) {
7035 nsecs_t now = systemTime();
7036 // FIXME should lastWarning per track?
7037 if ((now - lastWarning) > kWarningThrottleNs) {
7038 ALOGW("RecordThread: buffer overflow");
7039 lastWarning = now;
7040 }
7041 }
7042 break;
7043 case OVERRUN_FALSE:
7044 activeTrack->clearOverflow();
7045 break;
7046 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007047 break;
7048 }
7049
Andy Hung3f0c9022016-01-15 17:49:46 -08007050 // update frame information and push timestamp out
7051 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007052 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007053 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7054 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007055 }
7056
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007057unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007058 // enable changes in effect chain
7059 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007060 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08007061 }
7062
Glenn Kasten93e471f2013-08-19 08:40:07 -07007063 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007064
7065 {
7066 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007067 for (size_t i = 0; i < mTracks.size(); i++) {
7068 sp<RecordTrack> track = mTracks[i];
7069 track->invalidate();
7070 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007071 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007072 mStartStopCond.broadcast();
7073 }
7074
7075 releaseWakeLock();
7076
7077 ALOGV("RecordThread %p exiting", this);
7078 return false;
7079}
7080
Glenn Kasten93e471f2013-08-19 08:40:07 -07007081void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007082{
7083 if (!mStandby) {
7084 inputStandBy();
7085 mStandby = true;
7086 }
7087}
7088
7089void AudioFlinger::RecordThread::inputStandBy()
7090{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007091 // Idle the fast capture if it's currently running
7092 if (mFastCapture != 0) {
7093 FastCaptureStateQueue *sq = mFastCapture->sq();
7094 FastCaptureState *state = sq->begin();
7095 if (!(state->mCommand & FastCaptureState::IDLE)) {
7096 state->mCommand = FastCaptureState::COLD_IDLE;
7097 state->mColdFutexAddr = &mFastCaptureFutex;
7098 state->mColdGen++;
7099 mFastCaptureFutex = 0;
7100 sq->end();
7101 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7102 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7103#if 0
7104 if (kUseFastCapture == FastCapture_Dynamic) {
7105 // FIXME
7106 }
7107#endif
7108#ifdef AUDIO_WATCHDOG
7109 // FIXME
7110#endif
7111 } else {
7112 sq->end(false /*didModify*/);
7113 }
7114 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007115 status_t result = mInput->stream->standby();
7116 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007117
7118 // If going into standby, flush the pipe source.
7119 if (mPipeSource.get() != nullptr) {
7120 const ssize_t flushed = mPipeSource->flush();
7121 if (flushed > 0) {
7122 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7123 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7124 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7125 }
7126 }
Eric Laurent81784c32012-11-19 14:55:58 -08007127}
7128
Glenn Kasten05997e22014-03-13 15:08:33 -07007129// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007130sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007131 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007132 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007133 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007134 audio_format_t format,
7135 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007136 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007137 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007138 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007139 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007140 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007141 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007142 status_t *status,
7143 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007144{
Glenn Kasten74935e42013-12-19 08:56:45 -08007145 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007146 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007147 sp<RecordTrack> track;
7148 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007149 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007150 audio_input_flags_t requestedFlags = *flags;
7151 uint32_t sampleRate;
7152
7153 lStatus = initCheck();
7154 if (lStatus != NO_ERROR) {
7155 ALOGE("createRecordTrack_l() audio driver not initialized");
7156 goto Exit;
7157 }
7158
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007159 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7160 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7161 lStatus = BAD_VALUE;
7162 goto Exit;
7163 }
7164
Eric Laurentf14db3c2017-12-08 14:20:36 -08007165 if (*pSampleRate == 0) {
7166 *pSampleRate = mSampleRate;
7167 }
7168 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007169
7170 // special case for FAST flag considered OK if fast capture is present
7171 if (hasFastCapture()) {
7172 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7173 }
7174
Eric Laurentf14db3c2017-12-08 14:20:36 -08007175 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007176 if ((*flags & inputFlags) != *flags) {
7177 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7178 " input flags (%08x)",
7179 *flags, inputFlags);
7180 *flags = (audio_input_flags_t)(*flags & inputFlags);
7181 }
Eric Laurent81784c32012-11-19 14:55:58 -08007182
Glenn Kasten90e58b12013-07-31 16:16:02 -07007183 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007184 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007185 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007186 // we formerly checked for a callback handler (non-0 tid),
7187 // but that is no longer required for TRANSFER_OBTAIN mode
7188 //
Glenn Kasten74105912014-07-03 12:28:53 -07007189 // frame count is not specified, or is exactly the pipe depth
7190 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007191 // PCM data
7192 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007193 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007194 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007195 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007196 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007197 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007198 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007199 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007200 hasFastCapture() &&
7201 // there are sufficient fast track slots available
7202 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007203 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007204 // check compatibility with audio effects.
7205 Mutex::Autolock _l(mLock);
7206 // Do not accept FAST flag if the session has software effects
7207 sp<EffectChain> chain = getEffectChain_l(sessionId);
7208 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007209 audio_input_flags_t old = *flags;
7210 chain->checkInputFlagCompatibility(flags);
7211 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007212 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7213 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007214 }
7215 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007216 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007217 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7218 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007219 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007220 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7221 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007222 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007223 this, frameCount, mFrameCount, mPipeFramesP2,
7224 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007225 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007226 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007227 }
7228 }
7229
Eric Laurentf14db3c2017-12-08 14:20:36 -08007230 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7231 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7232 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7233 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7234 lStatus = BAD_TYPE;
7235 goto Exit;
7236 }
7237
Glenn Kasten74105912014-07-03 12:28:53 -07007238 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007239 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007240 // fast track: frame count is exactly the pipe depth
7241 frameCount = mPipeFramesP2;
7242 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007243 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007244 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007245 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7246 // or 20 ms if there is a fast capture
7247 // TODO This could be a roundupRatio inline, and const
7248 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7249 * sampleRate + mSampleRate - 1) / mSampleRate;
7250 // minimum number of notification periods is at least kMinNotifications,
7251 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7252 static const size_t kMinNotifications = 3;
7253 static const uint32_t kMinMs = 30;
7254 // TODO This could be a roundupRatio inline
7255 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7256 // TODO This could be a roundupRatio inline
7257 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7258 maxNotificationFrames;
7259 const size_t minFrameCount = maxNotificationFrames *
7260 max(kMinNotifications, minNotificationsByMs);
7261 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007262 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7263 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007264 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007265 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007266 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007267 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007268
7269 { // scope for mLock
7270 Mutex::Autolock _l(mLock);
7271
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007272 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007273 format, channelMask, frameCount,
7274 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007275 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007276
Glenn Kasten03003332013-08-06 15:40:54 -07007277 lStatus = track->initCheck();
7278 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007279 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007280 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007281 goto Exit;
7282 }
7283 mTracks.add(track);
7284
Eric Laurent05067782016-06-01 18:27:28 -07007285 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007286 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7287 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7288 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007289 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007290 }
Eric Laurent81784c32012-11-19 14:55:58 -08007291 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007292
Eric Laurent81784c32012-11-19 14:55:58 -08007293 lStatus = NO_ERROR;
7294
7295Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007296 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007297 return track;
7298}
7299
7300status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7301 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007302 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007303{
7304 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7305 sp<ThreadBase> strongMe = this;
7306 status_t status = NO_ERROR;
7307
7308 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007309 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007310 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007311 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007312 triggerSession,
7313 recordTrack->sessionId(),
7314 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007315 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007316 // Sync event can be cancelled by the trigger session if the track is not in a
7317 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007318 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007319 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007320 } else {
7321 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007322 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007323 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007324 }
7325 }
7326
7327 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007328 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007329 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007330 if (recordTrack->isInvalid()) {
7331 recordTrack->clearSyncStartEvent();
7332 return INVALID_OPERATION;
7333 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007334 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7335 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007336 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7337 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007338 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007339 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007340 } else {
7341 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007342 }
7343 return status;
7344 }
7345
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007346 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7347 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7348 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007349 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007350 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007351 status_t status = NO_ERROR;
7352 if (recordTrack->isExternalTrack()) {
7353 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007354 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007355 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007356 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007357 if (recordTrack->isInvalid()) {
7358 recordTrack->clearSyncStartEvent();
7359 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7360 recordTrack->mState = TrackBase::STARTING_2;
7361 // STARTING_2 forces destroy to call stopInput.
7362 }
7363 return INVALID_OPERATION;
7364 }
7365 if (recordTrack->mState != TrackBase::STARTING_1) {
7366 ALOGW("%s(%d): unsynchronized mState:%d change",
7367 __func__, recordTrack->id(), recordTrack->mState);
7368 // Someone else has changed state, let them take over,
7369 // leave mState in the new state.
7370 recordTrack->clearSyncStartEvent();
7371 return INVALID_OPERATION;
7372 }
7373 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007374 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007375 ALOGW("%s(%d): startInput failed, status %d",
7376 __func__, recordTrack->id(), status);
7377 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7378 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007379 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007380 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007381 return status;
7382 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007383 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007384 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007385 // Catch up with current buffer indices if thread is already running.
7386 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7387 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7388 // see previously buffered data before it called start(), but with greater risk of overrun.
7389
Andy Hung73c02e42015-03-29 01:13:58 -07007390 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007391 if (!recordTrack->isDirect()) {
7392 // clear any converter state as new data will be discontinuous
7393 recordTrack->mRecordBufferConverter->reset();
7394 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007395 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007396 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007397 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007398 return status;
7399 }
Eric Laurent81784c32012-11-19 14:55:58 -08007400}
7401
Eric Laurent81784c32012-11-19 14:55:58 -08007402void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7403{
7404 sp<SyncEvent> strongEvent = event.promote();
7405
7406 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007407 sp<RefBase> ptr = strongEvent->cookie().promote();
7408 if (ptr != 0) {
7409 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7410 recordTrack->handleSyncStartEvent(strongEvent);
7411 }
Eric Laurent81784c32012-11-19 14:55:58 -08007412 }
7413}
7414
Glenn Kastena8356f62013-07-25 14:37:52 -07007415bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007416 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007417 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007418 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007419 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007420 return false;
7421 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007422 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007423 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007424
7425 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7426 mWaitWorkCV.broadcast(); // signal thread to stop
7427 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007428 }
Andy Hungce685402018-10-05 17:23:27 -07007429
7430 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007431 ALOGV("Record stopped OK");
7432 return true;
7433 }
Andy Hungce685402018-10-05 17:23:27 -07007434
7435 // don't handle anything - we've been invalidated or restarted and in a different state
7436 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7437 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007438 return false;
7439}
7440
Glenn Kasten0f11b512014-01-31 16:18:54 -08007441bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007442{
7443 return false;
7444}
7445
Glenn Kasten0f11b512014-01-31 16:18:54 -08007446status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007447{
7448#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7449 if (!isValidSyncEvent(event)) {
7450 return BAD_VALUE;
7451 }
7452
Glenn Kastend848eb42016-03-08 13:42:11 -08007453 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007454 status_t ret = NAME_NOT_FOUND;
7455
7456 Mutex::Autolock _l(mLock);
7457
7458 for (size_t i = 0; i < mTracks.size(); i++) {
7459 sp<RecordTrack> track = mTracks[i];
7460 if (eventSession == track->sessionId()) {
7461 (void) track->setSyncEvent(event);
7462 ret = NO_ERROR;
7463 }
7464 }
7465 return ret;
7466#else
7467 return BAD_VALUE;
7468#endif
7469}
7470
jiabin653cc0a2018-01-17 17:54:10 -08007471status_t AudioFlinger::RecordThread::getActiveMicrophones(
7472 std::vector<media::MicrophoneInfo>* activeMicrophones)
7473{
7474 ALOGV("RecordThread::getActiveMicrophones");
7475 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007476 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7477 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007478}
7479
Kevin Rocard069c2712018-03-29 19:09:14 -07007480void AudioFlinger::RecordThread::updateMetadata_l()
7481{
7482 if (mInput == nullptr || mInput->stream == nullptr ||
7483 !mActiveTracks.readAndClearHasChanged()) {
7484 return;
7485 }
7486 StreamInHalInterface::SinkMetadata metadata;
7487 for (const sp<RecordTrack> &track : mActiveTracks) {
7488 // No track is invalid as this is called after prepareTrack_l in the same critical section
7489 metadata.tracks.push_back({
7490 .source = track->attributes().source,
7491 .gain = 1, // capture tracks do not have volumes
7492 });
7493 }
7494 mInput->stream->updateSinkMetadata(metadata);
7495}
7496
Eric Laurent81784c32012-11-19 14:55:58 -08007497// destroyTrack_l() must be called with ThreadBase::mLock held
7498void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7499{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007500 track->terminate();
7501 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007502 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007503 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007504 removeTrack_l(track);
7505 }
7506}
7507
7508void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7509{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007510 String8 result;
7511 track->appendDump(result, false /* active */);
7512 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7513
Eric Laurent81784c32012-11-19 14:55:58 -08007514 mTracks.remove(track);
7515 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007516 if (track->isFastTrack()) {
7517 ALOG_ASSERT(!mFastTrackAvail);
7518 mFastTrackAvail = true;
7519 }
Eric Laurent81784c32012-11-19 14:55:58 -08007520}
7521
7522void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7523{
7524 dumpInternals(fd, args);
7525 dumpTracks(fd, args);
7526 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007527 dprintf(fd, " Local log:\n");
7528 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007529}
7530
7531void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7532{
Glenn Kasten44182c22015-03-05 17:12:23 -08007533 dumpBase(fd, args);
7534
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007535 AudioStreamIn *input = mInput;
7536 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7537 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7538 input, flags, inputFlagsToString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007539 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007540 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007541 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007542 }
Andy Hungbfa64962017-06-12 14:43:19 -07007543
7544 if (input != nullptr) {
7545 dprintf(fd, " Hal stream dump:\n");
7546 (void)input->stream->dump(fd);
7547 }
7548
Andy Hung7f39f562018-08-08 17:30:20 -07007549 const double latencyMs = audio_is_linear_pcm(mFormat)
7550 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
Andy Hung20bd30b2018-06-01 15:39:35 -07007551 if (latencyMs != 0.) {
7552 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7553 } else {
7554 dprintf(fd, " NormalRecord latency ms: unavail\n");
7555 }
7556
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007557 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007558 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007559
Glenn Kasten2f90c512015-12-02 11:40:09 -08007560 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7561 // while we are dumping it. It may be inconsistent, but it won't mutate!
7562 // This is a large object so we place it on the heap.
7563 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007564 const std::unique_ptr<FastCaptureDumpState> copy =
7565 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007566 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007567}
7568
Glenn Kasten0f11b512014-01-31 16:18:54 -08007569void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007570{
Eric Laurent81784c32012-11-19 14:55:58 -08007571 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007572 size_t numtracks = mTracks.size();
7573 size_t numactive = mActiveTracks.size();
7574 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007575 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007576 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007577 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007578 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007579 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007580 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007581 for (size_t i = 0; i < numtracks ; ++i) {
7582 sp<RecordTrack> track = mTracks[i];
7583 if (track != 0) {
7584 bool active = mActiveTracks.indexOf(track) >= 0;
7585 if (active) {
7586 numactiveseen++;
7587 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007588 result.append(prefix);
7589 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007590 }
Eric Laurent81784c32012-11-19 14:55:58 -08007591 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007592 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007593 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007594 }
7595
Marco Nelissenb2208842014-02-07 14:00:50 -08007596 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007597 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007598 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007599 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007600 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007601 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007602 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007603 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007604 result.append(prefix);
7605 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007606 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007607 }
Eric Laurent81784c32012-11-19 14:55:58 -08007608
7609 }
7610 write(fd, result.string(), result.size());
7611}
7612
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007613void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7614{
7615 Mutex::Autolock _l(mLock);
7616 for (size_t i = 0; i < mTracks.size() ; i++) {
7617 sp<RecordTrack> track = mTracks[i];
7618 if (track != 0 && track->uid() == uid) {
7619 track->setSilenced(silenced);
7620 }
7621 }
7622}
Andy Hung73c02e42015-03-29 01:13:58 -07007623
7624void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7625{
7626 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7627 RecordThread *recordThread = (RecordThread *) threadBase.get();
7628 mRsmpInFront = recordThread->mRsmpInRear;
7629 mRsmpInUnrel = 0;
7630}
7631
7632void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7633 size_t *framesAvailable, bool *hasOverrun)
7634{
7635 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7636 RecordThread *recordThread = (RecordThread *) threadBase.get();
7637 const int32_t rear = recordThread->mRsmpInRear;
7638 const int32_t front = mRsmpInFront;
7639 const ssize_t filled = rear - front;
7640
7641 size_t framesIn;
7642 bool overrun = false;
7643 if (filled < 0) {
7644 // should not happen, but treat like a massive overrun and re-sync
7645 framesIn = 0;
7646 mRsmpInFront = rear;
7647 overrun = true;
7648 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7649 framesIn = (size_t) filled;
7650 } else {
7651 // client is not keeping up with server, but give it latest data
7652 framesIn = recordThread->mRsmpInFrames;
7653 mRsmpInFront = /* front = */ rear - framesIn;
7654 overrun = true;
7655 }
7656 if (framesAvailable != NULL) {
7657 *framesAvailable = framesIn;
7658 }
7659 if (hasOverrun != NULL) {
7660 *hasOverrun = overrun;
7661 }
7662}
7663
Eric Laurent81784c32012-11-19 14:55:58 -08007664// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007665status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007666 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007667{
Andy Hung73c02e42015-03-29 01:13:58 -07007668 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007669 if (threadBase == 0) {
7670 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007671 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007672 return NOT_ENOUGH_DATA;
7673 }
7674 RecordThread *recordThread = (RecordThread *) threadBase.get();
7675 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007676 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007677 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007678 // FIXME should not be P2 (don't want to increase latency)
7679 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007680 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007681 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007682 front &= recordThread->mRsmpInFramesP2 - 1;
7683 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007684 if (part1 > (size_t) filled) {
7685 part1 = filled;
7686 }
7687 size_t ask = buffer->frameCount;
7688 ALOG_ASSERT(ask > 0);
7689 if (part1 > ask) {
7690 part1 = ask;
7691 }
7692 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007693 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007694 buffer->raw = NULL;
7695 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007696 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007697 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007698 }
7699
Andy Hung57446612015-04-19 23:56:46 -07007700 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007701 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007702 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007703 return NO_ERROR;
7704}
7705
7706// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007707void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7708 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007709{
Glenn Kasten85948432013-08-19 12:09:05 -07007710 size_t stepCount = buffer->frameCount;
7711 if (stepCount == 0) {
7712 return;
7713 }
Andy Hung73c02e42015-03-29 01:13:58 -07007714 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7715 mRsmpInUnrel -= stepCount;
7716 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007717 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007718 buffer->frameCount = 0;
7719}
7720
Eric Laurentd8365c52017-07-16 15:27:05 -07007721void AudioFlinger::RecordThread::checkBtNrec()
7722{
7723 Mutex::Autolock _l(mLock);
7724 checkBtNrec_l();
7725}
7726
7727void AudioFlinger::RecordThread::checkBtNrec_l()
7728{
7729 // disable AEC and NS if the device is a BT SCO headset supporting those
7730 // pre processings
7731 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7732 mAudioFlinger->btNrecIsOff();
7733 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7734 for (size_t i = 0; i < mEffectChains.size(); i++) {
7735 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7736 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7737 }
7738 }
7739}
7740
Andy Hung97a893e2015-03-29 01:03:07 -07007741
Eric Laurent10351942014-05-08 18:49:52 -07007742bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7743 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007744{
7745 bool reconfig = false;
7746
Eric Laurent10351942014-05-08 18:49:52 -07007747 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007748
Eric Laurent10351942014-05-08 18:49:52 -07007749 audio_format_t reqFormat = mFormat;
7750 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007751 // 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 -07007752 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7753
7754 AudioParameter param = AudioParameter(keyValuePair);
7755 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007756
7757 // scope for AutoPark extends to end of method
7758 AutoPark<FastCapture> park(mFastCapture);
7759
Eric Laurent10351942014-05-08 18:49:52 -07007760 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7761 // channel count change can be requested. Do we mandate the first client defines the
7762 // HAL sampling rate and channel count or do we allow changes on the fly?
7763 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7764 samplingRate = value;
7765 reconfig = true;
7766 }
7767 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007768 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007769 status = BAD_VALUE;
7770 } else {
7771 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007772 reconfig = true;
7773 }
Eric Laurent10351942014-05-08 18:49:52 -07007774 }
7775 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7776 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007777 if (!audio_is_input_channel(mask) ||
7778 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007779 status = BAD_VALUE;
7780 } else {
7781 channelMask = mask;
7782 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007783 }
Eric Laurent10351942014-05-08 18:49:52 -07007784 }
7785 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7786 // do not accept frame count changes if tracks are open as the track buffer
7787 // size depends on frame count and correct behavior would not be guaranteed
7788 // if frame count is changed after track creation
7789 if (mActiveTracks.size() > 0) {
7790 status = INVALID_OPERATION;
7791 } else {
7792 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007793 }
Eric Laurent10351942014-05-08 18:49:52 -07007794 }
7795 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7796 // forward device change to effects that have requested to be
7797 // aware of attached audio device.
7798 for (size_t i = 0; i < mEffectChains.size(); i++) {
7799 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007800 }
Eric Laurent81784c32012-11-19 14:55:58 -08007801
Eric Laurent10351942014-05-08 18:49:52 -07007802 // store input device and output device but do not forward output device to audio HAL.
7803 // Note that status is ignored by the caller for output device
7804 // (see AudioFlinger::setParameters()
7805 if (audio_is_output_devices(value)) {
7806 mOutDevice = value;
7807 status = BAD_VALUE;
7808 } else {
7809 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007810 if (value != AUDIO_DEVICE_NONE) {
7811 mPrevInDevice = value;
7812 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007813 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007814 }
Eric Laurent10351942014-05-08 18:49:52 -07007815 }
7816 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7817 mAudioSource != (audio_source_t)value) {
7818 // forward device change to effects that have requested to be
7819 // aware of attached audio device.
7820 for (size_t i = 0; i < mEffectChains.size(); i++) {
7821 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007822 }
Eric Laurent10351942014-05-08 18:49:52 -07007823 mAudioSource = (audio_source_t)value;
7824 }
Glenn Kastene198c362013-08-13 09:13:36 -07007825
Eric Laurent10351942014-05-08 18:49:52 -07007826 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007827 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007828 if (status == INVALID_OPERATION) {
7829 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007830 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007831 }
7832 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007833 if (status == BAD_VALUE) {
7834 uint32_t sRate;
7835 audio_channel_mask_t channelMask;
7836 audio_format_t format;
7837 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7838 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7839 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7840 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7841 status = NO_ERROR;
7842 }
Eric Laurent81784c32012-11-19 14:55:58 -08007843 }
Eric Laurent10351942014-05-08 18:49:52 -07007844 if (status == NO_ERROR) {
7845 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007846 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007847 }
7848 }
Eric Laurent81784c32012-11-19 14:55:58 -08007849 }
Eric Laurent10351942014-05-08 18:49:52 -07007850
Eric Laurent81784c32012-11-19 14:55:58 -08007851 return reconfig;
7852}
7853
7854String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7855{
Eric Laurent81784c32012-11-19 14:55:58 -08007856 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007857 if (initCheck() == NO_ERROR) {
7858 String8 out_s8;
7859 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7860 return out_s8;
7861 }
Eric Laurent81784c32012-11-19 14:55:58 -08007862 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007863 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007864}
7865
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007866void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007867 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7868
7869 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007870
7871 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007872 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007873 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007874 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007875 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007876 desc->mChannelMask = mChannelMask;
7877 desc->mSamplingRate = mSampleRate;
7878 desc->mFormat = mFormat;
7879 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007880 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007881 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007882 break;
7883
Eric Laurent73e26b62015-04-27 16:55:58 -07007884 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007885 default:
7886 break;
7887 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007888 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007889}
7890
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007891void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007892{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007893 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7894 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07007895 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007896 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
7897 if (audio_is_linear_pcm(mFormat)) {
7898 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
7899 mChannelCount, FCC_8);
7900 } else {
7901 // Can have more that FCC_8 channels in encoded streams.
7902 ALOGI("HAL format %#x is not linear pcm", mFormat);
7903 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007904 result = mInput->stream->getFrameSize(&mFrameSize);
7905 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7906 result = mInput->stream->getBufferSize(&mBufferSize);
7907 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007908 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007909 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7910 "mBufferSize=%lld, mFrameCount=%lld",
7911 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7912 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007913 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007914 // 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 -07007915 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007916 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007917 // A larger value should allow more old data to be read after a track calls start(),
7918 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007919 //
7920 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007921 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007922 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007923 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007924 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007925
7926 // TODO optimize audio capture buffer sizes ...
7927 // Here we calculate the size of the sliding buffer used as a source
7928 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7929 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7930 // be better to have it derived from the pipe depth in the long term.
7931 // The current value is higher than necessary. However it should not add to latency.
7932
Glenn Kasten85948432013-08-19 12:09:05 -07007933 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007934 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7935 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007936 // if posix_memalign fails, will segv here.
7937 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007938
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007939 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7940 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007941}
7942
Glenn Kasten5f972c02014-01-13 09:59:31 -08007943uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007944{
7945 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007946 uint32_t result;
7947 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7948 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007949 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007950 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007951}
7952
Eric Laurent4c415062016-06-17 16:14:16 -07007953// hasAudioSession_l() must be called with ThreadBase::mLock held
7954uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007955{
Eric Laurent81784c32012-11-19 14:55:58 -08007956 uint32_t result = 0;
7957 if (getEffectChain_l(sessionId) != 0) {
7958 result = EFFECT_SESSION;
7959 }
7960
7961 for (size_t i = 0; i < mTracks.size(); ++i) {
7962 if (sessionId == mTracks[i]->sessionId()) {
7963 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007964 if (mTracks[i]->isFastTrack()) {
7965 result |= FAST_SESSION;
7966 }
Eric Laurent81784c32012-11-19 14:55:58 -08007967 break;
7968 }
7969 }
7970
7971 return result;
7972}
7973
Glenn Kastend848eb42016-03-08 13:42:11 -08007974KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007975{
Glenn Kastend848eb42016-03-08 13:42:11 -08007976 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007977 Mutex::Autolock _l(mLock);
7978 for (size_t j = 0; j < mTracks.size(); ++j) {
7979 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007980 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007981 if (ids.indexOfKey(sessionId) < 0) {
7982 ids.add(sessionId, true);
7983 }
7984 }
7985 return ids;
7986}
7987
7988AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7989{
7990 Mutex::Autolock _l(mLock);
7991 AudioStreamIn *input = mInput;
7992 mInput = NULL;
7993 return input;
7994}
7995
7996// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007997sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007998{
7999 if (mInput == NULL) {
8000 return NULL;
8001 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008002 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008003}
8004
8005status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8006{
8007 // only one chain per input thread
Eric Tan39ec8d62018-07-24 09:49:29 -07008008 if (!mEffectChains.isEmpty()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07008009 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08008010 return INVALID_OPERATION;
8011 }
8012 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008013 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008014 chain->setInBuffer(NULL);
8015 chain->setOutBuffer(NULL);
8016
8017 checkSuspendOnAddEffectChain_l(chain);
8018
Eric Laurent1b928682014-10-02 19:41:47 -07008019 // make sure enabled pre processing effects state is communicated to the HAL as we
8020 // just moved them to a new input stream.
8021 chain->syncHalEffectsState();
8022
Eric Laurent81784c32012-11-19 14:55:58 -08008023 mEffectChains.add(chain);
8024
8025 return NO_ERROR;
8026}
8027
8028size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8029{
8030 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
8031 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008032 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08008033 chain.get(), mEffectChains.size(), this);
8034 if (mEffectChains.size() == 1) {
8035 mEffectChains.removeAt(0);
8036 }
8037 return 0;
8038}
8039
Eric Laurent1c333e22014-05-20 10:48:17 -07008040status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8041 audio_patch_handle_t *handle)
8042{
8043 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008044
8045 // store new device and send to effects
8046 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07008047 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07008048 for (size_t i = 0; i < mEffectChains.size(); i++) {
8049 mEffectChains[i]->setDevice_l(mInDevice);
8050 }
8051
Eric Laurentd8365c52017-07-16 15:27:05 -07008052 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008053
8054 // store new source and send to effects
8055 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8056 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008057 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008058 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008059 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008060 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008061
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008062 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008063 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8064 status = hwDevice->createAudioPatch(patch->num_sources,
8065 patch->sources,
8066 patch->num_sinks,
8067 patch->sinks,
8068 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008069 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008070 char *address;
8071 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8072 address = audio_device_address_to_parameter(
8073 patch->sources[0].ext.device.type,
8074 patch->sources[0].ext.device.address);
8075 } else {
8076 address = (char *)calloc(1, 1);
8077 }
8078 AudioParameter param = AudioParameter(String8(address));
8079 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008080 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008081 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008082 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008083 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008084 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008085 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008086 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008087
Eric Laurente8726fe2015-06-26 09:39:24 -07008088 if (mInDevice != mPrevInDevice) {
8089 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8090 mPrevInDevice = mInDevice;
8091 }
Eric Laurent296fb132015-05-01 11:38:42 -07008092
Eric Laurent1c333e22014-05-20 10:48:17 -07008093 return status;
8094}
8095
8096status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8097{
8098 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008099
8100 mInDevice = AUDIO_DEVICE_NONE;
8101
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008102 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008103 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8104 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008105 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008106 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008107 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008108 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008109 }
8110 return status;
8111}
8112
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008113void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008114{
8115 Mutex::Autolock _l(mLock);
8116 mTracks.add(record);
8117}
8118
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008119void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008120{
8121 Mutex::Autolock _l(mLock);
8122 destroyTrack_l(record);
8123}
8124
Mikhail Naganovdc769682018-05-04 15:34:08 -07008125void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008126{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008127 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008128 config->role = AUDIO_PORT_ROLE_SINK;
8129 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8130 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008131 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8132 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8133 config->flags.input = mInput->flags;
8134 }
Eric Laurent83b88082014-06-20 18:31:16 -07008135}
Eric Laurent1c333e22014-05-20 10:48:17 -07008136
Eric Laurent6acd1d42017-01-04 14:23:29 -08008137// ----------------------------------------------------------------------------
8138// Mmap
8139// ----------------------------------------------------------------------------
8140
8141AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8142 : mThread(thread)
8143{
Phil Burk9fabbf82017-08-03 12:02:00 -07008144 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008145}
8146
8147AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8148{
Phil Burk9fabbf82017-08-03 12:02:00 -07008149 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008150}
8151
8152status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8153 struct audio_mmap_buffer_info *info)
8154{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008155 return mThread->createMmapBuffer(minSizeFrames, info);
8156}
8157
8158status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8159{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008160 return mThread->getMmapPosition(position);
8161}
8162
Eric Laurenta54f1282017-07-01 19:39:32 -07008163status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008164 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008165
8166{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008167 return mThread->start(client, handle);
8168}
8169
8170status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8171{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008172 return mThread->stop(handle);
8173}
8174
Eric Laurent18b57012017-02-13 16:23:52 -08008175status_t AudioFlinger::MmapThreadHandle::standby()
8176{
Eric Laurent18b57012017-02-13 16:23:52 -08008177 return mThread->standby();
8178}
8179
Eric Laurent6acd1d42017-01-04 14:23:29 -08008180
8181AudioFlinger::MmapThread::MmapThread(
8182 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8183 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8184 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8185 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008186 mSessionId(AUDIO_SESSION_NONE),
8187 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008188 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008189 mActiveTracks(&this->mLocalLog),
8190 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8191 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008192{
Eric Laurent18b57012017-02-13 16:23:52 -08008193 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008194 readHalParameters_l();
8195}
8196
8197AudioFlinger::MmapThread::~MmapThread()
8198{
Eric Laurent18b57012017-02-13 16:23:52 -08008199 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008200}
8201
8202void AudioFlinger::MmapThread::onFirstRef()
8203{
8204 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8205}
8206
8207void AudioFlinger::MmapThread::disconnect()
8208{
Eric Laurent331679c2018-04-16 17:03:16 -07008209 ActiveTracks<MmapTrack> activeTracks;
8210 {
8211 Mutex::Autolock _l(mLock);
8212 for (const sp<MmapTrack> &t : mActiveTracks) {
8213 activeTracks.add(t);
8214 }
8215 }
8216 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008217 stop(t->portId());
8218 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008219 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008220 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008221 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008222 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008223 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008224 }
8225}
8226
8227
8228void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8229 audio_stream_type_t streamType __unused,
8230 audio_session_t sessionId,
8231 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008232 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008233 audio_port_handle_t portId)
8234{
8235 mAttr = *attr;
8236 mSessionId = sessionId;
8237 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008238 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008239 mPortId = portId;
8240}
8241
8242status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8243 struct audio_mmap_buffer_info *info)
8244{
8245 if (mHalStream == 0) {
8246 return NO_INIT;
8247 }
Eric Laurent18b57012017-02-13 16:23:52 -08008248 mStandby = true;
8249 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008250 return mHalStream->createMmapBuffer(minSizeFrames, info);
8251}
8252
8253status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8254{
8255 if (mHalStream == 0) {
8256 return NO_INIT;
8257 }
8258 return mHalStream->getMmapPosition(position);
8259}
8260
Eric Laurent331679c2018-04-16 17:03:16 -07008261status_t AudioFlinger::MmapThread::exitStandby()
8262{
8263 status_t ret = mHalStream->start();
8264 if (ret != NO_ERROR) {
8265 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8266 return ret;
8267 }
8268 mStandby = false;
8269 return NO_ERROR;
8270}
8271
Eric Laurenta54f1282017-07-01 19:39:32 -07008272status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008273 audio_port_handle_t *handle)
8274{
Eric Laurenta54f1282017-07-01 19:39:32 -07008275 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8276 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008277 if (mHalStream == 0) {
8278 return NO_INIT;
8279 }
8280
8281 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008282
Eric Laurenta54f1282017-07-01 19:39:32 -07008283 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008284 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008285 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008286 }
8287
8288 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8289
8290 audio_io_handle_t io = mId;
8291 if (isOutput()) {
8292 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8293 config.sample_rate = mSampleRate;
8294 config.channel_mask = mChannelMask;
8295 config.format = mFormat;
8296 audio_stream_type_t stream = streamType();
8297 audio_output_flags_t flags =
8298 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008299 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008300 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8301 mSessionId,
8302 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008303 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008304 client.clientUid,
8305 &config,
8306 flags,
8307 &deviceId,
8308 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008309 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008310 audio_config_base_t config;
8311 config.sample_rate = mSampleRate;
8312 config.channel_mask = mChannelMask;
8313 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008314 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008315 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8316 mSessionId,
8317 client.clientPid,
8318 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008319 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008320 &config,
8321 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8322 &deviceId,
8323 &portId);
8324 }
8325 // APM should not chose a different input or output stream for the same set of attributes
8326 // and audo configuration
8327 if (ret != NO_ERROR || io != mId) {
8328 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8329 __FUNCTION__, ret, io, mId);
8330 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008331 }
8332
Eric Laurent331679c2018-04-16 17:03:16 -07008333 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008334 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008335 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008336 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008337 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008338 }
8339
Eric Laurent331679c2018-04-16 17:03:16 -07008340 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008341 // abort if start is rejected by audio policy manager
8342 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008343 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008344 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008345 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008346 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008347 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008348 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008349 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008350 }
Eric Laurent331679c2018-04-16 17:03:16 -07008351 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008352 } else {
8353 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008354 }
8355 return PERMISSION_DENIED;
8356 }
8357
Eric Laurent67f97292018-04-20 18:05:41 -07008358 if (isOutput()) {
8359 // force volume update when a new track is added
8360 mHalVolFloat = -1.0f;
8361 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008362 for (const sp<MmapTrack> &track : mActiveTracks) {
8363 if (track->isSilenced_l() && track->uid() != client.clientUid)
8364 track->invalidate();
8365 }
8366 }
8367
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008368 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8369 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008370 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008371
Eric Laurent331679c2018-04-16 17:03:16 -07008372 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008373 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008374 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008375 if (chain != 0) {
8376 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8377 chain->incTrackCnt();
8378 chain->incActiveTrackCnt();
8379 }
8380
8381 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008382 broadcast_l();
8383
Eric Laurenta54f1282017-07-01 19:39:32 -07008384 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008385
8386 return NO_ERROR;
8387}
8388
8389status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8390{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008391 ALOGV("%s handle %d", __FUNCTION__, handle);
8392
8393 if (mHalStream == 0) {
8394 return NO_INIT;
8395 }
8396
Eric Laurenta54f1282017-07-01 19:39:32 -07008397 if (handle == mPortId) {
8398 mHalStream->stop();
8399 return NO_ERROR;
8400 }
8401
Eric Laurent331679c2018-04-16 17:03:16 -07008402 Mutex::Autolock _l(mLock);
8403
Eric Laurent6acd1d42017-01-04 14:23:29 -08008404 sp<MmapTrack> track;
8405 for (const sp<MmapTrack> &t : mActiveTracks) {
8406 if (handle == t->portId()) {
8407 track = t;
8408 break;
8409 }
8410 }
8411 if (track == 0) {
8412 return BAD_VALUE;
8413 }
8414
8415 mActiveTracks.remove(track);
8416
Eric Laurent331679c2018-04-16 17:03:16 -07008417 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008418 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008419 AudioSystem::stopOutput(track->portId());
8420 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008421 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008422 AudioSystem::stopInput(track->portId());
8423 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008424 }
Eric Laurent331679c2018-04-16 17:03:16 -07008425 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008426
8427 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8428 if (chain != 0) {
8429 chain->decActiveTrackCnt();
8430 chain->decTrackCnt();
8431 }
8432
8433 broadcast_l();
8434
Eric Laurent6acd1d42017-01-04 14:23:29 -08008435 return NO_ERROR;
8436}
8437
Eric Laurent18b57012017-02-13 16:23:52 -08008438status_t AudioFlinger::MmapThread::standby()
8439{
8440 ALOGV("%s", __FUNCTION__);
8441
8442 if (mHalStream == 0) {
8443 return NO_INIT;
8444 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008445 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008446 return INVALID_OPERATION;
8447 }
8448 mHalStream->standby();
8449 mStandby = true;
8450 releaseWakeLock();
8451 return NO_ERROR;
8452}
8453
Eric Laurent6acd1d42017-01-04 14:23:29 -08008454
8455void AudioFlinger::MmapThread::readHalParameters_l()
8456{
8457 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8458 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8459 mFormat = mHALFormat;
8460 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8461 result = mHalStream->getFrameSize(&mFrameSize);
8462 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8463 result = mHalStream->getBufferSize(&mBufferSize);
8464 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8465 mFrameCount = mBufferSize / mFrameSize;
8466}
8467
8468bool AudioFlinger::MmapThread::threadLoop()
8469{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008470 checkSilentMode_l();
8471
8472 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8473
8474 while (!exitPending())
8475 {
8476 Mutex::Autolock _l(mLock);
8477 Vector< sp<EffectChain> > effectChains;
8478
8479 if (mSignalPending) {
8480 // A signal was raised while we were unlocked
8481 mSignalPending = false;
8482 } else {
8483 if (mConfigEvents.isEmpty()) {
8484 // we're about to wait, flush the binder command buffer
8485 IPCThreadState::self()->flushCommands();
8486
8487 if (exitPending()) {
8488 break;
8489 }
8490
Eric Laurent6acd1d42017-01-04 14:23:29 -08008491 // wait until we have something to do...
8492 ALOGV("%s going to sleep", myName.string());
8493 mWaitWorkCV.wait(mLock);
8494 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008495
8496 checkSilentMode_l();
8497
8498 continue;
8499 }
8500 }
8501
8502 processConfigEvents_l();
8503
8504 processVolume_l();
8505
8506 checkInvalidTracks_l();
8507
8508 mActiveTracks.updatePowerState(this);
8509
Kevin Rocard069c2712018-03-29 19:09:14 -07008510 updateMetadata_l();
8511
Eric Laurent6acd1d42017-01-04 14:23:29 -08008512 lockEffectChains_l(effectChains);
8513 for (size_t i = 0; i < effectChains.size(); i ++) {
8514 effectChains[i]->process_l();
8515 }
8516 // enable changes in effect chain
8517 unlockEffectChains(effectChains);
8518 // Effect chains will be actually deleted here if they were removed from
8519 // mEffectChains list during mixing or effects processing
8520 }
8521
8522 threadLoop_exit();
8523
8524 if (!mStandby) {
8525 threadLoop_standby();
8526 mStandby = true;
8527 }
8528
Eric Laurent6acd1d42017-01-04 14:23:29 -08008529 ALOGV("Thread %p type %d exiting", this, mType);
8530 return false;
8531}
8532
8533// checkForNewParameter_l() must be called with ThreadBase::mLock held
8534bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8535 status_t& status)
8536{
8537 AudioParameter param = AudioParameter(keyValuePair);
8538 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008539 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008540 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008541 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008542 // forward device change to effects that have requested to be
8543 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008544 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008545 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008546 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008547 }
8548 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008549 if (audio_is_output_devices(device)) {
8550 mOutDevice = device;
8551 if (!isOutput()) {
8552 sendToHal = false;
8553 }
8554 } else {
8555 mInDevice = device;
8556 if (device != AUDIO_DEVICE_NONE) {
8557 mPrevInDevice = value;
8558 }
8559 // TODO: implement and call checkBtNrec_l();
8560 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008561 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008562 if (sendToHal) {
8563 status = mHalStream->setParameters(keyValuePair);
8564 } else {
8565 status = NO_ERROR;
8566 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008567
8568 return false;
8569}
8570
8571String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8572{
8573 Mutex::Autolock _l(mLock);
8574 String8 out_s8;
8575 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8576 return out_s8;
8577 }
8578 return String8();
8579}
8580
8581void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8582 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8583
8584 desc->mIoHandle = mId;
8585
8586 switch (event) {
8587 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008588 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008589 case AUDIO_INPUT_CONFIG_CHANGED:
8590 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008591 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008592 case AUDIO_OUTPUT_CONFIG_CHANGED:
8593 desc->mPatch = mPatch;
8594 desc->mChannelMask = mChannelMask;
8595 desc->mSamplingRate = mSampleRate;
8596 desc->mFormat = mFormat;
8597 desc->mFrameCount = mFrameCount;
8598 desc->mFrameCountHAL = mFrameCount;
8599 desc->mLatency = 0;
8600 break;
8601
8602 case AUDIO_INPUT_CLOSED:
8603 case AUDIO_OUTPUT_CLOSED:
8604 default:
8605 break;
8606 }
8607 mAudioFlinger->ioConfigChanged(event, desc, pid);
8608}
8609
8610status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8611 audio_patch_handle_t *handle)
8612{
8613 status_t status = NO_ERROR;
8614
8615 // store new device and send to effects
8616 audio_devices_t type = AUDIO_DEVICE_NONE;
8617 audio_port_handle_t deviceId;
8618 if (isOutput()) {
8619 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8620 type |= patch->sinks[i].ext.device.type;
8621 }
8622 deviceId = patch->sinks[0].id;
8623 } else {
8624 type = patch->sources[0].ext.device.type;
8625 deviceId = patch->sources[0].id;
8626 }
8627
8628 for (size_t i = 0; i < mEffectChains.size(); i++) {
8629 mEffectChains[i]->setDevice_l(type);
8630 }
8631
8632 if (isOutput()) {
8633 mOutDevice = type;
8634 } else {
8635 mInDevice = type;
8636 // store new source and send to effects
8637 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8638 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8639 for (size_t i = 0; i < mEffectChains.size(); i++) {
8640 mEffectChains[i]->setAudioSource_l(mAudioSource);
8641 }
8642 }
8643 }
8644
8645 if (mAudioHwDev->supportsAudioPatches()) {
8646 status = mHalDevice->createAudioPatch(patch->num_sources,
8647 patch->sources,
8648 patch->num_sinks,
8649 patch->sinks,
8650 handle);
8651 } else {
8652 char *address;
8653 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8654 //FIXME: we only support address on first sink with HAL version < 3.0
8655 address = audio_device_address_to_parameter(
8656 patch->sinks[0].ext.device.type,
8657 patch->sinks[0].ext.device.address);
8658 } else {
8659 address = (char *)calloc(1, 1);
8660 }
8661 AudioParameter param = AudioParameter(String8(address));
8662 free(address);
8663 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8664 if (!isOutput()) {
8665 param.addInt(String8(AudioParameter::keyInputSource),
8666 (int)patch->sinks[0].ext.mix.usecase.source);
8667 }
8668 status = mHalStream->setParameters(param.toString());
8669 *handle = AUDIO_PATCH_HANDLE_NONE;
8670 }
8671
8672 if (isOutput() && mPrevOutDevice != mOutDevice) {
8673 mPrevOutDevice = type;
8674 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008675 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008676 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008677 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008678 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008679 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008680 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008681 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008682 }
8683 if (!isOutput() && mPrevInDevice != mInDevice) {
8684 mPrevInDevice = type;
8685 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008686 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008687 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008688 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008689 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008690 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008691 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008692 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008693 }
8694 return status;
8695}
8696
8697status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8698{
8699 status_t status = NO_ERROR;
8700
8701 mInDevice = AUDIO_DEVICE_NONE;
8702
8703 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8704 supportsAudioPatches : false;
8705
8706 if (supportsAudioPatches) {
8707 status = mHalDevice->releaseAudioPatch(handle);
8708 } else {
8709 AudioParameter param;
8710 param.addInt(String8(AudioParameter::keyRouting), 0);
8711 status = mHalStream->setParameters(param.toString());
8712 }
8713 return status;
8714}
8715
Mikhail Naganovdc769682018-05-04 15:34:08 -07008716void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008717{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008718 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008719 if (isOutput()) {
8720 config->role = AUDIO_PORT_ROLE_SOURCE;
8721 config->ext.mix.hw_module = mAudioHwDev->handle();
8722 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8723 } else {
8724 config->role = AUDIO_PORT_ROLE_SINK;
8725 config->ext.mix.hw_module = mAudioHwDev->handle();
8726 config->ext.mix.usecase.source = mAudioSource;
8727 }
8728}
8729
8730status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8731{
8732 audio_session_t session = chain->sessionId();
8733
8734 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8735 // Attach all tracks with same session ID to this chain.
8736 // indicate all active tracks in the chain
8737 for (const sp<MmapTrack> &track : mActiveTracks) {
8738 if (session == track->sessionId()) {
8739 chain->incTrackCnt();
8740 chain->incActiveTrackCnt();
8741 }
8742 }
8743
8744 chain->setThread(this);
8745 chain->setInBuffer(nullptr);
8746 chain->setOutBuffer(nullptr);
8747 chain->syncHalEffectsState();
8748
8749 mEffectChains.add(chain);
8750 checkSuspendOnAddEffectChain_l(chain);
8751 return NO_ERROR;
8752}
8753
8754size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8755{
8756 audio_session_t session = chain->sessionId();
8757
8758 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8759
8760 for (size_t i = 0; i < mEffectChains.size(); i++) {
8761 if (chain == mEffectChains[i]) {
8762 mEffectChains.removeAt(i);
8763 // detach all active tracks from the chain
8764 // detach all tracks with same session ID from this chain
8765 for (const sp<MmapTrack> &track : mActiveTracks) {
8766 if (session == track->sessionId()) {
8767 chain->decActiveTrackCnt();
8768 chain->decTrackCnt();
8769 }
8770 }
8771 break;
8772 }
8773 }
8774 return mEffectChains.size();
8775}
8776
8777// hasAudioSession_l() must be called with ThreadBase::mLock held
8778uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8779{
8780 uint32_t result = 0;
8781 if (getEffectChain_l(sessionId) != 0) {
8782 result = EFFECT_SESSION;
8783 }
8784
8785 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8786 sp<MmapTrack> track = mActiveTracks[i];
8787 if (sessionId == track->sessionId()) {
8788 result |= TRACK_SESSION;
8789 if (track->isFastTrack()) {
8790 result |= FAST_SESSION;
8791 }
8792 break;
8793 }
8794 }
8795
8796 return result;
8797}
8798
8799void AudioFlinger::MmapThread::threadLoop_standby()
8800{
8801 mHalStream->standby();
8802}
8803
8804void AudioFlinger::MmapThread::threadLoop_exit()
8805{
Phil Burk7dce7282017-09-27 13:51:41 -07008806 // Do not call callback->onTearDown() because it is redundant for thread exit
8807 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008808}
8809
8810status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8811{
8812 return BAD_VALUE;
8813}
8814
8815bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8816{
8817 return false;
8818}
8819
8820status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8821 const effect_descriptor_t *desc, audio_session_t sessionId)
8822{
8823 // No global effect sessions on mmap threads
8824 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8825 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8826 desc->name, mThreadName);
8827 return BAD_VALUE;
8828 }
8829
8830 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8831 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8832 desc->name);
8833 return BAD_VALUE;
8834 }
8835 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008836 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8837 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008838 return BAD_VALUE;
8839 }
8840
8841 // Only allow effects without processing load or latency
8842 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8843 return BAD_VALUE;
8844 }
8845
8846 return NO_ERROR;
8847
8848}
8849
8850void AudioFlinger::MmapThread::checkInvalidTracks_l()
8851{
8852 for (const sp<MmapTrack> &track : mActiveTracks) {
8853 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008854 sp<MmapStreamCallback> callback = mCallback.promote();
8855 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008856 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008857 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008858 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008859 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8860 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8861 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008862 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008863 }
8864 }
8865}
8866
8867void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8868{
8869 dumpInternals(fd, args);
8870 dumpTracks(fd, args);
8871 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008872 dprintf(fd, " Local log:\n");
8873 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008874}
8875
8876void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8877{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008878 dumpBase(fd, args);
8879
8880 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8881 mAttr.content_type, mAttr.usage, mAttr.source);
8882 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07008883 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008884 dprintf(fd, " No active clients\n");
8885 }
8886}
8887
8888void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8889{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008890 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008891 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008892 dprintf(fd, " %zu Tracks\n", numtracks);
8893 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008894 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008895 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008896 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008897 for (size_t i = 0; i < numtracks ; ++i) {
8898 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008899 result.append(prefix);
8900 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008901 }
8902 } else {
8903 dprintf(fd, "\n");
8904 }
8905 write(fd, result.string(), result.size());
8906}
8907
8908AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8909 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8910 AudioHwDevice *hwDev, AudioStreamOut *output,
8911 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8912 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8913 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008914 mStreamVolume(1.0),
8915 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008916 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008917{
8918 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8919 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8920 mMasterVolume = audioFlinger->masterVolume_l();
8921 mMasterMute = audioFlinger->masterMute_l();
8922 if (mAudioHwDev) {
8923 if (mAudioHwDev->canSetMasterVolume()) {
8924 mMasterVolume = 1.0;
8925 }
8926
8927 if (mAudioHwDev->canSetMasterMute()) {
8928 mMasterMute = false;
8929 }
8930 }
8931}
8932
8933void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8934 audio_stream_type_t streamType,
8935 audio_session_t sessionId,
8936 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008937 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008938 audio_port_handle_t portId)
8939{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008940 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008941 mStreamType = streamType;
8942}
8943
8944AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8945{
8946 Mutex::Autolock _l(mLock);
8947 AudioStreamOut *output = mOutput;
8948 mOutput = NULL;
8949 return output;
8950}
8951
8952void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8953{
8954 Mutex::Autolock _l(mLock);
8955 // Don't apply master volume in SW if our HAL can do it for us.
8956 if (mAudioHwDev &&
8957 mAudioHwDev->canSetMasterVolume()) {
8958 mMasterVolume = 1.0;
8959 } else {
8960 mMasterVolume = value;
8961 }
8962}
8963
8964void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8965{
8966 Mutex::Autolock _l(mLock);
8967 // Don't apply master mute in SW if our HAL can do it for us.
8968 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8969 mMasterMute = false;
8970 } else {
8971 mMasterMute = muted;
8972 }
8973}
8974
8975void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8976{
8977 Mutex::Autolock _l(mLock);
8978 if (stream == mStreamType) {
8979 mStreamVolume = value;
8980 broadcast_l();
8981 }
8982}
8983
8984float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8985{
8986 Mutex::Autolock _l(mLock);
8987 if (stream == mStreamType) {
8988 return mStreamVolume;
8989 }
8990 return 0.0f;
8991}
8992
8993void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8994{
8995 Mutex::Autolock _l(mLock);
8996 if (stream == mStreamType) {
8997 mStreamMute= muted;
8998 broadcast_l();
8999 }
9000}
9001
9002void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9003{
9004 Mutex::Autolock _l(mLock);
9005 if (streamType == mStreamType) {
9006 for (const sp<MmapTrack> &track : mActiveTracks) {
9007 track->invalidate();
9008 }
9009 broadcast_l();
9010 }
9011}
9012
9013void AudioFlinger::MmapPlaybackThread::processVolume_l()
9014{
9015 float volume;
9016
9017 if (mMasterMute || mStreamMute) {
9018 volume = 0;
9019 } else {
9020 volume = mMasterVolume * mStreamVolume;
9021 }
9022
9023 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009024
9025 // Convert volumes from float to 8.24
9026 uint32_t vol = (uint32_t)(volume * (1 << 24));
9027
9028 // Delegate volume control to effect in track effect chain if needed
9029 // only one effect chain can be present on DirectOutputThread, so if
9030 // there is one, the track is connected to it
9031 if (!mEffectChains.isEmpty()) {
9032 mEffectChains[0]->setVolume_l(&vol, &vol);
9033 volume = (float)vol / (1 << 24);
9034 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009035 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009036 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9037 mHalVolFloat = volume; // HW volume control worked, so update value.
9038 mNoCallbackWarningCount = 0;
9039 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009040 sp<MmapStreamCallback> callback = mCallback.promote();
9041 if (callback != 0) {
9042 int channelCount;
9043 if (isOutput()) {
9044 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9045 } else {
9046 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9047 }
9048 Vector<float> values;
9049 for (int i = 0; i < channelCount; i++) {
9050 values.add(volume);
9051 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009052 mHalVolFloat = volume; // SW volume control worked, so update value.
9053 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009054 mLock.unlock();
9055 callback->onVolumeChanged(mChannelMask, values);
9056 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009057 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009058 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9059 ALOGW("Could not set MMAP stream volume: no volume callback!");
9060 mNoCallbackWarningCount++;
9061 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009062 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009063 }
9064 }
9065}
9066
Kevin Rocard069c2712018-03-29 19:09:14 -07009067void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9068{
9069 if (mOutput == nullptr || mOutput->stream == nullptr ||
9070 !mActiveTracks.readAndClearHasChanged()) {
9071 return;
9072 }
9073 StreamOutHalInterface::SourceMetadata metadata;
9074 for (const sp<MmapTrack> &track : mActiveTracks) {
9075 // No track is invalid as this is called after prepareTrack_l in the same critical section
9076 metadata.tracks.push_back({
9077 .usage = track->attributes().usage,
9078 .content_type = track->attributes().content_type,
9079 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9080 });
9081 }
9082 mOutput->stream->updateSourceMetadata(metadata);
9083}
9084
Eric Laurent6acd1d42017-01-04 14:23:29 -08009085void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9086{
9087 if (!mMasterMute) {
9088 char value[PROPERTY_VALUE_MAX];
9089 if (property_get("ro.audio.silent", value, "0") > 0) {
9090 char *endptr;
9091 unsigned long ul = strtoul(value, &endptr, 0);
9092 if (*endptr == '\0' && ul != 0) {
9093 ALOGD("Silence is golden");
9094 // The setprop command will not allow a property to be changed after
9095 // the first time it is set, so we don't have to worry about un-muting.
9096 setMasterMute_l(true);
9097 }
9098 }
9099 }
9100}
9101
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009102void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9103{
9104 MmapThread::toAudioPortConfig(config);
9105 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9106 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9107 config->flags.output = mOutput->flags;
9108 }
9109}
9110
Eric Laurent6acd1d42017-01-04 14:23:29 -08009111void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9112{
9113 MmapThread::dumpInternals(fd, args);
9114
Glenn Kastend3bb6452016-12-05 18:14:37 -08009115 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9116 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009117 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9118}
9119
9120AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9121 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9122 AudioHwDevice *hwDev, AudioStreamIn *input,
9123 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9124 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9125 mInput(input)
9126{
9127 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9128 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9129}
9130
Eric Laurent331679c2018-04-16 17:03:16 -07009131status_t AudioFlinger::MmapCaptureThread::exitStandby()
9132{
9133 mInput->stream->setGain(1.0f);
9134 return MmapThread::exitStandby();
9135}
9136
Eric Laurent6acd1d42017-01-04 14:23:29 -08009137AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9138{
9139 Mutex::Autolock _l(mLock);
9140 AudioStreamIn *input = mInput;
9141 mInput = NULL;
9142 return input;
9143}
Kevin Rocard069c2712018-03-29 19:09:14 -07009144
Eric Laurent331679c2018-04-16 17:03:16 -07009145
9146void AudioFlinger::MmapCaptureThread::processVolume_l()
9147{
9148 bool changed = false;
9149 bool silenced = false;
9150
9151 sp<MmapStreamCallback> callback = mCallback.promote();
9152 if (callback == 0) {
9153 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9154 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9155 mNoCallbackWarningCount++;
9156 }
9157 }
9158
9159 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9160 // track is silenced and unmute otherwise
9161 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9162 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9163 changed = true;
9164 silenced = mActiveTracks[i]->isSilenced_l();
9165 }
9166 }
9167
9168 if (changed) {
9169 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9170 }
9171}
9172
Kevin Rocard069c2712018-03-29 19:09:14 -07009173void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9174{
9175 if (mInput == nullptr || mInput->stream == nullptr ||
9176 !mActiveTracks.readAndClearHasChanged()) {
9177 return;
9178 }
9179 StreamInHalInterface::SinkMetadata metadata;
9180 for (const sp<MmapTrack> &track : mActiveTracks) {
9181 // No track is invalid as this is called after prepareTrack_l in the same critical section
9182 metadata.tracks.push_back({
9183 .source = track->attributes().source,
9184 .gain = 1, // capture tracks do not have volumes
9185 });
9186 }
9187 mInput->stream->updateSinkMetadata(metadata);
9188}
9189
Eric Laurent331679c2018-04-16 17:03:16 -07009190void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9191{
9192 Mutex::Autolock _l(mLock);
9193 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9194 if (mActiveTracks[i]->uid() == uid) {
9195 mActiveTracks[i]->setSilenced_l(silenced);
9196 broadcast_l();
9197 }
9198 }
9199}
9200
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009201void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9202{
9203 MmapThread::toAudioPortConfig(config);
9204 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9205 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9206 config->flags.input = mInput->flags;
9207 }
9208}
9209
Glenn Kasten63238ef2015-03-02 15:50:29 -08009210} // namespace android