blob: 5cc8c312befc7b1a9edcffda8c2575c6ceb73460 [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
76#include <cpustats/CentralTendencyStatistics.h>
77#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
338 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
339
340 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
341
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) {
366 mWcStats.sample(wcNs);
367 }
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) {
385 double cycles = wcNs * cpukHz * 0.000001;
386 mHzStats.sample(cycles);
387 }
388
389 unsigned n = mWcStats.n();
390 // mCpuUsage.elapsed() is expensive, so don't call it every loop
391 if ((n & 127) == 1) {
392 long long elapsed = mCpuUsage.elapsed();
393 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
394 double perLoop = elapsed / (double) n;
395 double perLoop100 = perLoop * 0.01;
396 double perLoop1k = perLoop * 0.001;
397 double mean = mWcStats.mean();
398 double stddev = mWcStats.stddev();
399 double minimum = mWcStats.minimum();
400 double maximum = mWcStats.maximum();
401 double meanCycles = mHzStats.mean();
402 double stddevCycles = mHzStats.stddev();
403 double minCycles = mHzStats.minimum();
404 double maxCycles = mHzStats.maximum();
405 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
862 || (mType == DIRECT && audio_is_linear_pcm(mHALFormat))) {
863 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
864 }
865
Eric Laurent81784c32012-11-19 14:55:58 -0800866 if (locked) {
867 mLock.unlock();
868 }
869}
870
871void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
872{
873 const size_t SIZE = 256;
874 char buffer[SIZE];
875 String8 result;
876
Marco Nelissenb2208842014-02-07 14:00:50 -0800877 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000878 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800879 write(fd, buffer, strlen(buffer));
880
Marco Nelissenb2208842014-02-07 14:00:50 -0800881 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800882 sp<EffectChain> chain = mEffectChains[i];
883 if (chain != 0) {
884 chain->dump(fd, args);
885 }
886 }
887}
888
Andy Hungdae27702016-10-31 14:01:16 -0700889void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800890{
891 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700892 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800893}
894
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100895String16 AudioFlinger::ThreadBase::getWakeLockTag()
896{
897 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800898 case MIXER:
899 return String16("AudioMix");
900 case DIRECT:
901 return String16("AudioDirectOut");
902 case DUPLICATING:
903 return String16("AudioDup");
904 case RECORD:
905 return String16("AudioIn");
906 case OFFLOAD:
907 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800908 case MMAP:
909 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800910 default:
911 ALOG_ASSERT(false);
912 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100913 }
914}
915
Andy Hungdae27702016-10-31 14:01:16 -0700916void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800917{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800918 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800919 if (mPowerManager != 0) {
920 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700921 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
922 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700923 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100924 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700925 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700926 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800927 if (status == NO_ERROR) {
928 mWakeLockToken = binder;
929 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800930 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 }
Wei Jia3f273d12015-11-24 09:06:49 -0800932
Andy Hung3f0c9022016-01-15 17:49:46 -0800933 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800934 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
935 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800936}
937
938void AudioFlinger::ThreadBase::releaseWakeLock()
939{
940 Mutex::Autolock _l(mLock);
941 releaseWakeLock_l();
942}
943
944void AudioFlinger::ThreadBase::releaseWakeLock_l()
945{
Andy Hung3f0c9022016-01-15 17:49:46 -0800946 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800947 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800948 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800949 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700950 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
951 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800952 }
953 mWakeLockToken.clear();
954 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800955}
956
957void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700958 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800959 // use checkService() to avoid blocking if power service is not up yet
960 sp<IBinder> binder =
961 defaultServiceManager()->checkService(String16("power"));
962 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800963 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800964 } else {
965 mPowerManager = interface_cast<IPowerManager>(binder);
966 binder->linkToDeath(mDeathRecipient);
967 }
968 }
969}
970
Andy Hungd01b0f12016-11-07 16:10:30 -0800971void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800972 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700973
974#if !LOG_NDEBUG
975 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800976 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700977 s << uid << " ";
978 }
979 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
980#endif
981
Andy Hung438e7572015-12-14 15:51:17 -0800982 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
983 if (mSystemReady) {
984 ALOGE("no wake lock to update, but system ready!");
985 } else {
986 ALOGW("no wake lock to update, system not ready yet");
987 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800988 return;
989 }
990 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800991 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
992 status_t status = mPowerManager->updateWakeLockUids(
993 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
994 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800995 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800996 }
997}
998
Eric Laurent81784c32012-11-19 14:55:58 -0800999void AudioFlinger::ThreadBase::clearPowerManager()
1000{
1001 Mutex::Autolock _l(mLock);
1002 releaseWakeLock_l();
1003 mPowerManager.clear();
1004}
1005
Glenn Kasten0f11b512014-01-31 16:18:54 -08001006void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001007{
1008 sp<ThreadBase> thread = mThread.promote();
1009 if (thread != 0) {
1010 thread->clearPowerManager();
1011 }
1012 ALOGW("power manager service died !!!");
1013}
1014
Eric Laurent81784c32012-11-19 14:55:58 -08001015void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001016 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001017{
1018 sp<EffectChain> chain = getEffectChain_l(sessionId);
1019 if (chain != 0) {
1020 if (type != NULL) {
1021 chain->setEffectSuspended_l(type, suspend);
1022 } else {
1023 chain->setEffectSuspendedAll_l(suspend);
1024 }
1025 }
1026
1027 updateSuspendedSessions_l(type, suspend, sessionId);
1028}
1029
1030void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1031{
1032 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1033 if (index < 0) {
1034 return;
1035 }
1036
1037 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1038 mSuspendedSessions.valueAt(index);
1039
1040 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001041 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001042 for (int j = 0; j < desc->mRefCount; j++) {
1043 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1044 chain->setEffectSuspendedAll_l(true);
1045 } else {
1046 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1047 desc->mType.timeLow);
1048 chain->setEffectSuspended_l(&desc->mType, true);
1049 }
1050 }
1051 }
1052}
1053
1054void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1055 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001056 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001057{
1058 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1059
1060 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1061
1062 if (suspend) {
1063 if (index >= 0) {
1064 sessionEffects = mSuspendedSessions.valueAt(index);
1065 } else {
1066 mSuspendedSessions.add(sessionId, sessionEffects);
1067 }
1068 } else {
1069 if (index < 0) {
1070 return;
1071 }
1072 sessionEffects = mSuspendedSessions.valueAt(index);
1073 }
1074
1075
1076 int key = EffectChain::kKeyForSuspendAll;
1077 if (type != NULL) {
1078 key = type->timeLow;
1079 }
1080 index = sessionEffects.indexOfKey(key);
1081
1082 sp<SuspendedSessionDesc> desc;
1083 if (suspend) {
1084 if (index >= 0) {
1085 desc = sessionEffects.valueAt(index);
1086 } else {
1087 desc = new SuspendedSessionDesc();
1088 if (type != NULL) {
1089 desc->mType = *type;
1090 }
1091 sessionEffects.add(key, desc);
1092 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1093 }
1094 desc->mRefCount++;
1095 } else {
1096 if (index < 0) {
1097 return;
1098 }
1099 desc = sessionEffects.valueAt(index);
1100 if (--desc->mRefCount == 0) {
1101 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1102 sessionEffects.removeItemsAt(index);
1103 if (sessionEffects.isEmpty()) {
1104 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1105 sessionId);
1106 mSuspendedSessions.removeItem(sessionId);
1107 }
1108 }
1109 }
1110 if (!sessionEffects.isEmpty()) {
1111 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1112 }
1113}
1114
1115void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1116 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001117 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001118{
1119 Mutex::Autolock _l(mLock);
1120 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1121}
1122
1123void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1124 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001125 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001126{
1127 if (mType != RECORD) {
1128 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1129 // another session. This gives the priority to well behaved effect control panels
1130 // and applications not using global effects.
1131 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1132 // global effects
1133 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1134 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1135 }
1136 }
1137
1138 sp<EffectChain> chain = getEffectChain_l(sessionId);
1139 if (chain != 0) {
1140 chain->checkSuspendOnEffectEnabled(effect, enabled);
1141 }
1142}
1143
Eric Laurent4c415062016-06-17 16:14:16 -07001144// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1145status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1146 const effect_descriptor_t *desc, audio_session_t sessionId)
1147{
1148 // No global effect sessions on record threads
1149 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1150 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1151 desc->name, mThreadName);
1152 return BAD_VALUE;
1153 }
1154 // only pre processing effects on record thread
1155 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1156 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1157 desc->name, mThreadName);
1158 return BAD_VALUE;
1159 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001160
1161 // always allow effects without processing load or latency
1162 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1163 return NO_ERROR;
1164 }
1165
Eric Laurent4c415062016-06-17 16:14:16 -07001166 audio_input_flags_t flags = mInput->flags;
1167 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1168 if (flags & AUDIO_INPUT_FLAG_RAW) {
1169 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1170 desc->name, mThreadName);
1171 return BAD_VALUE;
1172 }
1173 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1174 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1175 desc->name, mThreadName);
1176 return BAD_VALUE;
1177 }
1178 }
1179 return NO_ERROR;
1180}
1181
1182// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1183status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1184 const effect_descriptor_t *desc, audio_session_t sessionId)
1185{
1186 // no preprocessing on playback threads
1187 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1188 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1189 " thread %s", desc->name, mThreadName);
1190 return BAD_VALUE;
1191 }
1192
Eric Laurent3e4de772017-07-16 16:55:08 -07001193 // always allow effects without processing load or latency
1194 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1195 return NO_ERROR;
1196 }
1197
Eric Laurent4c415062016-06-17 16:14:16 -07001198 switch (mType) {
1199 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001200#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001201 // Reject any effect on mixer multichannel sinks.
1202 // TODO: fix both format and multichannel issues with effects.
1203 if (mChannelCount != FCC_2) {
1204 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1205 " thread %s", desc->name, mChannelCount, mThreadName);
1206 return BAD_VALUE;
1207 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001208#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001209 audio_output_flags_t flags = mOutput->flags;
1210 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1211 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1212 // global effects are applied only to non fast tracks if they are SW
1213 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1214 break;
1215 }
1216 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1217 // only post processing on output stage session
1218 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1219 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1220 " on output stage session", desc->name);
1221 return BAD_VALUE;
1222 }
1223 } else {
1224 // no restriction on effects applied on non fast tracks
1225 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1226 break;
1227 }
1228 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001229
Eric Laurent4c415062016-06-17 16:14:16 -07001230 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1231 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1232 desc->name);
1233 return BAD_VALUE;
1234 }
1235 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1236 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1237 " in fast mode", desc->name);
1238 return BAD_VALUE;
1239 }
1240 }
1241 } break;
1242 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001243 // nothing actionable on offload threads, if the effect:
1244 // - is offloadable: the effect can be created
1245 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1246 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001247 break;
1248 case DIRECT:
1249 // Reject any effect on Direct output threads for now, since the format of
1250 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1251 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1252 desc->name, mThreadName);
1253 return BAD_VALUE;
1254 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001255#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001256 // Reject any effect on mixer multichannel sinks.
1257 // TODO: fix both format and multichannel issues with effects.
1258 if (mChannelCount != FCC_2) {
1259 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1260 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1261 return BAD_VALUE;
1262 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001263#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001264 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1265 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1266 " thread %s", desc->name, mThreadName);
1267 return BAD_VALUE;
1268 }
1269 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1270 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1271 " DUPLICATING thread %s", desc->name, mThreadName);
1272 return BAD_VALUE;
1273 }
1274 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1275 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1276 " DUPLICATING thread %s", desc->name, mThreadName);
1277 return BAD_VALUE;
1278 }
1279 break;
1280 default:
1281 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1282 }
1283
1284 return NO_ERROR;
1285}
1286
Eric Laurent81784c32012-11-19 14:55:58 -08001287// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1288sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1289 const sp<AudioFlinger::Client>& client,
1290 const sp<IEffectClient>& effectClient,
1291 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001292 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001293 effect_descriptor_t *desc,
1294 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001295 status_t *status,
1296 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001297{
1298 sp<EffectModule> effect;
1299 sp<EffectHandle> handle;
1300 status_t lStatus;
1301 sp<EffectChain> chain;
1302 bool chainCreated = false;
1303 bool effectCreated = false;
1304 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001305 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001306
1307 lStatus = initCheck();
1308 if (lStatus != NO_ERROR) {
1309 ALOGW("createEffect_l() Audio driver not initialized.");
1310 goto Exit;
1311 }
1312
Eric Laurent81784c32012-11-19 14:55:58 -08001313 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1314
1315 { // scope for mLock
1316 Mutex::Autolock _l(mLock);
1317
Eric Laurent4c415062016-06-17 16:14:16 -07001318 lStatus = checkEffectCompatibility_l(desc, sessionId);
1319 if (lStatus != NO_ERROR) {
1320 goto Exit;
1321 }
1322
Eric Laurent81784c32012-11-19 14:55:58 -08001323 // check for existing effect chain with the requested audio session
1324 chain = getEffectChain_l(sessionId);
1325 if (chain == 0) {
1326 // create a new chain for this session
1327 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1328 chain = new EffectChain(this, sessionId);
1329 addEffectChain_l(chain);
1330 chain->setStrategy(getStrategyForSession_l(sessionId));
1331 chainCreated = true;
1332 } else {
1333 effect = chain->getEffectFromDesc_l(desc);
1334 }
1335
1336 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1337
1338 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001339 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001340 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001341 lStatus = AudioSystem::registerEffect(
1342 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001343 if (lStatus != NO_ERROR) {
1344 goto Exit;
1345 }
1346 effectRegistered = true;
1347 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001348 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001349 if (lStatus != NO_ERROR) {
1350 goto Exit;
1351 }
1352 effectCreated = true;
1353
1354 effect->setDevice(mOutDevice);
1355 effect->setDevice(mInDevice);
1356 effect->setMode(mAudioFlinger->getMode());
1357 effect->setAudioSource(mAudioSource);
1358 }
1359 // create effect handle and connect it to effect module
1360 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001361 lStatus = handle->initCheck();
1362 if (lStatus == OK) {
1363 lStatus = effect->addHandle(handle.get());
1364 }
Eric Laurent81784c32012-11-19 14:55:58 -08001365 if (enabled != NULL) {
1366 *enabled = (int)effect->isEnabled();
1367 }
1368 }
1369
1370Exit:
1371 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1372 Mutex::Autolock _l(mLock);
1373 if (effectCreated) {
1374 chain->removeEffect_l(effect);
1375 }
1376 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001377 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001378 }
1379 if (chainCreated) {
1380 removeEffectChain_l(chain);
1381 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001382 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001383 }
1384
Glenn Kasten9156ef32013-08-06 15:39:08 -07001385 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001386 return handle;
1387}
1388
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001389void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1390 bool unpinIfLast)
1391{
1392 bool remove = false;
1393 sp<EffectModule> effect;
1394 {
1395 Mutex::Autolock _l(mLock);
1396
1397 effect = handle->effect().promote();
1398 if (effect == 0) {
1399 return;
1400 }
1401 // restore suspended effects if the disconnected handle was enabled and the last one.
1402 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1403 if (remove) {
1404 removeEffect_l(effect, true);
1405 }
1406 }
1407 if (remove) {
1408 mAudioFlinger->updateOrphanEffectChains(effect);
1409 AudioSystem::unregisterEffect(effect->id());
1410 if (handle->enabled()) {
1411 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1412 }
1413 }
1414}
1415
Glenn Kastend848eb42016-03-08 13:42:11 -08001416sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1417 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001418{
1419 Mutex::Autolock _l(mLock);
1420 return getEffect_l(sessionId, effectId);
1421}
1422
Glenn Kastend848eb42016-03-08 13:42:11 -08001423sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1424 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001425{
1426 sp<EffectChain> chain = getEffectChain_l(sessionId);
1427 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1428}
1429
1430// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1431// PlaybackThread::mLock held
1432status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1433{
1434 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001435 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001436 sp<EffectChain> chain = getEffectChain_l(sessionId);
1437 bool chainCreated = false;
1438
Eric Laurent5baf2af2013-09-12 17:37:00 -07001439 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001440 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001441 this, effect->desc().name, effect->desc().flags);
1442
Eric Laurent81784c32012-11-19 14:55:58 -08001443 if (chain == 0) {
1444 // create a new chain for this session
1445 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1446 chain = new EffectChain(this, sessionId);
1447 addEffectChain_l(chain);
1448 chain->setStrategy(getStrategyForSession_l(sessionId));
1449 chainCreated = true;
1450 }
1451 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1452
1453 if (chain->getEffectFromId_l(effect->id()) != 0) {
1454 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1455 this, effect->desc().name, chain.get());
1456 return BAD_VALUE;
1457 }
1458
Eric Laurent5baf2af2013-09-12 17:37:00 -07001459 effect->setOffloaded(mType == OFFLOAD, mId);
1460
Eric Laurent81784c32012-11-19 14:55:58 -08001461 status_t status = chain->addEffect_l(effect);
1462 if (status != NO_ERROR) {
1463 if (chainCreated) {
1464 removeEffectChain_l(chain);
1465 }
1466 return status;
1467 }
1468
1469 effect->setDevice(mOutDevice);
1470 effect->setDevice(mInDevice);
1471 effect->setMode(mAudioFlinger->getMode());
1472 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001473
Eric Laurent81784c32012-11-19 14:55:58 -08001474 return NO_ERROR;
1475}
1476
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001477void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001478
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001479 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001480 effect_descriptor_t desc = effect->desc();
1481 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1482 detachAuxEffect_l(effect->id());
1483 }
1484
1485 sp<EffectChain> chain = effect->chain().promote();
1486 if (chain != 0) {
1487 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001488 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001489 removeEffectChain_l(chain);
1490 }
1491 } else {
1492 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1493 }
1494}
1495
1496void AudioFlinger::ThreadBase::lockEffectChains_l(
1497 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1498{
1499 effectChains = mEffectChains;
1500 for (size_t i = 0; i < mEffectChains.size(); i++) {
1501 mEffectChains[i]->lock();
1502 }
1503}
1504
1505void AudioFlinger::ThreadBase::unlockEffectChains(
1506 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1507{
1508 for (size_t i = 0; i < effectChains.size(); i++) {
1509 effectChains[i]->unlock();
1510 }
1511}
1512
Glenn Kastend848eb42016-03-08 13:42:11 -08001513sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001514{
1515 Mutex::Autolock _l(mLock);
1516 return getEffectChain_l(sessionId);
1517}
1518
Glenn Kastend848eb42016-03-08 13:42:11 -08001519sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1520 const
Eric Laurent81784c32012-11-19 14:55:58 -08001521{
1522 size_t size = mEffectChains.size();
1523 for (size_t i = 0; i < size; i++) {
1524 if (mEffectChains[i]->sessionId() == sessionId) {
1525 return mEffectChains[i];
1526 }
1527 }
1528 return 0;
1529}
1530
1531void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1532{
1533 Mutex::Autolock _l(mLock);
1534 size_t size = mEffectChains.size();
1535 for (size_t i = 0; i < size; i++) {
1536 mEffectChains[i]->setMode_l(mode);
1537 }
1538}
1539
Mikhail Naganovdc769682018-05-04 15:34:08 -07001540void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001541{
1542 config->type = AUDIO_PORT_TYPE_MIX;
1543 config->ext.mix.handle = mId;
1544 config->sample_rate = mSampleRate;
1545 config->format = mFormat;
1546 config->channel_mask = mChannelMask;
1547 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1548 AUDIO_PORT_CONFIG_FORMAT;
1549}
1550
Eric Laurent72e3f392015-05-20 14:43:50 -07001551void AudioFlinger::ThreadBase::systemReady()
1552{
1553 Mutex::Autolock _l(mLock);
1554 if (mSystemReady) {
1555 return;
1556 }
1557 mSystemReady = true;
1558
1559 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1560 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1561 }
1562 mPendingConfigEvents.clear();
1563}
1564
Andy Hungdae27702016-10-31 14:01:16 -07001565template <typename T>
1566ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1567 ssize_t index = mActiveTracks.indexOf(track);
1568 if (index >= 0) {
1569 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1570 return index;
1571 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001572 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001573 mActiveTracksGeneration++;
1574 mLatestActiveTrack = track;
1575 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001576 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001577 return mActiveTracks.add(track);
1578}
1579
1580template <typename T>
1581ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1582 ssize_t index = mActiveTracks.remove(track);
1583 if (index < 0) {
1584 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1585 return index;
1586 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001587 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001588 mActiveTracksGeneration++;
1589 --mBatteryCounter[track->uid()].second;
1590 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001591 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001592#ifdef TEE_SINK
1593 track->dumpTee(-1 /* fd */, "_REMOVE");
1594#endif
Andy Hungdae27702016-10-31 14:01:16 -07001595 return index;
1596}
1597
1598template <typename T>
1599void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1600 for (const sp<T> &track : mActiveTracks) {
1601 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001602 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001603 }
1604 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001605 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001606 mActiveTracks.clear();
1607 mLatestActiveTrack.clear();
1608 mBatteryCounter.clear();
1609}
1610
1611template <typename T>
1612void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1613 sp<ThreadBase> thread, bool force) {
1614 // Updates ActiveTracks client uids to the thread wakelock.
1615 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1616 thread->updateWakeLockUids_l(getWakeLockUids());
1617 mLastActiveTracksGeneration = mActiveTracksGeneration;
1618 }
1619
1620 // Updates BatteryNotifier uids
1621 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1622 const uid_t uid = it->first;
1623 ssize_t &previous = it->second.first;
1624 ssize_t &current = it->second.second;
1625 if (current > 0) {
1626 if (previous == 0) {
1627 BatteryNotifier::getInstance().noteStartAudio(uid);
1628 }
1629 previous = current;
1630 ++it;
1631 } else if (current == 0) {
1632 if (previous > 0) {
1633 BatteryNotifier::getInstance().noteStopAudio(uid);
1634 }
1635 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1636 } else /* (current < 0) */ {
1637 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1638 }
1639 }
1640}
Eric Laurent83b88082014-06-20 18:31:16 -07001641
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001642template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001643bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1644 const bool hasChanged = mHasChanged;
1645 mHasChanged = false;
1646 return hasChanged;
1647}
1648
1649template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001650void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1651 const char *funcName, const sp<T> &track) const {
1652 if (mLocalLog != nullptr) {
1653 String8 result;
1654 track->appendDump(result, false /* active */);
1655 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1656 }
1657}
1658
Eric Laurent6acd1d42017-01-04 14:23:29 -08001659void AudioFlinger::ThreadBase::broadcast_l()
1660{
1661 // Thread could be blocked waiting for async
1662 // so signal it to handle state changes immediately
1663 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1664 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1665 mSignalPending = true;
1666 mWaitWorkCV.broadcast();
1667}
1668
Eric Laurent81784c32012-11-19 14:55:58 -08001669// ----------------------------------------------------------------------------
1670// Playback
1671// ----------------------------------------------------------------------------
1672
1673AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1674 AudioStreamOut* output,
1675 audio_io_handle_t id,
1676 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001677 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001678 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001679 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001680 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001681 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001682 mMixerBuffer(NULL),
1683 mMixerBufferSize(0),
1684 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1685 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001686 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001687 mEffectBuffer(NULL),
1688 mEffectBufferSize(0),
1689 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1690 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001691 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001692 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001693 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001694 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001695 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001696 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001697 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001698 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001699 mMixerStatus(MIXER_IDLE),
1700 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001701 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001702 mBytesRemaining(0),
1703 mCurrentWriteLength(0),
1704 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001705 mWriteAckSequence(0),
1706 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001707 mScreenState(AudioFlinger::mScreenState),
1708 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001709 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001710 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1711 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001712{
Glenn Kastend7dca052015-03-05 16:05:54 -08001713 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1714 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001715
1716 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1717 // it would be safer to explicitly pass initial masterVolume/masterMute as
1718 // parameter.
1719 //
1720 // If the HAL we are using has support for master volume or master mute,
1721 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1722 // and the mute set to false).
1723 mMasterVolume = audioFlinger->masterVolume_l();
1724 mMasterMute = audioFlinger->masterMute_l();
1725 if (mOutput && mOutput->audioHwDev) {
1726 if (mOutput->audioHwDev->canSetMasterVolume()) {
1727 mMasterVolume = 1.0;
1728 }
1729
1730 if (mOutput->audioHwDev->canSetMasterMute()) {
1731 mMasterMute = false;
1732 }
1733 }
1734
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001735 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001736
Eric Laurent223fd5c2014-11-11 13:43:36 -08001737 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001738 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001739 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001740 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001741 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1742 }
Eric Laurent98e38192018-02-15 18:31:53 -08001743 // Audio patch volume is always max
1744 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1745 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001746}
1747
1748AudioFlinger::PlaybackThread::~PlaybackThread()
1749{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001750 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001751 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001752 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001753 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001754}
1755
1756void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1757{
1758 dumpInternals(fd, args);
1759 dumpTracks(fd, args);
1760 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001761 dprintf(fd, " Local log:\n");
1762 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001763}
1764
Eric Tan7b651152018-07-13 10:17:19 -07001765std::string AudioFlinger::PlaybackThread::getJsonString() const
1766{
1767 return "{}";
1768}
1769
Glenn Kasten0f11b512014-01-31 16:18:54 -08001770void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001771{
Eric Laurent81784c32012-11-19 14:55:58 -08001772 String8 result;
1773
Marco Nelissenb2208842014-02-07 14:00:50 -08001774 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001775 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1776 const stream_type_t *st = &mStreamTypes[i];
1777 if (i > 0) {
1778 result.appendFormat(", ");
1779 }
1780 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1781 if (st->mute) {
1782 result.append("M");
1783 }
1784 }
1785 result.append("\n");
1786 write(fd, result.string(), result.length());
1787 result.clear();
1788
Eric Laurent81784c32012-11-19 14:55:58 -08001789 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1790 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001791 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001792 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001793
1794 size_t numtracks = mTracks.size();
1795 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001796 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001797 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001798 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001799 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001800 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001801 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001802 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001803 for (size_t i = 0; i < numtracks; ++i) {
1804 sp<Track> track = mTracks[i];
1805 if (track != 0) {
1806 bool active = mActiveTracks.indexOf(track) >= 0;
1807 if (active) {
1808 numactiveseen++;
1809 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001810 result.append(prefix);
1811 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001812 }
1813 }
1814 } else {
1815 result.append("\n");
1816 }
1817 if (numactiveseen != numactive) {
1818 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001819 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001820 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001821 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001822 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001823 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001824 sp<Track> track = mActiveTracks[i];
1825 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001826 result.append(prefix);
1827 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001828 }
1829 }
1830 }
1831
1832 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001833}
1834
1835void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1836{
Glenn Kasten44182c22015-03-05 17:12:23 -08001837 dumpBase(fd, args);
1838
Elliott Hughes87cebad2014-05-22 10:14:43 -07001839 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001840 dprintf(fd, " Last write occurred (msecs): %llu\n",
1841 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001842 dprintf(fd, " Total writes: %d\n", mNumWrites);
1843 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1844 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1845 dprintf(fd, " Suspend count: %d\n", mSuspended);
1846 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1847 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1848 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1849 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001850 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001851 AudioStreamOut *output = mOutput;
1852 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001853 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1854 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001855 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1856 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1857 if (mPipeSink.get() != nullptr) {
1858 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1859 }
1860 if (output != nullptr) {
1861 dprintf(fd, " Hal stream dump:\n");
1862 (void)output->stream->dump(fd);
1863 }
Eric Laurent81784c32012-11-19 14:55:58 -08001864}
1865
1866// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001867
1868void AudioFlinger::PlaybackThread::onFirstRef()
1869{
Glenn Kastend7dca052015-03-05 16:05:54 -08001870 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001871}
1872
1873// ThreadBase virtuals
1874void AudioFlinger::PlaybackThread::preExit()
1875{
1876 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001877 // FIXME this is using hard-coded strings but in the future, this functionality will be
1878 // converted to use audio HAL extensions required to support tunneling
1879 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1880 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001881}
1882
1883// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1884sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1885 const sp<AudioFlinger::Client>& client,
1886 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001887 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001888 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001889 audio_format_t format,
1890 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001891 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001892 size_t *pNotificationFrameCount,
1893 uint32_t notificationsPerBuffer,
1894 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001895 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001896 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001897 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001898 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001899 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001900 status_t *status,
1901 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001902{
Glenn Kasten74935e42013-12-19 08:56:45 -08001903 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001904 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001905 sp<Track> track;
1906 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001907 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001908 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001909 uint32_t sampleRate;
1910
1911 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1912 lStatus = BAD_VALUE;
1913 goto Exit;
1914 }
Eric Laurent21da6472017-11-09 16:29:26 -08001915
1916 if (*pSampleRate == 0) {
1917 *pSampleRate = mSampleRate;
1918 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001919 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001920
1921 // special case for FAST flag considered OK if fast mixer is present
1922 if (hasFastMixer()) {
1923 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1924 }
1925
1926 // Check if requested flags are compatible with output stream flags
1927 if ((*flags & outputFlags) != *flags) {
1928 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1929 *flags, outputFlags);
1930 *flags = (audio_output_flags_t)(*flags & outputFlags);
1931 }
Eric Laurent81784c32012-11-19 14:55:58 -08001932
Eric Laurent81784c32012-11-19 14:55:58 -08001933 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001934 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001935 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001936 // PCM data
1937 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001938 // TODO: extract as a data library function that checks that a computationally
1939 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001940 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001941 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1942 (channelMask == AUDIO_CHANNEL_OUT_MONO
1943 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001944 // hardware sample rate
1945 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001946 // normal mixer has an associated fast mixer
1947 hasFastMixer() &&
1948 // there are sufficient fast track slots available
1949 (mFastTrackAvailMask != 0)
1950 // FIXME test that MixerThread for this fast track has a capable output HAL
1951 // FIXME add a permission test also?
1952 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001953 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1954 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001955 // read the fast track multiplier property the first time it is needed
1956 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1957 if (ok != 0) {
1958 ALOGE("%s pthread_once failed: %d", __func__, ok);
1959 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001960 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001961 }
Eric Laurent4c415062016-06-17 16:14:16 -07001962
1963 // check compatibility with audio effects.
1964 { // scope for mLock
1965 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001966 for (audio_session_t session : {
1967 AUDIO_SESSION_OUTPUT_STAGE,
1968 AUDIO_SESSION_OUTPUT_MIX,
1969 sessionId,
1970 }) {
1971 sp<EffectChain> chain = getEffectChain_l(session);
1972 if (chain.get() != nullptr) {
1973 audio_output_flags_t old = *flags;
1974 chain->checkOutputFlagCompatibility(flags);
1975 if (old != *flags) {
1976 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1977 (int)session, (int)old, (int)*flags);
1978 }
Eric Laurent4c415062016-06-17 16:14:16 -07001979 }
1980 }
1981 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001982 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001983 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1984 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001985 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001986 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1987 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001988 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001989 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001990 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001991 audio_is_linear_pcm(format),
1992 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001993 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001994 }
1995 }
Eric Laurent21da6472017-11-09 16:29:26 -08001996
1997 if (!audio_has_proportional_frames(format)) {
1998 if (sharedBuffer != 0) {
1999 // Same comment as below about ignoring frameCount parameter for set()
2000 frameCount = sharedBuffer->size();
2001 } else if (frameCount == 0) {
2002 frameCount = mNormalFrameCount;
2003 }
2004 if (notificationFrameCount != frameCount) {
2005 notificationFrameCount = frameCount;
2006 }
2007 } else if (sharedBuffer != 0) {
2008 // FIXME: Ensure client side memory buffers need
2009 // not have additional alignment beyond sample
2010 // (e.g. 16 bit stereo accessed as 32 bit frame).
2011 size_t alignment = audio_bytes_per_sample(format);
2012 if (alignment & 1) {
2013 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2014 alignment = 1;
2015 }
2016 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2017 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2018 if (channelCount > 1) {
2019 // More than 2 channels does not require stronger alignment than stereo
2020 alignment <<= 1;
2021 }
2022 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2023 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2024 sharedBuffer->pointer(), channelCount);
2025 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002026 goto Exit;
2027 }
Eric Laurent21da6472017-11-09 16:29:26 -08002028
2029 // When initializing a shared buffer AudioTrack via constructors,
2030 // there's no frameCount parameter.
2031 // But when initializing a shared buffer AudioTrack via set(),
2032 // there _is_ a frameCount parameter. We silently ignore it.
2033 frameCount = sharedBuffer->size() / frameSize;
2034 } else {
2035 size_t minFrameCount = 0;
2036 // For fast tracks we try to respect the application's request for notifications per buffer.
2037 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2038 if (notificationsPerBuffer > 0) {
2039 // Avoid possible arithmetic overflow during multiplication.
2040 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2041 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2042 notificationsPerBuffer, mFrameCount);
2043 } else {
2044 minFrameCount = mFrameCount * notificationsPerBuffer;
2045 }
2046 }
2047 } else {
2048 // For normal PCM streaming tracks, update minimum frame count.
2049 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2050 // cover audio hardware latency.
2051 // This is probably too conservative, but legacy application code may depend on it.
2052 // If you change this calculation, also review the start threshold which is related.
2053 uint32_t latencyMs = latency_l();
2054 if (latencyMs == 0) {
2055 ALOGE("Error when retrieving output stream latency");
2056 lStatus = UNKNOWN_ERROR;
2057 goto Exit;
2058 }
2059
2060 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2061 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2062
Eric Laurent81784c32012-11-19 14:55:58 -08002063 }
Eric Laurent21da6472017-11-09 16:29:26 -08002064 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002065 frameCount = minFrameCount;
2066 }
Eric Laurent81784c32012-11-19 14:55:58 -08002067 }
Eric Laurent21da6472017-11-09 16:29:26 -08002068
2069 // Make sure that application is notified with sufficient margin before underrun.
2070 // The client can divide the AudioTrack buffer into sub-buffers,
2071 // and expresses its desire to server as the notification frame count.
2072 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2073 size_t maxNotificationFrames;
2074 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2075 // notify every HAL buffer, regardless of the size of the track buffer
2076 maxNotificationFrames = mFrameCount;
2077 } else {
2078 // For normal tracks, use at least double-buffering if no sample rate conversion,
2079 // or at least triple-buffering if there is sample rate conversion
2080 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2081 maxNotificationFrames = frameCount / nBuffering;
2082 // If client requested a fast track but this was denied, then use the smaller maximum.
2083 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2084 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2085 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2086 maxNotificationFrames = maxNotificationFramesFastDenied;
2087 }
2088 }
2089 }
2090 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2091 if (notificationFrameCount == 0) {
2092 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2093 maxNotificationFrames, frameCount);
2094 } else {
2095 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2096 notificationFrameCount, maxNotificationFrames, frameCount);
2097 }
2098 notificationFrameCount = maxNotificationFrames;
2099 }
2100 }
2101
Glenn Kasten74935e42013-12-19 08:56:45 -08002102 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002103 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002104
Glenn Kastenc3df8382014-03-13 15:05:25 -07002105 switch (mType) {
2106
2107 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002108 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002109 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002110 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2111 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002112 sampleRate, format, channelMask, mOutput, mFormat);
2113 lStatus = BAD_VALUE;
2114 goto Exit;
2115 }
2116 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002117 break;
2118
2119 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002120 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002121 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2122 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002123 sampleRate, format, channelMask, mOutput, mFormat);
2124 lStatus = BAD_VALUE;
2125 goto Exit;
2126 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002127 break;
2128
2129 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002130 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002131 ALOGE("createTrack_l() Bad parameter: format %#x \""
2132 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002133 format, mOutput, mFormat);
2134 lStatus = BAD_VALUE;
2135 goto Exit;
2136 }
Andy Hungcd044842014-08-07 11:04:34 -07002137 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002138 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2139 lStatus = BAD_VALUE;
2140 goto Exit;
2141 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002142 break;
2143
Eric Laurent81784c32012-11-19 14:55:58 -08002144 }
2145
2146 lStatus = initCheck();
2147 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002148 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002149 goto Exit;
2150 }
2151
2152 { // scope for mLock
2153 Mutex::Autolock _l(mLock);
2154
2155 // all tracks in same audio session must share the same routing strategy otherwise
2156 // conflicts will happen when tracks are moved from one output to another by audio policy
2157 // manager
2158 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2159 for (size_t i = 0; i < mTracks.size(); ++i) {
2160 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002161 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002162 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2163 if (sessionId == t->sessionId() && strategy != actual) {
2164 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2165 strategy, actual);
2166 lStatus = BAD_VALUE;
2167 goto Exit;
2168 }
2169 }
2170 }
2171
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002172 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002173 channelMask, frameCount,
2174 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002175 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002176
Glenn Kasten03003332013-08-06 15:40:54 -07002177 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2178 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002179 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002180 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002181 goto Exit;
2182 }
2183 mTracks.add(track);
2184
2185 sp<EffectChain> chain = getEffectChain_l(sessionId);
2186 if (chain != 0) {
2187 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2188 track->setMainBuffer(chain->inBuffer());
2189 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2190 chain->incTrackCnt();
2191 }
2192
Eric Laurent05067782016-06-01 18:27:28 -07002193 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002194 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2195 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2196 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002197 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002198 }
2199 }
2200
2201 lStatus = NO_ERROR;
2202
2203Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002204 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002205 return track;
2206}
2207
Andy Hung1bc088a2018-02-09 15:57:31 -08002208template<typename T>
2209ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track)
2210{
2211 const ssize_t index = mTracks.add(track);
2212 if (index >= 0) {
2213 // set name for track when adding.
2214 int name;
2215 if (mUnusedTrackNames.empty()) {
2216 name = mTracks.size() - 1; // new name {0 ... size-1}.
2217 } else {
2218 // reuse smallest name for deleted track.
2219 auto it = mUnusedTrackNames.begin();
2220 name = *it;
2221 (void)mUnusedTrackNames.erase(it);
2222 }
2223 track->setName(name);
2224 } else {
2225 LOG_ALWAYS_FATAL("cannot add track");
2226 }
2227 return index;
2228}
2229
2230template<typename T>
2231ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2232{
2233 const int name = track->name();
2234 const ssize_t index = mTracks.remove(track);
2235 if (index >= 0) {
2236 // invalidate name when removing from mTracks.
2237 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name);
2238
2239 if (mSaveDeletedTrackNames) {
2240 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2241 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update,
2242 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2243 mDeletedTrackNames.emplace(name);
2244 }
2245
2246 mUnusedTrackNames.emplace(name);
2247 track->setName(T::TRACK_NAME_PENDING);
2248 } else {
2249 LOG_ALWAYS_FATAL_IF(name >= 0,
2250 "valid name %d for track not in mTracks (returned %zd)", name, index);
2251 }
2252 return index;
2253}
2254
Eric Laurent81784c32012-11-19 14:55:58 -08002255uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2256{
2257 return latency;
2258}
2259
2260uint32_t AudioFlinger::PlaybackThread::latency() const
2261{
2262 Mutex::Autolock _l(mLock);
2263 return latency_l();
2264}
2265uint32_t AudioFlinger::PlaybackThread::latency_l() const
2266{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002267 uint32_t latency;
2268 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2269 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002270 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002271 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002272}
2273
2274void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2275{
2276 Mutex::Autolock _l(mLock);
2277 // Don't apply master volume in SW if our HAL can do it for us.
2278 if (mOutput && mOutput->audioHwDev &&
2279 mOutput->audioHwDev->canSetMasterVolume()) {
2280 mMasterVolume = 1.0;
2281 } else {
2282 mMasterVolume = value;
2283 }
2284}
2285
2286void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2287{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002288 if (isDuplicating()) {
2289 return;
2290 }
Eric Laurent81784c32012-11-19 14:55:58 -08002291 Mutex::Autolock _l(mLock);
2292 // Don't apply master mute in SW if our HAL can do it for us.
2293 if (mOutput && mOutput->audioHwDev &&
2294 mOutput->audioHwDev->canSetMasterMute()) {
2295 mMasterMute = false;
2296 } else {
2297 mMasterMute = muted;
2298 }
2299}
2300
2301void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2302{
2303 Mutex::Autolock _l(mLock);
2304 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002305 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002306}
2307
2308void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2309{
2310 Mutex::Autolock _l(mLock);
2311 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002312 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002313}
2314
2315float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2316{
2317 Mutex::Autolock _l(mLock);
2318 return mStreamTypes[stream].volume;
2319}
2320
2321// addTrack_l() must be called with ThreadBase::mLock held
2322status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2323{
2324 status_t status = ALREADY_EXISTS;
2325
Eric Laurent81784c32012-11-19 14:55:58 -08002326 if (mActiveTracks.indexOf(track) < 0) {
2327 // the track is newly added, make sure it fills up all its
2328 // buffers before playing. This is to ensure the client will
2329 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002330 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002331 TrackBase::track_state state = track->mState;
2332 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002333 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002334 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002335 mLock.lock();
2336 // abort track was stopped/paused while we released the lock
2337 if (state != track->mState) {
2338 if (status == NO_ERROR) {
2339 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002340 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002341 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002342 mLock.lock();
2343 }
2344 return INVALID_OPERATION;
2345 }
2346 // abort if start is rejected by audio policy manager
2347 if (status != NO_ERROR) {
2348 return PERMISSION_DENIED;
2349 }
2350#ifdef ADD_BATTERY_DATA
2351 // to track the speaker usage
2352 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2353#endif
2354 }
2355
Eric Laurent51716182016-02-29 18:00:56 -08002356 // set retry count for buffer fill
2357 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002358 if (track->isStopping_1()) {
2359 track->mRetryCount = kMaxTrackStopRetriesOffload;
2360 } else {
2361 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2362 }
2363 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002364 } else {
2365 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002366 track->mFillingUpStatus =
2367 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002368 }
2369
Eric Laurent81784c32012-11-19 14:55:58 -08002370 track->mResetDone = false;
2371 track->mPresentationCompleteFrames = 0;
2372 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002373 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2374 if (chain != 0) {
2375 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2376 track->sessionId());
2377 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002378 }
2379
2380 status = NO_ERROR;
2381 }
2382
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002383 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002384 return status;
2385}
2386
Eric Laurentbfb1b832013-01-07 09:53:42 -08002387bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002388{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002389 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002390 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002391 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2392 track->mState = TrackBase::STOPPED;
2393 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002394 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002395 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002396 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002397 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002398
2399 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002400}
2401
2402void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2403{
2404 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002405
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002406 String8 result;
2407 track->appendDump(result, false /* active */);
2408 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002409
Eric Laurent81784c32012-11-19 14:55:58 -08002410 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002411 if (track->isFastTrack()) {
2412 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002413 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002414 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2415 mFastTrackAvailMask |= 1 << index;
2416 // redundant as track is about to be destroyed, for dumpsys only
2417 track->mFastIndex = -1;
2418 }
2419 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2420 if (chain != 0) {
2421 chain->decTrackCnt();
2422 }
2423}
2424
2425String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2426{
Eric Laurent81784c32012-11-19 14:55:58 -08002427 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002428 String8 out_s8;
2429 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2430 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002431 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002432 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002433}
2434
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002435void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002436 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2437 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002438
Eric Laurent73e26b62015-04-27 16:55:58 -07002439 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002440
2441 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002442 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002443 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002444 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002445 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002446 desc->mChannelMask = mChannelMask;
2447 desc->mSamplingRate = mSampleRate;
2448 desc->mFormat = mFormat;
2449 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002451 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002452 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002453 break;
2454
Eric Laurent73e26b62015-04-27 16:55:58 -07002455 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002456 default:
2457 break;
2458 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002459 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002460}
2461
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002462void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002463{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002464 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002465}
2466
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002467void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002468{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002469 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002470}
2471
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002472void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002473{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002474 mCallbackThread->setAsyncError();
2475}
2476
Eric Laurent3b4529e2013-09-05 18:09:19 -07002477void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002478{
2479 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002480 // reject out of sequence requests
2481 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2482 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002483 mWaitWorkCV.signal();
2484 }
2485}
2486
Eric Laurent3b4529e2013-09-05 18:09:19 -07002487void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002488{
2489 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002490 // reject out of sequence requests
2491 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2492 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002493 mWaitWorkCV.signal();
2494 }
2495}
2496
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002497void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002498{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002499 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002500 mSampleRate = mOutput->getSampleRate();
2501 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002502 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002503 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002504 }
Andy Hung9a592762014-07-21 21:56:01 -07002505 if ((mType == MIXER || mType == DUPLICATING)
2506 && !isValidPcmSinkChannelMask(mChannelMask)) {
2507 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2508 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002509 }
Andy Hunge5412692014-05-16 11:25:07 -07002510 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002511
2512 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002513 status_t result = mOutput->stream->getFormat(&mHALFormat);
2514 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002515 // Get format from the shim, which will be different than the HAL format
2516 // if playing compressed audio over HDMI passthrough.
2517 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002518 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002519 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002520 }
Andy Hung6146c082014-03-18 11:56:15 -07002521 if ((mType == MIXER || mType == DUPLICATING)
2522 && !isValidPcmSinkFormat(mFormat)) {
2523 LOG_FATAL("HAL format %#x not supported for mixed output",
2524 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002525 }
Phil Burk062e67a2015-02-11 13:40:50 -08002526 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002527 result = mOutput->stream->getBufferSize(&mBufferSize);
2528 LOG_ALWAYS_FATAL_IF(result != OK,
2529 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002530 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002531 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002532 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002533 mFrameCount);
2534 }
2535
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002536 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2537 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002538 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002539 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002540 }
2541 }
2542
Eric Laurentd1f69b02014-12-15 14:33:13 -08002543 mHwSupportsPause = false;
2544 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002545 bool supportsPause = false, supportsResume = false;
2546 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2547 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002548 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002549 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002550 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002551 } else if (supportsResume) {
2552 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002553 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002554 }
2555 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002556 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2557 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2558 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002559
Andy Hungfbfc3952015-01-15 13:33:51 -08002560 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2561 // For best precision, we use float instead of the associated output
2562 // device format (typically PCM 16 bit).
2563
2564 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2565 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2566 mBufferSize = mFrameSize * mFrameCount;
2567
2568 // TODO: We currently use the associated output device channel mask and sample rate.
2569 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2570 // (if a valid mask) to avoid premature downmix.
2571 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2572 // instead of the output device sample rate to avoid loss of high frequency information.
2573 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2574 }
2575
Andy Hung09a50072014-02-27 14:30:47 -08002576 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002577 double multiplier = 1.0;
2578 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2579 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002580 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2581 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002582
Eric Laurent81784c32012-11-19 14:55:58 -08002583 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2584 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2585 maxNormalFrameCount = maxNormalFrameCount & ~15;
2586 if (maxNormalFrameCount < minNormalFrameCount) {
2587 maxNormalFrameCount = minNormalFrameCount;
2588 }
2589 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2590 if (multiplier <= 1.0) {
2591 multiplier = 1.0;
2592 } else if (multiplier <= 2.0) {
2593 if (2 * mFrameCount <= maxNormalFrameCount) {
2594 multiplier = 2.0;
2595 } else {
2596 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2597 }
2598 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002599 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002600 }
2601 }
2602 mNormalFrameCount = multiplier * mFrameCount;
2603 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002604 if (mType == MIXER || mType == DUPLICATING) {
2605 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2606 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002607 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002608 mNormalFrameCount);
2609
Andy Hung08fb1742015-05-31 23:22:10 -07002610 // Check if we want to throttle the processing to no more than 2x normal rate
2611 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002612 mThreadThrottleTimeMs = 0;
2613 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002614 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2615
Andy Hung010a1a12014-03-13 13:57:33 -07002616 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2617 // Originally this was int16_t[] array, need to remove legacy implications.
2618 free(mSinkBuffer);
2619 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002620 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2621 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2622 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002623 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002624
Andy Hung69aed5f2014-02-25 17:24:40 -08002625 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2626 // drives the output.
2627 free(mMixerBuffer);
2628 mMixerBuffer = NULL;
2629 if (mMixerBufferEnabled) {
2630 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2631 mMixerBufferSize = mNormalFrameCount * mChannelCount
2632 * audio_bytes_per_sample(mMixerBufferFormat);
2633 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2634 }
Andy Hung98ef9782014-03-04 14:46:50 -08002635 free(mEffectBuffer);
2636 mEffectBuffer = NULL;
2637 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002638 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002639 mEffectBufferSize = mNormalFrameCount * mChannelCount
2640 * audio_bytes_per_sample(mEffectBufferFormat);
2641 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2642 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002643
Eric Laurent81784c32012-11-19 14:55:58 -08002644 // force reconfiguration of effect chains and engines to take new buffer size and audio
2645 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002646 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002647 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2648 // matter.
2649 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2650 Vector< sp<EffectChain> > effectChains = mEffectChains;
2651 for (size_t i = 0; i < effectChains.size(); i ++) {
2652 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2653 }
2654}
2655
Kevin Rocard069c2712018-03-29 19:09:14 -07002656void AudioFlinger::PlaybackThread::updateMetadata_l()
2657{
Kevin Rocard12381092018-04-11 09:19:59 -07002658 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2659 return; // That should not happen
2660 }
2661 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2662 for (const sp<Track> &track : mActiveTracks) {
2663 // Do not short-circuit as all hasChanged states must be reset
2664 // as all the metadata are going to be sent
2665 hasChanged |= track->readAndClearHasChanged();
2666 }
2667 if (!hasChanged) {
2668 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002669 }
2670 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002671 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002672 for (const sp<Track> &track : mActiveTracks) {
2673 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002674 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002675 }
Kevin Rocard12381092018-04-11 09:19:59 -07002676 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002677}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002678
Kevin Rocard12381092018-04-11 09:19:59 -07002679void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2680 const StreamOutHalInterface::SourceMetadata& metadata)
2681{
2682 mOutput->stream->updateSourceMetadata(metadata);
2683};
2684
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002685status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002686{
2687 if (halFrames == NULL || dspFrames == NULL) {
2688 return BAD_VALUE;
2689 }
2690 Mutex::Autolock _l(mLock);
2691 if (initCheck() != NO_ERROR) {
2692 return INVALID_OPERATION;
2693 }
Andy Hung818e7a32016-02-16 18:08:07 -08002694 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002695 *halFrames = framesWritten;
2696
2697 if (isSuspended()) {
2698 // return an estimation of rendered frames when the output is suspended
2699 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002700 *dspFrames = (uint32_t)
2701 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002702 return NO_ERROR;
2703 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002704 status_t status;
2705 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002706 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002707 *dspFrames = (size_t)frames;
2708 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002709 }
2710}
2711
Eric Laurent4c415062016-06-17 16:14:16 -07002712// hasAudioSession_l() must be called with ThreadBase::mLock held
2713uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002714{
Eric Laurent81784c32012-11-19 14:55:58 -08002715 uint32_t result = 0;
2716 if (getEffectChain_l(sessionId) != 0) {
2717 result = EFFECT_SESSION;
2718 }
2719
2720 for (size_t i = 0; i < mTracks.size(); ++i) {
2721 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002722 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002723 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002724 if (track->isFastTrack()) {
2725 result |= FAST_SESSION;
2726 }
Eric Laurent81784c32012-11-19 14:55:58 -08002727 break;
2728 }
2729 }
2730
2731 return result;
2732}
2733
Glenn Kastend848eb42016-03-08 13:42:11 -08002734uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002735{
2736 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2737 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2738 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2739 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2740 }
2741 for (size_t i = 0; i < mTracks.size(); i++) {
2742 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002743 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002744 return AudioSystem::getStrategyForStream(track->streamType());
2745 }
2746 }
2747 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2748}
2749
2750
Phil Burk062e67a2015-02-11 13:40:50 -08002751AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002752{
2753 Mutex::Autolock _l(mLock);
2754 return mOutput;
2755}
2756
Phil Burk062e67a2015-02-11 13:40:50 -08002757AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002758{
2759 Mutex::Autolock _l(mLock);
2760 AudioStreamOut *output = mOutput;
2761 mOutput = NULL;
2762 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2763 // must push a NULL and wait for ack
2764 mOutputSink.clear();
2765 mPipeSink.clear();
2766 mNormalSink.clear();
2767 return output;
2768}
2769
2770// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002771sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002772{
2773 if (mOutput == NULL) {
2774 return NULL;
2775 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002776 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002777}
2778
2779uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2780{
2781 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2782}
2783
2784status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2785{
2786 if (!isValidSyncEvent(event)) {
2787 return BAD_VALUE;
2788 }
2789
2790 Mutex::Autolock _l(mLock);
2791
2792 for (size_t i = 0; i < mTracks.size(); ++i) {
2793 sp<Track> track = mTracks[i];
2794 if (event->triggerSession() == track->sessionId()) {
2795 (void) track->setSyncEvent(event);
2796 return NO_ERROR;
2797 }
2798 }
2799
2800 return NAME_NOT_FOUND;
2801}
2802
2803bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2804{
2805 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2806}
2807
2808void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2809 const Vector< sp<Track> >& tracksToRemove)
2810{
2811 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002812 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002813 for (size_t i = 0 ; i < count ; i++) {
2814 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002815 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002816 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002817 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002818#ifdef ADD_BATTERY_DATA
2819 // to track the speaker usage
2820 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2821#endif
2822 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002823 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002824 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002825 }
Eric Laurent81784c32012-11-19 14:55:58 -08002826 }
2827 }
2828 }
Eric Laurent81784c32012-11-19 14:55:58 -08002829}
2830
2831void AudioFlinger::PlaybackThread::checkSilentMode_l()
2832{
2833 if (!mMasterMute) {
2834 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002835 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2836 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2837 return;
2838 }
Eric Laurent81784c32012-11-19 14:55:58 -08002839 if (property_get("ro.audio.silent", value, "0") > 0) {
2840 char *endptr;
2841 unsigned long ul = strtoul(value, &endptr, 0);
2842 if (*endptr == '\0' && ul != 0) {
2843 ALOGD("Silence is golden");
2844 // The setprop command will not allow a property to be changed after
2845 // the first time it is set, so we don't have to worry about un-muting.
2846 setMasterMute_l(true);
2847 }
2848 }
2849 }
2850}
2851
2852// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002853ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002854{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002855 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002856 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002857 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002858 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002859
2860 // If an NBAIO sink is present, use it to write the normal mixer's submix
2861 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002862
Andy Hung010a1a12014-03-13 13:57:33 -07002863 const size_t count = mBytesRemaining / mFrameSize;
2864
Simon Wilson2d590962012-11-29 15:18:50 -08002865 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002866 // update the setpoint when AudioFlinger::mScreenState changes
2867 uint32_t screenState = AudioFlinger::mScreenState;
2868 if (screenState != mScreenState) {
2869 mScreenState = screenState;
2870 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2871 if (pipe != NULL) {
2872 pipe->setAvgFrames((mScreenState & 1) ?
2873 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2874 }
2875 }
Andy Hung010a1a12014-03-13 13:57:33 -07002876 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002877 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002878 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002879 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002880#ifdef TEE_SINK
2881 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2882#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002883 } else {
2884 bytesWritten = framesWritten;
2885 }
2886 // otherwise use the HAL / AudioStreamOut directly
2887 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002888 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002889
Eric Laurentbfb1b832013-01-07 09:53:42 -08002890 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002891 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2892 mWriteAckSequence += 2;
2893 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002894 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002895 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002896 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002897 // FIXME We should have an implementation of timestamps for direct output threads.
2898 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002899 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002900
Eric Laurentbfb1b832013-01-07 09:53:42 -08002901 if (mUseAsyncWrite &&
2902 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2903 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002904 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002906 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002907 }
Eric Laurent81784c32012-11-19 14:55:58 -08002908 }
2909
Eric Laurent81784c32012-11-19 14:55:58 -08002910 mNumWrites++;
2911 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002912 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002913 return bytesWritten;
2914}
2915
2916void AudioFlinger::PlaybackThread::threadLoop_drain()
2917{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002918 bool supportsDrain = false;
2919 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002920 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2921 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002922 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2923 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002924 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002925 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002926 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002927 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002928 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002929 }
2930}
2931
2932void AudioFlinger::PlaybackThread::threadLoop_exit()
2933{
Eric Laurent275e8e92014-11-30 15:14:47 -08002934 {
2935 Mutex::Autolock _l(mLock);
2936 for (size_t i = 0; i < mTracks.size(); i++) {
2937 sp<Track> track = mTracks[i];
2938 track->invalidate();
2939 }
Andy Hungdae27702016-10-31 14:01:16 -07002940 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2941 // After we exit there are no more track changes sent to BatteryNotifier
2942 // because that requires an active threadLoop.
2943 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2944 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002945 }
Eric Laurent81784c32012-11-19 14:55:58 -08002946}
2947
2948/*
2949The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002950 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002951 - mActiveSleepTimeUs from activeSleepTimeUs()
2952 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002953 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2954 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002955 - maxPeriod from frame count and sample rate (MIXER only)
2956
2957The parameters that affect these derived values are:
2958 - frame count
2959 - frame size
2960 - sample rate
2961 - device type: A2DP or not
2962 - device latency
2963 - format: PCM or not
2964 - active sleep time
2965 - idle sleep time
2966*/
2967
2968void AudioFlinger::PlaybackThread::cacheParameters_l()
2969{
Andy Hung25c2dac2014-02-27 14:56:00 -08002970 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002971 mActiveSleepTimeUs = activeSleepTimeUs();
2972 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002973
2974 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2975 // truncating audio when going to standby.
2976 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2977 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2978 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2979 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2980 }
2981 }
Eric Laurent81784c32012-11-19 14:55:58 -08002982}
2983
Eric Laurent13084622016-05-17 10:51:49 -07002984bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002985{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002986 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002987 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002988 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002989 size_t size = mTracks.size();
2990 for (size_t i = 0; i < size; i++) {
2991 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002992 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002993 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002994 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002995 }
2996 }
Eric Laurent13084622016-05-17 10:51:49 -07002997 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002998}
2999
Haynes Mathew George05317d22016-05-03 16:34:26 -07003000void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3001{
3002 Mutex::Autolock _l(mLock);
3003 invalidateTracks_l(streamType);
3004}
3005
Eric Laurent81784c32012-11-19 14:55:58 -08003006status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3007{
Glenn Kastend848eb42016-03-08 13:42:11 -08003008 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003009 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003010 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003011 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3012 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3013 &halInBuffer);
3014 if (result != OK) return result;
3015 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003016 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003017 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003018 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003019 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003020 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003021 if (mType != DIRECT) {
3022 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003023 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003024 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003025 &halInBuffer);
3026 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003027#ifdef FLOAT_EFFECT_CHAIN
3028 buffer = halInBuffer->audioBuffer()->f32;
3029#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003030 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003031#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003032 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3033 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003034 }
3035
3036 // Attach all tracks with same session ID to this chain.
3037 for (size_t i = 0; i < mTracks.size(); ++i) {
3038 sp<Track> track = mTracks[i];
3039 if (session == track->sessionId()) {
3040 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3041 buffer);
3042 track->setMainBuffer(buffer);
3043 chain->incTrackCnt();
3044 }
3045 }
3046
3047 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003048 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003049 if (session == track->sessionId()) {
3050 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3051 chain->incActiveTrackCnt();
3052 }
3053 }
3054 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003055 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003056 chain->setInBuffer(halInBuffer);
3057 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003058 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003059 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003060 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3061 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003062 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003063 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003064 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003065 // Effect chain for other sessions are inserted at beginning of effect
3066 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003067 // sessions is not important.
3068 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3069 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3070 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003071 size_t size = mEffectChains.size();
3072 size_t i = 0;
3073 for (i = 0; i < size; i++) {
3074 if (mEffectChains[i]->sessionId() < session) {
3075 break;
3076 }
3077 }
3078 mEffectChains.insertAt(chain, i);
3079 checkSuspendOnAddEffectChain_l(chain);
3080
3081 return NO_ERROR;
3082}
3083
3084size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3085{
Glenn Kastend848eb42016-03-08 13:42:11 -08003086 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003087
3088 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3089
3090 for (size_t i = 0; i < mEffectChains.size(); i++) {
3091 if (chain == mEffectChains[i]) {
3092 mEffectChains.removeAt(i);
3093 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003094 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003095 if (session == track->sessionId()) {
3096 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3097 chain.get(), session);
3098 chain->decActiveTrackCnt();
3099 }
3100 }
3101
3102 // detach all tracks with same session ID from this chain
3103 for (size_t i = 0; i < mTracks.size(); ++i) {
3104 sp<Track> track = mTracks[i];
3105 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003106 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003107 chain->decTrackCnt();
3108 }
3109 }
3110 break;
3111 }
3112 }
3113 return mEffectChains.size();
3114}
3115
3116status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003117 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003118{
3119 Mutex::Autolock _l(mLock);
3120 return attachAuxEffect_l(track, EffectId);
3121}
3122
3123status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003124 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003125{
3126 status_t status = NO_ERROR;
3127
3128 if (EffectId == 0) {
3129 track->setAuxBuffer(0, NULL);
3130 } else {
3131 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3132 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3133 if (effect != 0) {
3134 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3135 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3136 } else {
3137 status = INVALID_OPERATION;
3138 }
3139 } else {
3140 status = BAD_VALUE;
3141 }
3142 }
3143 return status;
3144}
3145
3146void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3147{
3148 for (size_t i = 0; i < mTracks.size(); ++i) {
3149 sp<Track> track = mTracks[i];
3150 if (track->auxEffectId() == effectId) {
3151 attachAuxEffect_l(track, 0);
3152 }
3153 }
3154}
3155
3156bool AudioFlinger::PlaybackThread::threadLoop()
3157{
Glenn Kasten388d5712017-04-07 14:38:41 -07003158 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003159
Eric Laurent81784c32012-11-19 14:55:58 -08003160 Vector< sp<Track> > tracksToRemove;
3161
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003162 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003163 nsecs_t lastWriteFinished = -1; // time last server write completed
3164 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003165
3166 // MIXER
3167 nsecs_t lastWarning = 0;
3168
3169 // DUPLICATING
3170 // FIXME could this be made local to while loop?
3171 writeFrames = 0;
3172
3173 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003174 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003175
3176 if (mType == MIXER) {
3177 sleepTimeShift = 0;
3178 }
3179
3180 CpuStats cpuStats;
3181 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3182
3183 acquireWakeLock();
3184
Glenn Kasteneef598c2017-04-03 14:41:13 -07003185 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3186 // thread associated with this PlaybackThread.
3187 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3188 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003189 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3190 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003191 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003192 const char *logString = NULL;
3193
rago1bb90822017-05-02 18:31:48 -07003194 // Estimated time for next buffer to be written to hal. This is used only on
3195 // suspended mode (for now) to help schedule the wait time until next iteration.
3196 nsecs_t timeLoopNextNs = 0;
3197
Eric Laurent664539d2013-09-23 18:24:31 -07003198 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003199
Eric Laurent81784c32012-11-19 14:55:58 -08003200 while (!exitPending())
3201 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003202 // Log merge requests are performed during AudioFlinger binder transactions, but
3203 // that does not cover audio playback. It's requested here for that reason.
3204 mAudioFlinger->requestLogMerge();
3205
Eric Laurent81784c32012-11-19 14:55:58 -08003206 cpuStats.sample(myName);
3207
3208 Vector< sp<EffectChain> > effectChains;
3209
Eric Laurent81784c32012-11-19 14:55:58 -08003210 { // scope for mLock
3211
3212 Mutex::Autolock _l(mLock);
3213
Eric Laurent021cf962014-05-13 10:18:14 -07003214 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003215
Glenn Kasteneef598c2017-04-03 14:41:13 -07003216 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003217 if (logString != NULL) {
3218 mNBLogWriter->logTimestamp();
3219 mNBLogWriter->log(logString);
3220 logString = NULL;
3221 }
3222
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003223 // Collect timestamp statistics for the Playback Thread types that support it.
3224 if (mType == MIXER
3225 || mType == DUPLICATING
3226 || (mType == DIRECT && audio_is_linear_pcm(mHALFormat))) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003227 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003228 // and associate with the sink frames written out. We need
3229 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003230 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003231 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003232 if (mStandby) {
3233 mTimestampVerifier.discontinuity();
3234 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3235 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3236 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3237 mSampleRate);
Andy Hung818e7a32016-02-16 18:08:07 -08003238 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003239 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003240
3241 // We keep track of the last valid kernel position in case we are in underrun
3242 // and the normal mixer period is the same as the fast mixer period, or there
3243 // is some error from the HAL.
3244 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3245 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3246 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3247 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3248 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3249
3250 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3251 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3252 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3253 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003254 }
3255
3256 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3257 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003258 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003259 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003260 }
3261
Andy Hung818e7a32016-02-16 18:08:07 -08003262 // copy over kernel info
3263 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003264 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3265 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003266 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3267 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003268 } else {
3269 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003270 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003271
Andy Hungc54b1ff2016-02-23 14:07:07 -08003272 // mFramesWritten for non-offloaded tracks are contiguous
3273 // even after standby() is called. This is useful for the track frame
3274 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003275 bool serverLocationUpdate = false;
3276 if (mFramesWritten != lastFramesWritten) {
3277 serverLocationUpdate = true;
3278 lastFramesWritten = mFramesWritten;
3279 }
3280 // Only update timestamps if there is a meaningful change.
3281 // Either the kernel timestamp must be valid or we have written something.
3282 if (kernelLocationUpdate || serverLocationUpdate) {
3283 if (serverLocationUpdate) {
3284 // use the time before we called the HAL write - it is a bit more accurate
3285 // to when the server last read data than the current time here.
3286 //
3287 // If we haven't written anything, mLastWriteTime will be -1
3288 // and we use systemTime().
3289 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3290 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3291 ? systemTime() : mLastWriteTime;
3292 }
Andy Hungdae27702016-10-31 14:01:16 -07003293
3294 for (const sp<Track> &t : mActiveTracks) {
3295 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003296 t->updateTrackFrameInfo(
3297 t->mAudioTrackServerProxy->framesReleased(),
3298 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003299 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003300 mTimestamp);
3301 }
Andy Hunge10393e2015-06-12 13:59:33 -07003302 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003303 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003304 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003305#if 0
3306 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003307 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003308 timespec ts;
3309 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003310 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003311 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003312 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003313 }
3314 ++z;
3315#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003316 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003317 if (mSignalPending) {
3318 // A signal was raised while we were unlocked
3319 mSignalPending = false;
3320 } else if (waitingAsyncCallback_l()) {
3321 if (exitPending()) {
3322 break;
3323 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003324 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003325 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003326 releaseWakeLock_l();
3327 released = true;
3328 }
Andy Hung10cbff12017-02-21 17:30:14 -08003329
3330 const int64_t waitNs = computeWaitTimeNs_l();
3331 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3332 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3333 if (status == TIMED_OUT) {
3334 mSignalPending = true; // if timeout recheck everything
3335 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003336 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003337 if (released) {
3338 acquireWakeLock_l();
3339 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003340 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3341 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003342
3343 continue;
3344 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003345 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003346 isSuspended()) {
3347 // put audio hardware into standby after short delay
3348 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003349
3350 threadLoop_standby();
3351
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003352 // This is where we go into standby
3353 if (!mStandby) {
3354 LOG_AUDIO_STATE();
3355 }
Eric Laurent81784c32012-11-19 14:55:58 -08003356 mStandby = true;
3357 }
3358
3359 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3360 // we're about to wait, flush the binder command buffer
3361 IPCThreadState::self()->flushCommands();
3362
3363 clearOutputTracks();
3364
3365 if (exitPending()) {
3366 break;
3367 }
3368
3369 releaseWakeLock_l();
3370 // wait until we have something to do...
3371 ALOGV("%s going to sleep", myName.string());
3372 mWaitWorkCV.wait(mLock);
3373 ALOGV("%s waking up", myName.string());
3374 acquireWakeLock_l();
3375
3376 mMixerStatus = MIXER_IDLE;
3377 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3378 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003379 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003380 checkSilentMode_l();
3381
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003382 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3383 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003384 if (mType == MIXER) {
3385 sleepTimeShift = 0;
3386 }
3387
3388 continue;
3389 }
3390 }
Eric Laurent81784c32012-11-19 14:55:58 -08003391 // mMixerStatusIgnoringFastTracks is also updated internally
3392 mMixerStatus = prepareTracks_l(&tracksToRemove);
3393
Andy Hungdae27702016-10-31 14:01:16 -07003394 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003395
Kevin Rocard069c2712018-03-29 19:09:14 -07003396 updateMetadata_l();
3397
Eric Laurent81784c32012-11-19 14:55:58 -08003398 // prevent any changes in effect chain list and in each effect chain
3399 // during mixing and effect process as the audio buffers could be deleted
3400 // or modified if an effect is created or deleted
3401 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003402 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003403
Eric Laurentbfb1b832013-01-07 09:53:42 -08003404 if (mBytesRemaining == 0) {
3405 mCurrentWriteLength = 0;
3406 if (mMixerStatus == MIXER_TRACKS_READY) {
3407 // threadLoop_mix() sets mCurrentWriteLength
3408 threadLoop_mix();
3409 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3410 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003411 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003412 // must be written to HAL
3413 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003414 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003415 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003416 }
3417 }
Andy Hung98ef9782014-03-04 14:46:50 -08003418 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003419 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003420 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3421 // or mSinkBuffer (if there are no effects).
3422 //
3423 // This is done pre-effects computation; if effects change to
3424 // support higher precision, this needs to move.
3425 //
3426 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003427 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003428 if (mMixerBufferValid) {
3429 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3430 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3431
Andy Hung2ddee192015-12-18 17:34:44 -08003432 // mono blend occurs for mixer threads only (not direct or offloaded)
3433 // and is handled here if we're going directly to the sink.
3434 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003435 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3436 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003437 }
3438
Andy Hung98ef9782014-03-04 14:46:50 -08003439 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3440 mNormalFrameCount * mChannelCount);
3441 }
3442
Eric Laurentbfb1b832013-01-07 09:53:42 -08003443 mBytesRemaining = mCurrentWriteLength;
3444 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003445 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3446 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3447 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3448 mBytesWritten += mBytesRemaining;
3449 mFramesWritten += framesRemaining;
3450 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003451 mBytesRemaining = 0;
3452 }
Eric Laurent81784c32012-11-19 14:55:58 -08003453
Eric Laurentbfb1b832013-01-07 09:53:42 -08003454 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003455 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003456 for (size_t i = 0; i < effectChains.size(); i ++) {
3457 effectChains[i]->process_l();
3458 }
Eric Laurent81784c32012-11-19 14:55:58 -08003459 }
3460 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003461 // Process effect chains for offloaded thread even if no audio
3462 // was read from audio track: process only updates effect state
3463 // and thus does have to be synchronized with audio writes but may have
3464 // to be called while waiting for async write callback
3465 if (mType == OFFLOAD) {
3466 for (size_t i = 0; i < effectChains.size(); i ++) {
3467 effectChains[i]->process_l();
3468 }
3469 }
Eric Laurent81784c32012-11-19 14:55:58 -08003470
Andy Hung98ef9782014-03-04 14:46:50 -08003471 // Only if the Effects buffer is enabled and there is data in the
3472 // Effects buffer (buffer valid), we need to
3473 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003474 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003475 if (mEffectBufferValid) {
3476 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003477
3478 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003479 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3480 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003481 }
3482
Andy Hung98ef9782014-03-04 14:46:50 -08003483 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3484 mNormalFrameCount * mChannelCount);
3485 }
3486
Eric Laurent81784c32012-11-19 14:55:58 -08003487 // enable changes in effect chain
3488 unlockEffectChains(effectChains);
3489
Eric Laurentbfb1b832013-01-07 09:53:42 -08003490 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003491 // mSleepTimeUs == 0 means we must write to audio hardware
3492 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003493 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003494 // We save lastWriteFinished here, as previousLastWriteFinished,
3495 // for throttling. On thread start, previousLastWriteFinished will be
3496 // set to -1, which properly results in no throttling after the first write.
3497 nsecs_t previousLastWriteFinished = lastWriteFinished;
3498 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003499 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003500 // FIXME rewrite to reduce number of system calls
3501 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003502 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003503 lastWriteFinished = systemTime();
3504 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003505 if (ret < 0) {
3506 mBytesRemaining = 0;
3507 } else {
3508 mBytesWritten += ret;
3509 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003510 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003511 }
3512 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3513 (mMixerStatus == MIXER_DRAIN_ALL)) {
3514 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003515 }
Andy Hung08fb1742015-05-31 23:22:10 -07003516 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003517 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003518 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003519 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003520 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003521 ATRACE_NAME("underrun");
3522 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003523 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003524 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003525 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003526 }
Andy Hung08fb1742015-05-31 23:22:10 -07003527
3528 if (mThreadThrottle
3529 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3530 && ret > 0) { // we wrote something
3531 // Limit MixerThread data processing to no more than twice the
3532 // expected processing rate.
3533 //
3534 // This helps prevent underruns with NuPlayer and other applications
3535 // which may set up buffers that are close to the minimum size, or use
3536 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3537 //
3538 // The throttle smooths out sudden large data drains from the device,
3539 // e.g. when it comes out of standby, which often causes problems with
3540 // (1) mixer threads without a fast mixer (which has its own warm-up)
3541 // (2) minimum buffer sized tracks (even if the track is full,
3542 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003543 //
3544 // Total time spent in last processing cycle equals time spent in
3545 // 1. threadLoop_write, as well as time spent in
3546 // 2. threadLoop_mix (significant for heavy mixing, especially
3547 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003548
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003549 // it's OK if deltaMs (and deltaNs) is an overestimate.
3550 nsecs_t deltaNs;
3551 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3552 __builtin_sub_overflow(
3553 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3554 const int32_t deltaMs = deltaNs / 1000000;
3555
Ivan Lozanoea04d392017-11-07 14:37:07 -08003556 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003557 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3558 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003559 // notify of throttle start on verbose log
3560 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3561 "mixer(%p) throttle begin:"
3562 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003563 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003564 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003565 // Throttle must be attributed to the previous mixer loop's write time
3566 // to allow back-to-back throttling.
3567 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003568 } else {
3569 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3570 if (diff > 0) {
3571 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003572 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003573 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3574 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003575 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003576 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3577 }
Andy Hung08fb1742015-05-31 23:22:10 -07003578 }
3579 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580 }
Eric Laurent81784c32012-11-19 14:55:58 -08003581
Eric Laurentbfb1b832013-01-07 09:53:42 -08003582 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003583 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003584 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003585 // suspended requires accurate metering of sleep time.
3586 if (isSuspended()) {
3587 // advance by expected sleepTime
3588 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3589 const nsecs_t nowNs = systemTime();
3590
3591 // compute expected next time vs current time.
3592 // (negative deltas are treated as delays).
3593 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3594 if (deltaNs < -kMaxNextBufferDelayNs) {
3595 // Delays longer than the max allowed trigger a reset.
3596 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3597 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3598 timeLoopNextNs = nowNs + deltaNs;
3599 } else if (deltaNs < 0) {
3600 // Delays within the max delay allowed: zero the delta/sleepTime
3601 // to help the system catch up in the next iteration(s)
3602 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3603 deltaNs = 0;
3604 }
3605 // update sleep time (which is >= 0)
3606 mSleepTimeUs = deltaNs / 1000;
3607 }
Eric Laurente93cc032016-05-05 10:15:10 -07003608 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3609 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003610 }
Glenn Kastene7754022014-10-31 12:11:26 -07003611 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003612 }
Eric Laurent81784c32012-11-19 14:55:58 -08003613 }
3614
3615 // Finally let go of removed track(s), without the lock held
3616 // since we can't guarantee the destructors won't acquire that
3617 // same lock. This will also mutate and push a new fast mixer state.
3618 threadLoop_removeTracks(tracksToRemove);
3619 tracksToRemove.clear();
3620
3621 // FIXME I don't understand the need for this here;
3622 // it was in the original code but maybe the
3623 // assignment in saveOutputTracks() makes this unnecessary?
3624 clearOutputTracks();
3625
3626 // Effect chains will be actually deleted here if they were removed from
3627 // mEffectChains list during mixing or effects processing
3628 effectChains.clear();
3629
3630 // FIXME Note that the above .clear() is no longer necessary since effectChains
3631 // is now local to this block, but will keep it for now (at least until merge done).
3632 }
3633
Eric Laurentbfb1b832013-01-07 09:53:42 -08003634 threadLoop_exit();
3635
Eric Laurentcf817a22014-08-04 20:36:31 -07003636 if (!mStandby) {
3637 threadLoop_standby();
3638 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003639 }
3640
3641 releaseWakeLock();
3642
3643 ALOGV("Thread %p type %d exiting", this, mType);
3644 return false;
3645}
3646
Eric Laurentbfb1b832013-01-07 09:53:42 -08003647// removeTracks_l() must be called with ThreadBase::mLock held
3648void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3649{
3650 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003651 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003652 for (size_t i=0 ; i<count ; i++) {
3653 const sp<Track>& track = tracksToRemove.itemAt(i);
3654 mActiveTracks.remove(track);
3655 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3656 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3657 if (chain != 0) {
3658 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3659 track->sessionId());
3660 chain->decActiveTrackCnt();
3661 }
3662 if (track->isTerminated()) {
3663 removeTrack_l(track);
3664 }
3665 }
3666 }
3667
3668}
Eric Laurent81784c32012-11-19 14:55:58 -08003669
Eric Laurentaccc1472013-09-20 09:36:34 -07003670status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3671{
3672 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003673 ExtendedTimestamp ets;
3674 status_t status = mNormalSink->getTimestamp(ets);
3675 if (status == NO_ERROR) {
3676 status = ets.getBestTimestamp(&timestamp);
3677 }
3678 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003679 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003680 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003681 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003682 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003683 timestamp.mPosition = (uint32_t)position64;
3684 return NO_ERROR;
3685 }
3686 }
3687 return INVALID_OPERATION;
3688}
Eric Laurent1c333e22014-05-20 10:48:17 -07003689
Eric Laurent054d9d32015-04-24 08:48:48 -07003690status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3691 audio_patch_handle_t *handle)
3692{
Andy Hungf60abce2016-08-26 11:37:54 -07003693 status_t status;
3694 if (property_get_bool("af.patch_park", false /* default_value */)) {
3695 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3696 // or if HAL does not properly lock against access.
3697 AutoPark<FastMixer> park(mFastMixer);
3698 status = PlaybackThread::createAudioPatch_l(patch, handle);
3699 } else {
3700 status = PlaybackThread::createAudioPatch_l(patch, handle);
3701 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003702 return status;
3703}
3704
Eric Laurent1c333e22014-05-20 10:48:17 -07003705status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3706 audio_patch_handle_t *handle)
3707{
3708 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003709
3710 // store new device and send to effects
3711 audio_devices_t type = AUDIO_DEVICE_NONE;
3712 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3713 type |= patch->sinks[i].ext.device.type;
3714 }
3715
3716#ifdef ADD_BATTERY_DATA
3717 // when changing the audio output device, call addBatteryData to notify
3718 // the change
3719 if (mOutDevice != type) {
3720 uint32_t params = 0;
3721 // check whether speaker is on
3722 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3723 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003724 }
3725
Eric Laurent054d9d32015-04-24 08:48:48 -07003726 audio_devices_t deviceWithoutSpeaker
3727 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3728 // check if any other device (except speaker) is on
3729 if (type & deviceWithoutSpeaker) {
3730 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3731 }
3732
3733 if (params != 0) {
3734 addBatteryData(params);
3735 }
3736 }
3737#endif
3738
3739 for (size_t i = 0; i < mEffectChains.size(); i++) {
3740 mEffectChains[i]->setDevice_l(type);
3741 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003742
3743 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3744 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3745 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003746 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003747 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003748
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003749 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003750 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3751 status = hwDevice->createAudioPatch(patch->num_sources,
3752 patch->sources,
3753 patch->num_sinks,
3754 patch->sinks,
3755 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003756 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003757 char *address;
3758 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3759 //FIXME: we only support address on first sink with HAL version < 3.0
3760 address = audio_device_address_to_parameter(
3761 patch->sinks[0].ext.device.type,
3762 patch->sinks[0].ext.device.address);
3763 } else {
3764 address = (char *)calloc(1, 1);
3765 }
3766 AudioParameter param = AudioParameter(String8(address));
3767 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003768 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003769 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003770 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003771 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003772 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003773 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003774 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3775 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003776 return status;
3777}
3778
Eric Laurent054d9d32015-04-24 08:48:48 -07003779status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3780{
Andy Hungf60abce2016-08-26 11:37:54 -07003781 status_t status;
3782 if (property_get_bool("af.patch_park", false /* default_value */)) {
3783 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3784 // or if HAL does not properly lock against access.
3785 AutoPark<FastMixer> park(mFastMixer);
3786 status = PlaybackThread::releaseAudioPatch_l(handle);
3787 } else {
3788 status = PlaybackThread::releaseAudioPatch_l(handle);
3789 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003790 return status;
3791}
3792
Eric Laurent1c333e22014-05-20 10:48:17 -07003793status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3794{
3795 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003796
3797 mOutDevice = AUDIO_DEVICE_NONE;
3798
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003799 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003800 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3801 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003802 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003803 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003804 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003805 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003806 }
3807 return status;
3808}
3809
Eric Laurent83b88082014-06-20 18:31:16 -07003810void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3811{
3812 Mutex::Autolock _l(mLock);
3813 mTracks.add(track);
3814}
3815
3816void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3817{
3818 Mutex::Autolock _l(mLock);
3819 destroyTrack_l(track);
3820}
3821
Mikhail Naganovdc769682018-05-04 15:34:08 -07003822void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003823{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003824 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003825 config->role = AUDIO_PORT_ROLE_SOURCE;
3826 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3827 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003828 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3829 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3830 config->flags.output = mOutput->flags;
3831 }
Eric Laurent83b88082014-06-20 18:31:16 -07003832}
3833
Eric Laurent81784c32012-11-19 14:55:58 -08003834// ----------------------------------------------------------------------------
3835
3836AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003837 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3838 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003839 // mAudioMixer below
3840 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003841 mFastMixerFutex(0),
3842 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003843 // mOutputSink below
3844 // mPipeSink below
3845 // mNormalSink below
3846{
3847 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003848 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003849 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003850 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3851 mNormalFrameCount);
3852 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3853
Andy Hungfbfc3952015-01-15 13:33:51 -08003854 if (type == DUPLICATING) {
3855 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3856 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3857 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3858 return;
3859 }
Eric Laurent81784c32012-11-19 14:55:58 -08003860 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003861 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003862 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003863 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003864#if !LOG_NDEBUG
3865 ssize_t index =
3866#else
3867 (void)
3868#endif
3869 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003870 ALOG_ASSERT(index == 0);
3871
3872 // initialize fast mixer depending on configuration
3873 bool initFastMixer;
3874 switch (kUseFastMixer) {
3875 case FastMixer_Never:
3876 initFastMixer = false;
3877 break;
3878 case FastMixer_Always:
3879 initFastMixer = true;
3880 break;
3881 case FastMixer_Static:
3882 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003883 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3884 // where the period is less than an experimentally determined threshold that can be
3885 // scheduled reliably with CFS. However, the BT A2DP HAL is
3886 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3887 initFastMixer = mFrameCount < mNormalFrameCount
3888 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003889 break;
3890 }
Andy Hungfda69402017-02-15 14:33:12 -08003891 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3892 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3893 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003894 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003895 audio_format_t fastMixerFormat;
3896 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3897 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3898 } else {
3899 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3900 }
3901 if (mFormat != fastMixerFormat) {
3902 // change our Sink format to accept our intermediate precision
3903 mFormat = fastMixerFormat;
3904 free(mSinkBuffer);
3905 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3906 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3907 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3908 }
Eric Laurent81784c32012-11-19 14:55:58 -08003909
3910 // create a MonoPipe to connect our submix to FastMixer
3911 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07003912
Andy Hung1258c1a2014-05-23 21:22:17 -07003913 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003914 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003915 format.mFormat = fastMixerFormat;
3916 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3917
Eric Laurent81784c32012-11-19 14:55:58 -08003918 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3919 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3920 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3921 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3922 const NBAIO_Format offers[1] = {format};
3923 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07003924#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003925 ssize_t index =
3926#else
3927 (void)
3928#endif
3929 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003930 ALOG_ASSERT(index == 0);
3931 monoPipe->setAvgFrames((mScreenState & 1) ?
3932 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3933 mPipeSink = monoPipe;
3934
Eric Laurent81784c32012-11-19 14:55:58 -08003935 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07003936 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003937 FastMixerStateQueue *sq = mFastMixer->sq();
3938#ifdef STATE_QUEUE_DUMP
3939 sq->setObserverDump(&mStateQueueObserverDump);
3940 sq->setMutatorDump(&mStateQueueMutatorDump);
3941#endif
3942 FastMixerState *state = sq->begin();
3943 FastTrack *fastTrack = &state->mFastTracks[0];
3944 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3945 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3946 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003947 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3948 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003949 fastTrack->mGeneration++;
3950 state->mFastTracksGen++;
3951 state->mTrackMask = 1;
3952 // fast mixer will use the HAL output sink
3953 state->mOutputSink = mOutputSink.get();
3954 state->mOutputSinkGen++;
3955 state->mFrameCount = mFrameCount;
3956 state->mCommand = FastMixerState::COLD_IDLE;
3957 // already done in constructor initialization list
3958 //mFastMixerFutex = 0;
3959 state->mColdFutexAddr = &mFastMixerFutex;
3960 state->mColdGen++;
3961 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08003962 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3963 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003964 sq->end();
3965 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3966
3967 // start the fast mixer
3968 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3969 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003970 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003971 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003972
3973#ifdef AUDIO_WATCHDOG
3974 // create and start the watchdog
3975 mAudioWatchdog = new AudioWatchdog();
3976 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3977 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3978 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003979 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003980#endif
Andy Hung8946a282018-04-19 20:04:56 -07003981 } else {
3982#ifdef TEE_SINK
3983 // Only use the MixerThread tee if there is no FastMixer.
3984 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
3985 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
3986#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003987 }
3988
3989 switch (kUseFastMixer) {
3990 case FastMixer_Never:
3991 case FastMixer_Dynamic:
3992 mNormalSink = mOutputSink;
3993 break;
3994 case FastMixer_Always:
3995 mNormalSink = mPipeSink;
3996 break;
3997 case FastMixer_Static:
3998 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3999 break;
4000 }
4001}
4002
4003AudioFlinger::MixerThread::~MixerThread()
4004{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004005 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004006 FastMixerStateQueue *sq = mFastMixer->sq();
4007 FastMixerState *state = sq->begin();
4008 if (state->mCommand == FastMixerState::COLD_IDLE) {
4009 int32_t old = android_atomic_inc(&mFastMixerFutex);
4010 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004011 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004012 }
4013 }
4014 state->mCommand = FastMixerState::EXIT;
4015 sq->end();
4016 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4017 mFastMixer->join();
4018 // Though the fast mixer thread has exited, it's state queue is still valid.
4019 // We'll use that extract the final state which contains one remaining fast track
4020 // corresponding to our sub-mix.
4021 state = sq->begin();
4022 ALOG_ASSERT(state->mTrackMask == 1);
4023 FastTrack *fastTrack = &state->mFastTracks[0];
4024 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4025 delete fastTrack->mBufferProvider;
4026 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004027 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004028#ifdef AUDIO_WATCHDOG
4029 if (mAudioWatchdog != 0) {
4030 mAudioWatchdog->requestExit();
4031 mAudioWatchdog->requestExitAndWait();
4032 mAudioWatchdog.clear();
4033 }
4034#endif
4035 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004036 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004037 delete mAudioMixer;
4038}
4039
4040
4041uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4042{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004043 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004044 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4045 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4046 }
4047 return latency;
4048}
4049
4050
4051void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4052{
4053 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4054}
4055
Eric Laurentbfb1b832013-01-07 09:53:42 -08004056ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004057{
4058 // FIXME we should only do one push per cycle; confirm this is true
4059 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004060 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004061 FastMixerStateQueue *sq = mFastMixer->sq();
4062 FastMixerState *state = sq->begin();
4063 if (state->mCommand != FastMixerState::MIX_WRITE &&
4064 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4065 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004066
4067 // FIXME workaround for first HAL write being CPU bound on some devices
4068 ATRACE_BEGIN("write");
4069 mOutput->write((char *)mSinkBuffer, 0);
4070 ATRACE_END();
4071
Eric Laurent81784c32012-11-19 14:55:58 -08004072 int32_t old = android_atomic_inc(&mFastMixerFutex);
4073 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004074 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004075 }
4076#ifdef AUDIO_WATCHDOG
4077 if (mAudioWatchdog != 0) {
4078 mAudioWatchdog->resume();
4079 }
4080#endif
4081 }
4082 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004083#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004084 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004085 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004086#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004087 sq->end();
4088 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4089 if (kUseFastMixer == FastMixer_Dynamic) {
4090 mNormalSink = mPipeSink;
4091 }
4092 } else {
4093 sq->end(false /*didModify*/);
4094 }
4095 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004096 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004097}
4098
4099void AudioFlinger::MixerThread::threadLoop_standby()
4100{
4101 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004102 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004103 FastMixerStateQueue *sq = mFastMixer->sq();
4104 FastMixerState *state = sq->begin();
4105 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004106 // Report any frames trapped in the Monopipe
4107 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4108 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4109 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4110 "monoPipeWritten:%lld monoPipeLeft:%lld",
4111 (long long)mFramesWritten, (long long)mSuspendedFrames,
4112 (long long)mPipeSink->framesWritten(), pipeFrames);
4113 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4114
Eric Laurent81784c32012-11-19 14:55:58 -08004115 state->mCommand = FastMixerState::COLD_IDLE;
4116 state->mColdFutexAddr = &mFastMixerFutex;
4117 state->mColdGen++;
4118 mFastMixerFutex = 0;
4119 sq->end();
4120 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4121 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4122 if (kUseFastMixer == FastMixer_Dynamic) {
4123 mNormalSink = mOutputSink;
4124 }
4125#ifdef AUDIO_WATCHDOG
4126 if (mAudioWatchdog != 0) {
4127 mAudioWatchdog->pause();
4128 }
4129#endif
4130 } else {
4131 sq->end(false /*didModify*/);
4132 }
4133 }
4134 PlaybackThread::threadLoop_standby();
4135}
4136
Eric Laurentbfb1b832013-01-07 09:53:42 -08004137bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4138{
4139 return false;
4140}
4141
4142bool AudioFlinger::PlaybackThread::shouldStandby_l()
4143{
4144 return !mStandby;
4145}
4146
4147bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4148{
4149 Mutex::Autolock _l(mLock);
4150 return waitingAsyncCallback_l();
4151}
4152
Eric Laurent81784c32012-11-19 14:55:58 -08004153// shared by MIXER and DIRECT, overridden by DUPLICATING
4154void AudioFlinger::PlaybackThread::threadLoop_standby()
4155{
4156 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004157 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004158 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004159 // discard any pending drain or write ack by incrementing sequence
4160 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4161 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004162 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004163 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4164 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004165 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004166 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004167}
4168
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004169void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4170{
4171 ALOGV("signal playback thread");
4172 broadcast_l();
4173}
4174
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004175void AudioFlinger::PlaybackThread::onAsyncError()
4176{
4177 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4178 invalidateTracks((audio_stream_type_t)i);
4179 }
4180}
4181
Eric Laurent81784c32012-11-19 14:55:58 -08004182void AudioFlinger::MixerThread::threadLoop_mix()
4183{
Eric Laurent81784c32012-11-19 14:55:58 -08004184 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004185 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004186 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004187 // increase sleep time progressively when application underrun condition clears.
4188 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4189 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4190 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004191 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004192 sleepTimeShift--;
4193 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004194 mSleepTimeUs = 0;
4195 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004196 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004197
Eric Laurent81784c32012-11-19 14:55:58 -08004198}
4199
4200void AudioFlinger::MixerThread::threadLoop_sleepTime()
4201{
4202 // If no tracks are ready, sleep once for the duration of an output
4203 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004204 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004205 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004206 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4207 // Using the Monopipe availableToWrite, we estimate the
4208 // sleep time to retry for more data (before we underrun).
4209 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4210 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4211 const size_t pipeFrames = monoPipe->maxFrames();
4212 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4213 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4214 const size_t framesDelay = std::min(
4215 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4216 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4217 pipeFrames, framesLeft, framesDelay);
4218 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4219 } else {
4220 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4221 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4222 mSleepTimeUs = kMinThreadSleepTimeUs;
4223 }
4224 // reduce sleep time in case of consecutive application underruns to avoid
4225 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4226 // duration we would end up writing less data than needed by the audio HAL if
4227 // the condition persists.
4228 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4229 sleepTimeShift++;
4230 }
Eric Laurent81784c32012-11-19 14:55:58 -08004231 }
4232 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004233 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004234 }
4235 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004236 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4237 // before effects processing or output.
4238 if (mMixerBufferValid) {
4239 memset(mMixerBuffer, 0, mMixerBufferSize);
4240 } else {
4241 memset(mSinkBuffer, 0, mSinkBufferSize);
4242 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004243 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004244 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4245 "anticipated start");
4246 }
4247 // TODO add standby time extension fct of effect tail
4248}
4249
4250// prepareTracks_l() must be called with ThreadBase::mLock held
4251AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4252 Vector< sp<Track> > *tracksToRemove)
4253{
Andy Hung1bc088a2018-02-09 15:57:31 -08004254 // clean up deleted track names in AudioMixer before allocating new tracks
4255 (void)mTracks.processDeletedTrackNames([this](int name) {
4256 // for each name, destroy it in the AudioMixer
4257 if (mAudioMixer->exists(name)) {
4258 mAudioMixer->destroy(name);
4259 }
4260 });
4261 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004262
4263 mixer_state mixerStatus = MIXER_IDLE;
4264 // find out which tracks need to be processed
4265 size_t count = mActiveTracks.size();
4266 size_t mixedTracks = 0;
4267 size_t tracksWithEffect = 0;
4268 // counts only _active_ fast tracks
4269 size_t fastTracks = 0;
4270 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4271
4272 float masterVolume = mMasterVolume;
4273 bool masterMute = mMasterMute;
4274
4275 if (masterMute) {
4276 masterVolume = 0;
4277 }
4278 // Delegate master volume control to effect in output mix effect chain if needed
4279 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4280 if (chain != 0) {
4281 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4282 chain->setVolume_l(&v, &v);
4283 masterVolume = (float)((v + (1 << 23)) >> 24);
4284 chain.clear();
4285 }
4286
4287 // prepare a new state to push
4288 FastMixerStateQueue *sq = NULL;
4289 FastMixerState *state = NULL;
4290 bool didModify = false;
4291 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004292 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004293 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004294 sq = mFastMixer->sq();
4295 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004296 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004297 }
4298
Andy Hung69aed5f2014-02-25 17:24:40 -08004299 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004300 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004301
Andy Hungbd3b2b02018-05-21 10:53:11 -07004302 // DeferredOperations handles statistics after setting mixerStatus.
4303 class DeferredOperations {
4304 public:
4305 DeferredOperations(mixer_state *mixerStatus)
4306 : mMixerStatus(mixerStatus) { }
4307
4308 // when leaving scope, tally frames properly.
4309 ~DeferredOperations() {
4310 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4311 // because that is when the underrun occurs.
4312 // We do not distinguish between FastTracks and NormalTracks here.
4313 if (*mMixerStatus == MIXER_TRACKS_READY) {
4314 for (const auto &underrun : mUnderrunFrames) {
4315 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4316 underrun.second);
4317 }
4318 }
4319 }
4320
4321 // tallyUnderrunFrames() is called to update the track counters
4322 // with the number of underrun frames for a particular mixer period.
4323 // We defer tallying until we know the final mixer status.
4324 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4325 mUnderrunFrames.emplace_back(track, underrunFrames);
4326 }
4327
4328 private:
4329 const mixer_state * const mMixerStatus;
4330 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4331 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4332
Eric Laurent81784c32012-11-19 14:55:58 -08004333 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004334 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004335
4336 // this const just means the local variable doesn't change
4337 Track* const track = t.get();
4338
4339 // process fast tracks
4340 if (track->isFastTrack()) {
4341
4342 // It's theoretically possible (though unlikely) for a fast track to be created
4343 // and then removed within the same normal mix cycle. This is not a problem, as
4344 // the track never becomes active so it's fast mixer slot is never touched.
4345 // The converse, of removing an (active) track and then creating a new track
4346 // at the identical fast mixer slot within the same normal mix cycle,
4347 // is impossible because the slot isn't marked available until the end of each cycle.
4348 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004349 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004350 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4351 FastTrack *fastTrack = &state->mFastTracks[j];
4352
4353 // Determine whether the track is currently in underrun condition,
4354 // and whether it had a recent underrun.
4355 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4356 FastTrackUnderruns underruns = ftDump->mUnderruns;
4357 uint32_t recentFull = (underruns.mBitFields.mFull -
4358 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4359 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4360 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4361 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4362 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4363 uint32_t recentUnderruns = recentPartial + recentEmpty;
4364 track->mObservedUnderruns = underruns;
4365 // don't count underruns that occur while stopping or pausing
4366 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004367 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004368 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4369 recentUnderruns > 0) {
4370 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004371 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004372 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004373 // Immediately account for FastTrack underruns.
4374 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004375
4376 // This is similar to the state machine for normal tracks,
4377 // with a few modifications for fast tracks.
4378 bool isActive = true;
4379 switch (track->mState) {
4380 case TrackBase::STOPPING_1:
4381 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004382 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004383 track->mState = TrackBase::STOPPING_2;
4384 }
4385 break;
4386 case TrackBase::PAUSING:
4387 // ramp down is not yet implemented
4388 track->setPaused();
4389 break;
4390 case TrackBase::RESUMING:
4391 // ramp up is not yet implemented
4392 track->mState = TrackBase::ACTIVE;
4393 break;
4394 case TrackBase::ACTIVE:
4395 if (recentFull > 0 || recentPartial > 0) {
4396 // track has provided at least some frames recently: reset retry count
4397 track->mRetryCount = kMaxTrackRetries;
4398 }
4399 if (recentUnderruns == 0) {
4400 // no recent underruns: stay active
4401 break;
4402 }
4403 // there has recently been an underrun of some kind
4404 if (track->sharedBuffer() == 0) {
4405 // were any of the recent underruns "empty" (no frames available)?
4406 if (recentEmpty == 0) {
4407 // no, then ignore the partial underruns as they are allowed indefinitely
4408 break;
4409 }
4410 // there has recently been an "empty" underrun: decrement the retry counter
4411 if (--(track->mRetryCount) > 0) {
4412 break;
4413 }
4414 // indicate to client process that the track was disabled because of underrun;
4415 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004416 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004417 // remove from active list, but state remains ACTIVE [confusing but true]
4418 isActive = false;
4419 break;
4420 }
4421 // fall through
4422 case TrackBase::STOPPING_2:
4423 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004424 case TrackBase::STOPPED:
4425 case TrackBase::FLUSHED: // flush() while active
4426 // Check for presentation complete if track is inactive
4427 // We have consumed all the buffers of this track.
4428 // This would be incomplete if we auto-paused on underrun
4429 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004430 uint32_t latency = 0;
4431 status_t result = mOutput->stream->getLatency(&latency);
4432 ALOGE_IF(result != OK,
4433 "Error when retrieving output stream latency: %d", result);
4434 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004435 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004436 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4437 // track stays in active list until presentation is complete
4438 break;
4439 }
4440 }
4441 if (track->isStopping_2()) {
4442 track->mState = TrackBase::STOPPED;
4443 }
4444 if (track->isStopped()) {
4445 // Can't reset directly, as fast mixer is still polling this track
4446 // track->reset();
4447 // So instead mark this track as needing to be reset after push with ack
4448 resetMask |= 1 << i;
4449 }
4450 isActive = false;
4451 break;
4452 case TrackBase::IDLE:
4453 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004454 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004455 }
4456
4457 if (isActive) {
4458 // was it previously inactive?
4459 if (!(state->mTrackMask & (1 << j))) {
4460 ExtendedAudioBufferProvider *eabp = track;
4461 VolumeProvider *vp = track;
4462 fastTrack->mBufferProvider = eabp;
4463 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004464 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004465 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004466 fastTrack->mGeneration++;
4467 state->mTrackMask |= 1 << j;
4468 didModify = true;
4469 // no acknowledgement required for newly active tracks
4470 }
Kevin Rocard12381092018-04-11 09:19:59 -07004471 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004472 // cache the combined master volume and stream type volume for fast mixer; this
4473 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004474 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004475 proxy->framesReleased()).first;
4476 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004477 * mStreamTypes[track->streamType()].volume
4478 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004479 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004480 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4481 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4482 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4483 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004484 ++fastTracks;
4485 } else {
4486 // was it previously active?
4487 if (state->mTrackMask & (1 << j)) {
4488 fastTrack->mBufferProvider = NULL;
4489 fastTrack->mGeneration++;
4490 state->mTrackMask &= ~(1 << j);
4491 didModify = true;
4492 // If any fast tracks were removed, we must wait for acknowledgement
4493 // because we're about to decrement the last sp<> on those tracks.
4494 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4495 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004496 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4497 // AudioTrack may start (which may not be with a start() but with a write()
4498 // after underrun) and immediately paused or released. In that case the
4499 // FastTrack state hasn't had time to update.
4500 // TODO Remove the ALOGW when this theory is confirmed.
4501 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004502 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4503 j, track->mState, state->mTrackMask, recentUnderruns,
4504 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004505 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004506 }
4507 tracksToRemove->add(track);
4508 // Avoids a misleading display in dumpsys
4509 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4510 }
4511 continue;
4512 }
4513
4514 { // local variable scope to avoid goto warning
4515
4516 audio_track_cblk_t* cblk = track->cblk();
4517
4518 // The first time a track is added we wait
4519 // for all its buffers to be filled before processing it
4520 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004521
4522 // if an active track doesn't exist in the AudioMixer, create it.
4523 if (!mAudioMixer->exists(name)) {
4524 status_t status = mAudioMixer->create(
4525 name,
4526 track->mChannelMask,
4527 track->mFormat,
4528 track->mSessionId);
4529 if (status != OK) {
4530 ALOGW("%s: cannot create track name"
4531 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4532 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4533 tracksToRemove->add(track);
4534 track->invalidate(); // consider it dead.
4535 continue;
4536 }
4537 }
4538
Eric Laurent81784c32012-11-19 14:55:58 -08004539 // make sure that we have enough frames to mix one full buffer.
4540 // enforce this condition only once to enable draining the buffer in case the client
4541 // app does not call stop() and relies on underrun to stop:
4542 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4543 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004544 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004545 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004546 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004547
4548 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004549 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004550 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4551 // add frames already consumed but not yet released by the resampler
4552 // because mAudioTrackServerProxy->framesReady() will include these frames
4553 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4554
Eric Laurent81784c32012-11-19 14:55:58 -08004555 uint32_t minFrames = 1;
4556 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4557 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004558 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004559 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004560
4561 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004562 if (ATRACE_ENABLED()) {
4563 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004564 std::string traceName("nRdy");
4565 traceName += std::to_string(track->name());
4566 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004567 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004568 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004569 !track->isPaused() && !track->isTerminated())
4570 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004571 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004572
4573 mixedTracks++;
4574
Andy Hung69aed5f2014-02-25 17:24:40 -08004575 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4576 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004577 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004578 if (track->mainBuffer() != mSinkBuffer &&
4579 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004580 if (mEffectBufferEnabled) {
4581 mEffectBufferValid = true; // Later can set directly.
4582 }
Eric Laurent81784c32012-11-19 14:55:58 -08004583 chain = getEffectChain_l(track->sessionId());
4584 // Delegate volume control to effect in track effect chain if needed
4585 if (chain != 0) {
4586 tracksWithEffect++;
4587 } else {
4588 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4589 "session %d",
4590 name, track->sessionId());
4591 }
4592 }
4593
4594
4595 int param = AudioMixer::VOLUME;
4596 if (track->mFillingUpStatus == Track::FS_FILLED) {
4597 // no ramp for the first volume setting
4598 track->mFillingUpStatus = Track::FS_ACTIVE;
4599 if (track->mState == TrackBase::RESUMING) {
4600 track->mState = TrackBase::ACTIVE;
4601 param = AudioMixer::RAMP_VOLUME;
4602 }
4603 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004604 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004605 // FIXME should not make a decision based on mServer
4606 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004607 // If the track is stopped before the first frame was mixed,
4608 // do not apply ramp
4609 param = AudioMixer::RAMP_VOLUME;
4610 }
4611
4612 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004613 uint32_t vl, vr; // in U8.24 integer format
4614 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004615 // read original volumes with volume control
4616 float typeVolume = mStreamTypes[track->streamType()].volume;
4617 float v = masterVolume * typeVolume;
4618
Glenn Kastene4756fe2012-11-29 13:38:14 -08004619 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004620 vl = vr = 0;
4621 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004622 if (track->isPausing()) {
4623 track->setPaused();
4624 }
4625 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004626 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004627 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004628 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4629 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004630 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004631 if (vlf > GAIN_FLOAT_UNITY) {
4632 ALOGV("Track left volume out of range: %.3g", vlf);
4633 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004634 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004635 if (vrf > GAIN_FLOAT_UNITY) {
4636 ALOGV("Track right volume out of range: %.3g", vrf);
4637 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004638 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004639 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004640 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004641 // now apply the master volume and stream type volume and shaper volume
4642 vlf *= v * vh;
4643 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004644 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004645 // then derive vl and vr as U8.24 versions for the effect chain
4646 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4647 vl = (uint32_t) (scaleto8_24 * vlf);
4648 vr = (uint32_t) (scaleto8_24 * vrf);
4649 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004650 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004651 // send level comes from shared memory and so may be corrupt
4652 if (sendLevel > MAX_GAIN_INT) {
4653 ALOGV("Track send level out of range: %04X", sendLevel);
4654 sendLevel = MAX_GAIN_INT;
4655 }
Andy Hung6be49402014-05-30 10:42:03 -07004656 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4657 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004658 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004659
Kevin Rocard12381092018-04-11 09:19:59 -07004660 track->setFinalVolume((vrf + vlf) / 2.f);
4661
Eric Laurent81784c32012-11-19 14:55:58 -08004662 // Delegate volume control to effect in track effect chain if needed
4663 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4664 // Do not ramp volume if volume is controlled by effect
4665 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004666 // Update remaining floating point volume levels
4667 vlf = (float)vl / (1 << 24);
4668 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004669 track->mHasVolumeController = true;
4670 } else {
4671 // force no volume ramp when volume controller was just disabled or removed
4672 // from effect chain to avoid volume spike
4673 if (track->mHasVolumeController) {
4674 param = AudioMixer::VOLUME;
4675 }
4676 track->mHasVolumeController = false;
4677 }
4678
Eric Laurent7c29ec92017-09-20 17:54:22 -07004679 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4680 // still applied by the mixer.
4681 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4682 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4683 if (v != mLeftVolFloat) {
4684 status_t result = mOutput->stream->setVolume(v, v);
4685 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4686 if (result == OK) {
4687 mLeftVolFloat = v;
4688 }
4689 }
4690 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4691 // remove stream volume contribution from software volume.
4692 if (v != 0.0f && mLeftVolFloat == v) {
4693 vlf = min(1.0f, vlf / v);
4694 vrf = min(1.0f, vrf / v);
4695 vaf = min(1.0f, vaf / v);
4696 }
4697 }
Eric Laurent81784c32012-11-19 14:55:58 -08004698 // XXX: these things DON'T need to be done each time
4699 mAudioMixer->setBufferProvider(name, track);
4700 mAudioMixer->enable(name);
4701
Andy Hung6be49402014-05-30 10:42:03 -07004702 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4703 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4704 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004705 mAudioMixer->setParameter(
4706 name,
4707 AudioMixer::TRACK,
4708 AudioMixer::FORMAT, (void *)track->format());
4709 mAudioMixer->setParameter(
4710 name,
4711 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004712 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004713 mAudioMixer->setParameter(
4714 name,
4715 AudioMixer::TRACK,
4716 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004717 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004718 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004719 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004720 if (reqSampleRate == 0) {
4721 reqSampleRate = mSampleRate;
4722 } else if (reqSampleRate > maxSampleRate) {
4723 reqSampleRate = maxSampleRate;
4724 }
Eric Laurent81784c32012-11-19 14:55:58 -08004725 mAudioMixer->setParameter(
4726 name,
4727 AudioMixer::RESAMPLE,
4728 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004729 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004730
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004731 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004732 mAudioMixer->setParameter(
4733 name,
4734 AudioMixer::TIMESTRETCH,
4735 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004736 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004737
Andy Hung69aed5f2014-02-25 17:24:40 -08004738 /*
4739 * Select the appropriate output buffer for the track.
4740 *
Andy Hung98ef9782014-03-04 14:46:50 -08004741 * Tracks with effects go into their own effects chain buffer
4742 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004743 *
4744 * Other tracks can use mMixerBuffer for higher precision
4745 * channel accumulation. If this buffer is enabled
4746 * (mMixerBufferEnabled true), then selected tracks will accumulate
4747 * into it.
4748 *
4749 */
4750 if (mMixerBufferEnabled
4751 && (track->mainBuffer() == mSinkBuffer
4752 || track->mainBuffer() == mMixerBuffer)) {
4753 mAudioMixer->setParameter(
4754 name,
4755 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004756 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004757 mAudioMixer->setParameter(
4758 name,
4759 AudioMixer::TRACK,
4760 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4761 // TODO: override track->mainBuffer()?
4762 mMixerBufferValid = true;
4763 } else {
4764 mAudioMixer->setParameter(
4765 name,
4766 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004767 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004768 mAudioMixer->setParameter(
4769 name,
4770 AudioMixer::TRACK,
4771 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4772 }
Eric Laurent81784c32012-11-19 14:55:58 -08004773 mAudioMixer->setParameter(
4774 name,
4775 AudioMixer::TRACK,
4776 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4777
4778 // reset retry count
4779 track->mRetryCount = kMaxTrackRetries;
4780
4781 // If one track is ready, set the mixer ready if:
4782 // - the mixer was not ready during previous round OR
4783 // - no other track is not ready
4784 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4785 mixerStatus != MIXER_TRACKS_ENABLED) {
4786 mixerStatus = MIXER_TRACKS_READY;
4787 }
4788 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004789 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004790 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004791 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4792 track, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004793 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004794 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004795 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004796
Eric Laurent81784c32012-11-19 14:55:58 -08004797 // clear effect chain input buffer if an active track underruns to avoid sending
4798 // previous audio buffer again to effects
4799 chain = getEffectChain_l(track->sessionId());
4800 if (chain != 0) {
4801 chain->clearInputBuffer();
4802 }
4803
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004804 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004805 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4806 track->isStopped() || track->isPaused()) {
4807 // We have consumed all the buffers of this track.
4808 // Remove it from the list of active tracks.
4809 // TODO: use actual buffer filling status instead of latency when available from
4810 // audio HAL
4811 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004812 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004813 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4814 if (track->isStopped()) {
4815 track->reset();
4816 }
4817 tracksToRemove->add(track);
4818 }
4819 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004820 // No buffers for this track. Give it a few chances to
4821 // fill a buffer, then remove it from active list.
4822 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004823 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004824 tracksToRemove->add(track);
4825 // indicate to client process that the track was disabled because of underrun;
4826 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004827 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004828 // If one track is not ready, mark the mixer also not ready if:
4829 // - the mixer was ready during previous round OR
4830 // - no other track is ready
4831 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4832 mixerStatus != MIXER_TRACKS_READY) {
4833 mixerStatus = MIXER_TRACKS_ENABLED;
4834 }
4835 }
4836 mAudioMixer->disable(name);
4837 }
4838
4839 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004840
4841 }
4842
4843 // Push the new FastMixer state if necessary
4844 bool pauseAudioWatchdog = false;
4845 if (didModify) {
4846 state->mFastTracksGen++;
4847 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4848 if (kUseFastMixer == FastMixer_Dynamic &&
4849 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4850 state->mCommand = FastMixerState::COLD_IDLE;
4851 state->mColdFutexAddr = &mFastMixerFutex;
4852 state->mColdGen++;
4853 mFastMixerFutex = 0;
4854 if (kUseFastMixer == FastMixer_Dynamic) {
4855 mNormalSink = mOutputSink;
4856 }
4857 // If we go into cold idle, need to wait for acknowledgement
4858 // so that fast mixer stops doing I/O.
4859 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4860 pauseAudioWatchdog = true;
4861 }
Eric Laurent81784c32012-11-19 14:55:58 -08004862 }
4863 if (sq != NULL) {
4864 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004865 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4866 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4867 // when bringing the output sink into standby.)
4868 //
4869 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4870 //
4871 // This occurs with BT suspend when we idle the FastMixer with
4872 // active tracks, which may be added or removed.
4873 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004874 }
4875#ifdef AUDIO_WATCHDOG
4876 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4877 mAudioWatchdog->pause();
4878 }
4879#endif
4880
4881 // Now perform the deferred reset on fast tracks that have stopped
4882 while (resetMask != 0) {
4883 size_t i = __builtin_ctz(resetMask);
4884 ALOG_ASSERT(i < count);
4885 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004886 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004887 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4888 track->reset();
4889 }
4890
Andy Hung80d03d22018-04-10 10:32:11 -07004891 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4892 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4893 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4894 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4895 // See also the implementation of destroyTrack_l().
4896 for (const auto &track : *tracksToRemove) {
4897 const int name = track->name();
4898 if (mAudioMixer->exists(name)) { // Normal tracks here, fast tracks in FastMixer.
4899 mAudioMixer->setBufferProvider(name, nullptr /* bufferProvider */);
4900 }
4901 }
4902
Eric Laurent81784c32012-11-19 14:55:58 -08004903 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004904 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004905
Eric Laurent97d547d2014-09-02 14:45:53 -07004906 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4907 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004908 }
4909
4910 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004911 // as long as there are effects we should clear the effects buffer, to avoid
4912 // passing a non-clean buffer to the effect chain
4913 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004914 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004915 // sink or mix buffer must be cleared if all tracks are connected to an
4916 // effect chain as in this case the mixer will not write to the sink or mix buffer
4917 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004918 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4919 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004920 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004921 if (mMixerBufferValid) {
4922 memset(mMixerBuffer, 0, mMixerBufferSize);
4923 // TODO: In testing, mSinkBuffer below need not be cleared because
4924 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4925 // after mixing.
4926 //
4927 // To enforce this guarantee:
4928 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4929 // (mixedTracks == 0 && fastTracks > 0))
4930 // must imply MIXER_TRACKS_READY.
4931 // Later, we may clear buffers regardless, and skip much of this logic.
4932 }
Andy Hung98ef9782014-03-04 14:46:50 -08004933 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004934 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004935 }
4936
4937 // if any fast tracks, then status is ready
4938 mMixerStatusIgnoringFastTracks = mixerStatus;
4939 if (fastTracks > 0) {
4940 mixerStatus = MIXER_TRACKS_READY;
4941 }
4942 return mixerStatus;
4943}
4944
Eric Laurentad7dd962016-09-22 12:38:37 -07004945// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004946uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004947{
4948 uint32_t trackCount = 0;
4949 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004950 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004951 trackCount++;
4952 }
4953 }
4954 return trackCount;
4955}
4956
Andy Hung1bc088a2018-02-09 15:57:31 -08004957// isTrackAllowed_l() must be called with ThreadBase::mLock held
4958bool AudioFlinger::MixerThread::isTrackAllowed_l(
4959 audio_channel_mask_t channelMask, audio_format_t format,
4960 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004961{
Andy Hung1bc088a2018-02-09 15:57:31 -08004962 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4963 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004964 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004965 // Check validity as we don't call AudioMixer::create() here.
4966 if (!AudioMixer::isValidFormat(format)) {
4967 ALOGW("%s: invalid format: %#x", __func__, format);
4968 return false;
4969 }
4970 if (!AudioMixer::isValidChannelMask(channelMask)) {
4971 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4972 return false;
4973 }
4974 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004975}
4976
Eric Laurent10351942014-05-08 18:49:52 -07004977// checkForNewParameter_l() must be called with ThreadBase::mLock held
4978bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4979 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004980{
Eric Laurent81784c32012-11-19 14:55:58 -08004981 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004982 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004983
Eric Laurent10351942014-05-08 18:49:52 -07004984 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004985
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004986 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004987
Eric Laurent10351942014-05-08 18:49:52 -07004988 AudioParameter param = AudioParameter(keyValuePair);
4989 int value;
4990 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4991 reconfig = true;
4992 }
4993 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004994 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004995 status = BAD_VALUE;
4996 } else {
4997 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004998 reconfig = true;
4999 }
Eric Laurent10351942014-05-08 18:49:52 -07005000 }
5001 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005002 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005003 status = BAD_VALUE;
5004 } else {
5005 // no need to save value, since it's constant
5006 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005007 }
Eric Laurent10351942014-05-08 18:49:52 -07005008 }
5009 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5010 // do not accept frame count changes if tracks are open as the track buffer
5011 // size depends on frame count and correct behavior would not be guaranteed
5012 // if frame count is changed after track creation
5013 if (!mTracks.isEmpty()) {
5014 status = INVALID_OPERATION;
5015 } else {
5016 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005017 }
Eric Laurent10351942014-05-08 18:49:52 -07005018 }
5019 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005020#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005021 // when changing the audio output device, call addBatteryData to notify
5022 // the change
5023 if (mOutDevice != value) {
5024 uint32_t params = 0;
5025 // check whether speaker is on
5026 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5027 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005028 }
Eric Laurent10351942014-05-08 18:49:52 -07005029
5030 audio_devices_t deviceWithoutSpeaker
5031 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5032 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005033 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005034 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5035 }
5036
5037 if (params != 0) {
5038 addBatteryData(params);
5039 }
5040 }
Eric Laurent81784c32012-11-19 14:55:58 -08005041#endif
5042
Eric Laurent10351942014-05-08 18:49:52 -07005043 // forward device change to effects that have requested to be
5044 // aware of attached audio device.
5045 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005046 a2dpDeviceChanged =
5047 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005048 mOutDevice = value;
5049 for (size_t i = 0; i < mEffectChains.size(); i++) {
5050 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005051 }
5052 }
Eric Laurent10351942014-05-08 18:49:52 -07005053 }
Eric Laurent81784c32012-11-19 14:55:58 -08005054
Eric Laurent10351942014-05-08 18:49:52 -07005055 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005056 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005057 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005058 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005059 mStandby = true;
5060 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005061 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005062 }
Eric Laurent10351942014-05-08 18:49:52 -07005063 if (status == NO_ERROR && reconfig) {
5064 readOutputParameters_l();
5065 delete mAudioMixer;
5066 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005067 for (const auto &track : mTracks) {
5068 const int name = track->name();
5069 status_t status = mAudioMixer->create(
5070 name,
5071 track->mChannelMask,
5072 track->mFormat,
5073 track->mSessionId);
5074 ALOGW_IF(status != NO_ERROR,
5075 "%s: cannot create track name"
5076 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
5077 __func__,
5078 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005079 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005080 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005081 }
Eric Laurent81784c32012-11-19 14:55:58 -08005082 }
5083
Eric Laurent42537be2016-01-08 17:16:42 -08005084 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005085}
5086
5087
5088void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5089{
Eric Laurent81784c32012-11-19 14:55:58 -08005090 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005091 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005092 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005093 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005094 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005095 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005096 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005097 } else {
5098 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005099 }
Eric Laurent81784c32012-11-19 14:55:58 -08005100
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005101 if (hasFastMixer()) {
5102 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5103
5104 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5105 // while we are dumping it. It may be inconsistent, but it won't mutate!
5106 // This is a large object so we place it on the heap.
5107 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan7b651152018-07-13 10:17:19 -07005108 const std::unique_ptr<FastMixerDumpState> copy(new FastMixerDumpState(mFastMixerDumpState));
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005109 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005110
5111#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005112 // Similar for state queue
5113 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5114 observerCopy.dump(fd);
5115 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5116 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005117#endif
5118
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005119#ifdef AUDIO_WATCHDOG
5120 if (mAudioWatchdog != 0) {
5121 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5122 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5123 wdCopy.dump(fd);
5124 }
5125#endif
5126
5127 } else {
5128 dprintf(fd, " No FastMixer\n");
5129 }
Eric Laurent81784c32012-11-19 14:55:58 -08005130}
5131
Eric Tan7b651152018-07-13 10:17:19 -07005132std::string AudioFlinger::MixerThread::getJsonString() const
5133{
5134 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5135 // while we are dumping it. It may be inconsistent, but it won't mutate!
5136 // This is a large object so we place it on the heap.
5137 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5138 return std::unique_ptr<FastMixerDumpState>(new FastMixerDumpState(mFastMixerDumpState))
5139 ->getJsonString();
5140}
5141
Eric Laurent81784c32012-11-19 14:55:58 -08005142uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5143{
5144 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5145}
5146
5147uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5148{
5149 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5150}
5151
5152void AudioFlinger::MixerThread::cacheParameters_l()
5153{
5154 PlaybackThread::cacheParameters_l();
5155
5156 // FIXME: Relaxed timing because of a certain device that can't meet latency
5157 // Should be reduced to 2x after the vendor fixes the driver issue
5158 // increase threshold again due to low power audio mode. The way this warning
5159 // threshold is calculated and its usefulness should be reconsidered anyway.
5160 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5161}
5162
5163// ----------------------------------------------------------------------------
5164
5165AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005166 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5167 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005168{
5169}
5170
Eric Laurentbfb1b832013-01-07 09:53:42 -08005171AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5172 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005173 ThreadBase::type_t type, bool systemReady)
5174 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005175 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005176{
5177}
5178
Eric Laurent81784c32012-11-19 14:55:58 -08005179AudioFlinger::DirectOutputThread::~DirectOutputThread()
5180{
5181}
5182
Eric Laurent5850c4c2016-11-10 13:04:31 -08005183void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005184{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005185 float left, right;
5186
5187 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5188 left = right = 0;
5189 } else {
5190 float typeVolume = mStreamTypes[track->streamType()].volume;
5191 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005192 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005193
Andy Hung10cbff12017-02-21 17:30:14 -08005194 // Get volumeshaper scaling
5195 std::pair<float /* volume */, bool /* active */>
5196 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005197 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005198 v *= vh.first;
5199 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005200
Glenn Kastenc56f3422014-03-21 17:53:17 -07005201 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5202 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5203 if (left > GAIN_FLOAT_UNITY) {
5204 left = GAIN_FLOAT_UNITY;
5205 }
5206 left *= v;
5207 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5208 if (right > GAIN_FLOAT_UNITY) {
5209 right = GAIN_FLOAT_UNITY;
5210 }
5211 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005212 }
5213
5214 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005215 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005216 if (left != mLeftVolFloat || right != mRightVolFloat) {
5217 mLeftVolFloat = left;
5218 mRightVolFloat = right;
5219
5220 // Convert volumes from float to 8.24
5221 uint32_t vl = (uint32_t)(left * (1 << 24));
5222 uint32_t vr = (uint32_t)(right * (1 << 24));
5223
5224 // Delegate volume control to effect in track effect chain if needed
5225 // only one effect chain can be present on DirectOutputThread, so if
5226 // there is one, the track is connected to it
5227 if (!mEffectChains.isEmpty()) {
5228 mEffectChains[0]->setVolume_l(&vl, &vr);
5229 left = (float)vl / (1 << 24);
5230 right = (float)vr / (1 << 24);
5231 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005232 status_t result = mOutput->stream->setVolume(left, right);
5233 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005234 }
5235 }
5236}
5237
Phil Burk43b4dcc2015-06-09 16:53:44 -07005238void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5239{
5240 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005241 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005242
Eric Laurent0f0631e2015-07-06 18:01:25 -07005243 if (previousTrack != 0 && latestTrack != 0) {
5244 if (mType == DIRECT) {
5245 if (previousTrack.get() != latestTrack.get()) {
5246 mFlushPending = true;
5247 }
5248 } else /* mType == OFFLOAD */ {
5249 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5250 mFlushPending = true;
5251 }
5252 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005253 }
5254 PlaybackThread::onAddNewTrack_l();
5255}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005256
Eric Laurent81784c32012-11-19 14:55:58 -08005257AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5258 Vector< sp<Track> > *tracksToRemove
5259)
5260{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005261 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005262 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005263 bool doHwPause = false;
5264 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005265
5266 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005267 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005268 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005269 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005270 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005271 continue;
5272 }
5273
Eric Laurent5850c4c2016-11-10 13:04:31 -08005274 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005275#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005276 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005277#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005278 // Only consider last track started for volume and mixer state control.
5279 // In theory an older track could underrun and restart after the new one starts
5280 // but as we only care about the transition phase between two tracks on a
5281 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005282 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005283 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005284
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005285 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005286 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005287 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005288 doHwPause = true;
5289 mHwPaused = true;
5290 }
5291 tracksToRemove->add(track);
5292 } else if (track->isFlushPending()) {
5293 track->flushAck();
5294 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005295 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005296 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005297 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005298 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005299 if (last) {
5300 mLeftVolFloat = mRightVolFloat = -1.0;
5301 if (mHwPaused) {
5302 doHwResume = true;
5303 mHwPaused = false;
5304 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005305 }
5306 }
5307
Eric Laurent81784c32012-11-19 14:55:58 -08005308 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005309 // for all its buffers to be filled before processing it.
5310 // Allow draining the buffer in case the client
5311 // app does not call stop() and relies on underrun to stop:
5312 // hence the test on (track->mRetryCount > 1).
5313 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005314 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005315 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005316 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005317 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005318 minFrames = mNormalFrameCount;
5319 } else {
5320 minFrames = 1;
5321 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005322
Eric Laurentab5cdba2014-06-09 17:22:27 -07005323 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5324 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005325 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005326 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005327
5328 if (track->mFillingUpStatus == Track::FS_FILLED) {
5329 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005330 if (last) {
5331 // make sure processVolume_l() will apply new volume even if 0
5332 mLeftVolFloat = mRightVolFloat = -1.0;
5333 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005334 if (!mHwSupportsPause) {
5335 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005336 }
5337 }
5338
5339 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005340 processVolume_l(track, last);
5341 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005342 sp<Track> previousTrack = mPreviousTrack.promote();
5343 if (previousTrack != 0) {
5344 if (track != previousTrack.get()) {
5345 // Flush any data still being written from last track
5346 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005347 // Invalidate previous track to force a seek when resuming.
5348 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005349 }
5350 }
5351 mPreviousTrack = track;
5352
Eric Laurentd595b7c2013-04-03 17:27:56 -07005353 // reset retry count
5354 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005355 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005356 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005357 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005358 doHwResume = true;
5359 mHwPaused = false;
5360 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005361 }
Eric Laurent81784c32012-11-19 14:55:58 -08005362 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005363 // clear effect chain input buffer if the last active track started underruns
5364 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005365 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005366 mEffectChains[0]->clearInputBuffer();
5367 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005368 if (track->isStopping_1()) {
5369 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005370 if (last && mHwPaused) {
5371 doHwResume = true;
5372 mHwPaused = false;
5373 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005374 }
5375 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5376 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005377 // We have consumed all the buffers of this track.
5378 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005379 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005380 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005381 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5382 } else {
5383 audioHALFrames = 0;
5384 }
5385
Andy Hung818e7a32016-02-16 18:08:07 -08005386 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005387 if (mStandby || !last ||
5388 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005389 if (track->isStopping_2()) {
5390 track->mState = TrackBase::STOPPED;
5391 }
Eric Laurent81784c32012-11-19 14:55:58 -08005392 if (track->isStopped()) {
5393 track->reset();
5394 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005395 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005396 }
5397 } else {
5398 // No buffers for this track. Give it a few chances to
5399 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005400 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005401 if (--(track->mRetryCount) <= 0) {
5402 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005403 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005404 // indicate to client process that the track was disabled because of underrun;
5405 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005406 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005407 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005408 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5409 "minFrames = %u, mFormat = %#x",
5410 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005411 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005412 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005413 doHwPause = true;
5414 mHwPaused = true;
5415 }
Eric Laurent81784c32012-11-19 14:55:58 -08005416 }
5417 }
5418 }
5419 }
5420
Eric Laurentd1f69b02014-12-15 14:33:13 -08005421 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005422 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005423 for (size_t i = 0; i < mTracks.size(); i++) {
5424 if (mTracks[i]->isFlushPending()) {
5425 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005426 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005427 }
5428 }
5429 }
5430
5431 // make sure the pause/flush/resume sequence is executed in the right order.
5432 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5433 // before flush and then resume HW. This can happen in case of pause/flush/resume
5434 // if resume is received before pause is executed.
5435 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005436 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005437 status_t result = mOutput->stream->pause();
5438 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005439 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005440 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005441 flushHw_l();
5442 }
5443 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005444 status_t result = mOutput->stream->resume();
5445 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005446 }
Eric Laurent81784c32012-11-19 14:55:58 -08005447 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005448 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005449
5450 return mixerStatus;
5451}
5452
5453void AudioFlinger::DirectOutputThread::threadLoop_mix()
5454{
Eric Laurent81784c32012-11-19 14:55:58 -08005455 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005456 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005457 // output audio to hardware
5458 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005459 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005460 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005461 status_t status = mActiveTrack->getNextBuffer(&buffer);
5462 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005463 // no need to pad with 0 for compressed audio
5464 if (audio_has_proportional_frames(mFormat)) {
5465 memset(curBuf, 0, frameCount * mFrameSize);
5466 }
Eric Laurent81784c32012-11-19 14:55:58 -08005467 break;
5468 }
5469 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5470 frameCount -= buffer.frameCount;
5471 curBuf += buffer.frameCount * mFrameSize;
5472 mActiveTrack->releaseBuffer(&buffer);
5473 }
Andy Hung2098f272014-02-27 14:00:06 -08005474 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005475 mSleepTimeUs = 0;
5476 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005477 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005478}
5479
5480void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5481{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005482 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005483 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005484 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005485 return;
5486 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005487 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005488 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005489 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005490 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005491 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005492 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005493 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005494 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005495 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005496 }
5497}
5498
Eric Laurentd1f69b02014-12-15 14:33:13 -08005499void AudioFlinger::DirectOutputThread::threadLoop_exit()
5500{
5501 {
5502 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005503 for (size_t i = 0; i < mTracks.size(); i++) {
5504 if (mTracks[i]->isFlushPending()) {
5505 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005506 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005507 }
5508 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005509 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005510 flushHw_l();
5511 }
5512 }
5513 PlaybackThread::threadLoop_exit();
5514}
5515
5516// must be called with thread mutex locked
5517bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5518{
5519 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005520 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005521
vivek mehta9cd7ad12016-03-17 00:18:29 -07005522 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5523 return !mStandby;
5524 }
5525
Eric Laurentd1f69b02014-12-15 14:33:13 -08005526 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5527 // after a timeout and we will enter standby then.
5528 if (mTracks.size() > 0) {
5529 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005530 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5531 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005532 }
5533
Eric Laurent5cff4032015-05-26 13:49:58 -07005534 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005535}
5536
Eric Laurent10351942014-05-08 18:49:52 -07005537// checkForNewParameter_l() must be called with ThreadBase::mLock held
5538bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5539 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005540{
5541 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005542 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005543
Eric Laurent10351942014-05-08 18:49:52 -07005544 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005545
Eric Laurent10351942014-05-08 18:49:52 -07005546 AudioParameter param = AudioParameter(keyValuePair);
5547 int value;
5548 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5549 // forward device change to effects that have requested to be
5550 // aware of attached audio device.
5551 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005552 a2dpDeviceChanged =
5553 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005554 mOutDevice = value;
5555 for (size_t i = 0; i < mEffectChains.size(); i++) {
5556 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005557 }
5558 }
Eric Laurent81784c32012-11-19 14:55:58 -08005559 }
Eric Laurent10351942014-05-08 18:49:52 -07005560 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5561 // do not accept frame count changes if tracks are open as the track buffer
5562 // size depends on frame count and correct behavior would not be garantied
5563 // if frame count is changed after track creation
5564 if (!mTracks.isEmpty()) {
5565 status = INVALID_OPERATION;
5566 } else {
5567 reconfig = true;
5568 }
5569 }
5570 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005571 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005572 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005573 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005574 mStandby = true;
5575 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005576 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005577 }
5578 if (status == NO_ERROR && reconfig) {
5579 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005580 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005581 }
5582 }
5583
Eric Laurent42537be2016-01-08 17:16:42 -08005584 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005585}
5586
5587uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5588{
5589 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005590 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005591 time = PlaybackThread::activeSleepTimeUs();
5592 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005593 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005594 }
5595 return time;
5596}
5597
5598uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5599{
5600 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005601 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005602 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5603 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005604 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005605 }
5606 return time;
5607}
5608
5609uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5610{
5611 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005612 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005613 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5614 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005615 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005616 }
5617 return time;
5618}
5619
5620void AudioFlinger::DirectOutputThread::cacheParameters_l()
5621{
5622 PlaybackThread::cacheParameters_l();
5623
5624 // use shorter standby delay as on normal output to release
5625 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005626 // no delay on outputs with HW A/V sync
5627 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005628 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005629 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005630 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005631 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005632 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005633 }
Eric Laurent81784c32012-11-19 14:55:58 -08005634}
5635
Eric Laurente659ef42014-09-29 13:06:46 -07005636void AudioFlinger::DirectOutputThread::flushHw_l()
5637{
Phil Burk062e67a2015-02-11 13:40:50 -08005638 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005639 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005640 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005641}
5642
Andy Hung10cbff12017-02-21 17:30:14 -08005643int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5644 // If a VolumeShaper is active, we must wake up periodically to update volume.
5645 const int64_t NS_PER_MS = 1000000;
5646 return mVolumeShaperActive ?
5647 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5648}
5649
Eric Laurent81784c32012-11-19 14:55:58 -08005650// ----------------------------------------------------------------------------
5651
Eric Laurentbfb1b832013-01-07 09:53:42 -08005652AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005653 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005654 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005655 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005656 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005657 mDrainSequence(0),
5658 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005659{
5660}
5661
5662AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5663{
5664}
5665
5666void AudioFlinger::AsyncCallbackThread::onFirstRef()
5667{
5668 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5669}
5670
5671bool AudioFlinger::AsyncCallbackThread::threadLoop()
5672{
5673 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005674 uint32_t writeAckSequence;
5675 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005676 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005677
5678 {
5679 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005680 while (!((mWriteAckSequence & 1) ||
5681 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005682 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005683 exitPending())) {
5684 mWaitWorkCV.wait(mLock);
5685 }
5686
Eric Laurentbfb1b832013-01-07 09:53:42 -08005687 if (exitPending()) {
5688 break;
5689 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005690 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5691 mWriteAckSequence, mDrainSequence);
5692 writeAckSequence = mWriteAckSequence;
5693 mWriteAckSequence &= ~1;
5694 drainSequence = mDrainSequence;
5695 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005696 asyncError = mAsyncError;
5697 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005698 }
5699 {
Eric Laurent4de95592013-09-26 15:28:21 -07005700 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5701 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005702 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005703 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005704 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005705 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005706 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005707 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005708 if (asyncError) {
5709 playbackThread->onAsyncError();
5710 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005711 }
5712 }
5713 }
5714 return false;
5715}
5716
5717void AudioFlinger::AsyncCallbackThread::exit()
5718{
5719 ALOGV("AsyncCallbackThread::exit");
5720 Mutex::Autolock _l(mLock);
5721 requestExit();
5722 mWaitWorkCV.broadcast();
5723}
5724
Eric Laurent3b4529e2013-09-05 18:09:19 -07005725void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005726{
5727 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005728 // bit 0 is cleared
5729 mWriteAckSequence = sequence << 1;
5730}
5731
5732void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5733{
5734 Mutex::Autolock _l(mLock);
5735 // ignore unexpected callbacks
5736 if (mWriteAckSequence & 2) {
5737 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005738 mWaitWorkCV.signal();
5739 }
5740}
5741
Eric Laurent3b4529e2013-09-05 18:09:19 -07005742void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005743{
5744 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005745 // bit 0 is cleared
5746 mDrainSequence = sequence << 1;
5747}
5748
5749void AudioFlinger::AsyncCallbackThread::resetDraining()
5750{
5751 Mutex::Autolock _l(mLock);
5752 // ignore unexpected callbacks
5753 if (mDrainSequence & 2) {
5754 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005755 mWaitWorkCV.signal();
5756 }
5757}
5758
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005759void AudioFlinger::AsyncCallbackThread::setAsyncError()
5760{
5761 Mutex::Autolock _l(mLock);
5762 mAsyncError = true;
5763 mWaitWorkCV.signal();
5764}
5765
Eric Laurentbfb1b832013-01-07 09:53:42 -08005766
5767// ----------------------------------------------------------------------------
5768AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005769 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5770 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005771 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5772 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005773{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005774 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005775 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005776 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005777}
5778
Eric Laurentbfb1b832013-01-07 09:53:42 -08005779void AudioFlinger::OffloadThread::threadLoop_exit()
5780{
5781 if (mFlushPending || mHwPaused) {
5782 // If a flush is pending or track was paused, just discard buffered data
5783 flushHw_l();
5784 } else {
5785 mMixerStatus = MIXER_DRAIN_ALL;
5786 threadLoop_drain();
5787 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005788 if (mUseAsyncWrite) {
5789 ALOG_ASSERT(mCallbackThread != 0);
5790 mCallbackThread->exit();
5791 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005792 PlaybackThread::threadLoop_exit();
5793}
5794
5795AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5796 Vector< sp<Track> > *tracksToRemove
5797)
5798{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005799 size_t count = mActiveTracks.size();
5800
5801 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005802 bool doHwPause = false;
5803 bool doHwResume = false;
5804
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005805 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005806
Eric Laurentbfb1b832013-01-07 09:53:42 -08005807 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005808 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005809 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005810#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005811 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005812#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005813 // Only consider last track started for volume and mixer state control.
5814 // In theory an older track could underrun and restart after the new one starts
5815 // but as we only care about the transition phase between two tracks on a
5816 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005817 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005818 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005819
Haynes Mathew George7844f672014-01-15 12:32:55 -08005820 if (track->isInvalid()) {
5821 ALOGW("An invalidated track shouldn't be in active list");
5822 tracksToRemove->add(track);
5823 continue;
5824 }
5825
5826 if (track->mState == TrackBase::IDLE) {
5827 ALOGW("An idle track shouldn't be in active list");
5828 continue;
5829 }
5830
Eric Laurentbfb1b832013-01-07 09:53:42 -08005831 if (track->isPausing()) {
5832 track->setPaused();
5833 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005834 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005835 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005836 mHwPaused = true;
5837 }
5838 // If we were part way through writing the mixbuffer to
5839 // the HAL we must save this until we resume
5840 // BUG - this will be wrong if a different track is made active,
5841 // in that case we want to discard the pending data in the
5842 // mixbuffer and tell the client to present it again when the
5843 // track is resumed
5844 mPausedWriteLength = mCurrentWriteLength;
5845 mPausedBytesRemaining = mBytesRemaining;
5846 mBytesRemaining = 0; // stop writing
5847 }
5848 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005849 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005850 if (track->isStopping_1()) {
5851 track->mRetryCount = kMaxTrackStopRetriesOffload;
5852 } else {
5853 track->mRetryCount = kMaxTrackRetriesOffload;
5854 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005855 track->flushAck();
5856 if (last) {
5857 mFlushPending = true;
5858 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005859 } else if (track->isResumePending()){
5860 track->resumeAck();
5861 if (last) {
5862 if (mPausedBytesRemaining) {
5863 // Need to continue write that was interrupted
5864 mCurrentWriteLength = mPausedWriteLength;
5865 mBytesRemaining = mPausedBytesRemaining;
5866 mPausedBytesRemaining = 0;
5867 }
5868 if (mHwPaused) {
5869 doHwResume = true;
5870 mHwPaused = false;
5871 // threadLoop_mix() will handle the case that we need to
5872 // resume an interrupted write
5873 }
5874 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005875 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005876
Eric Laurent3df841a2016-07-15 15:15:40 -07005877 mLeftVolFloat = mRightVolFloat = -1.0;
5878
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005879 // Do not handle new data in this iteration even if track->framesReady()
5880 mixerStatus = MIXER_TRACKS_ENABLED;
5881 }
5882 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005883 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005884 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005885 if (track->mFillingUpStatus == Track::FS_FILLED) {
5886 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005887 if (last) {
5888 // make sure processVolume_l() will apply new volume even if 0
5889 mLeftVolFloat = mRightVolFloat = -1.0;
5890 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005891 }
5892
5893 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005894 sp<Track> previousTrack = mPreviousTrack.promote();
5895 if (previousTrack != 0) {
5896 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005897 // Flush any data still being written from last track
5898 mBytesRemaining = 0;
5899 if (mPausedBytesRemaining) {
5900 // Last track was paused so we also need to flush saved
5901 // mixbuffer state and invalidate track so that it will
5902 // re-submit that unwritten data when it is next resumed
5903 mPausedBytesRemaining = 0;
5904 // Invalidate is a bit drastic - would be more efficient
5905 // to have a flag to tell client that some of the
5906 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005907 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005908 }
5909 // flush data already sent to the DSP if changing audio session as audio
5910 // comes from a different source. Also invalidate previous track to force a
5911 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005912 if (previousTrack->sessionId() != track->sessionId()) {
5913 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005914 }
5915 }
5916 }
5917 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005918 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005919 if (track->isStopping_1()) {
5920 track->mRetryCount = kMaxTrackStopRetriesOffload;
5921 } else {
5922 track->mRetryCount = kMaxTrackRetriesOffload;
5923 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005924 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005925 mixerStatus = MIXER_TRACKS_READY;
5926 }
5927 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005928 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005929 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005930 if (--(track->mRetryCount) <= 0) {
5931 // Hardware buffer can hold a large amount of audio so we must
5932 // wait for all current track's data to drain before we say
5933 // that the track is stopped.
5934 if (mBytesRemaining == 0) {
5935 // Only start draining when all data in mixbuffer
5936 // has been written
5937 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5938 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5939 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5940 if (last && !mStandby) {
5941 // do not modify drain sequence if we are already draining. This happens
5942 // when resuming from pause after drain.
5943 if ((mDrainSequence & 1) == 0) {
5944 mSleepTimeUs = 0;
5945 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5946 mixerStatus = MIXER_DRAIN_TRACK;
5947 mDrainSequence += 2;
5948 }
5949 if (mHwPaused) {
5950 // It is possible to move from PAUSED to STOPPING_1 without
5951 // a resume so we must ensure hardware is running
5952 doHwResume = true;
5953 mHwPaused = false;
5954 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005955 }
5956 }
Eric Laurente93cc032016-05-05 10:15:10 -07005957 } else if (last) {
5958 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5959 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005960 }
5961 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005962 // Drain has completed or we are in standby, signal presentation complete
5963 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005964 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005965 uint32_t latency = 0;
5966 status_t result = mOutput->stream->getLatency(&latency);
5967 ALOGE_IF(result != OK,
5968 "Error when retrieving output stream latency: %d", result);
5969 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005970 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005971 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005972 track->presentationComplete(framesWritten, audioHALFrames);
5973 track->reset();
5974 tracksToRemove->add(track);
5975 }
5976 } else {
5977 // No buffers for this track. Give it a few chances to
5978 // fill a buffer, then remove it from active list.
5979 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005980 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005981 uint64_t position = 0;
5982 struct timespec unused;
5983 // The running check restarts the retry counter at least once.
5984 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5985 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5986 running = true;
5987 mOffloadUnderrunPosition = position;
5988 }
5989 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005990 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5991 (long long)position, (long long)mOffloadUnderrunPosition);
5992 }
5993 if (running) { // still running, give us more time.
5994 track->mRetryCount = kMaxTrackRetriesOffload;
5995 } else {
5996 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5997 track->name());
5998 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005999 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006000 // it will then automatically call start() when data is available
6001 track->disable();
6002 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006003 } else if (last){
6004 mixerStatus = MIXER_TRACKS_ENABLED;
6005 }
6006 }
6007 }
6008 // compute volume for this track
6009 processVolume_l(track, last);
6010 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006011
Eric Laurentea0fade2013-10-04 16:23:48 -07006012 // make sure the pause/flush/resume sequence is executed in the right order.
6013 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6014 // before flush and then resume HW. This can happen in case of pause/flush/resume
6015 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006016 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006017 status_t result = mOutput->stream->pause();
6018 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006019 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006020 if (mFlushPending) {
6021 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006022 }
Eric Laurentfd477972013-10-25 18:10:40 -07006023 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006024 status_t result = mOutput->stream->resume();
6025 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006026 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006027
Eric Laurentbfb1b832013-01-07 09:53:42 -08006028 // remove all the tracks that need to be...
6029 removeTracks_l(*tracksToRemove);
6030
6031 return mixerStatus;
6032}
6033
Eric Laurentbfb1b832013-01-07 09:53:42 -08006034// must be called with thread mutex locked
6035bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6036{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006037 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6038 mWriteAckSequence, mDrainSequence);
6039 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006040 return true;
6041 }
6042 return false;
6043}
6044
Eric Laurentbfb1b832013-01-07 09:53:42 -08006045bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6046{
6047 Mutex::Autolock _l(mLock);
6048 return waitingAsyncCallback_l();
6049}
6050
6051void AudioFlinger::OffloadThread::flushHw_l()
6052{
Eric Laurente659ef42014-09-29 13:06:46 -07006053 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006054 // Flush anything still waiting in the mixbuffer
6055 mCurrentWriteLength = 0;
6056 mBytesRemaining = 0;
6057 mPausedWriteLength = 0;
6058 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006059 // reset bytes written count to reflect that DSP buffers are empty after flush.
6060 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006061 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006062
Eric Laurentbfb1b832013-01-07 09:53:42 -08006063 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006064 // discard any pending drain or write ack by incrementing sequence
6065 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6066 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006067 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006068 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6069 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006070 }
6071}
6072
Haynes Mathew George05317d22016-05-03 16:34:26 -07006073void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6074{
6075 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006076 if (PlaybackThread::invalidateTracks_l(streamType)) {
6077 mFlushPending = true;
6078 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006079}
6080
Eric Laurentbfb1b832013-01-07 09:53:42 -08006081// ----------------------------------------------------------------------------
6082
Eric Laurent81784c32012-11-19 14:55:58 -08006083AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006084 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006085 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006086 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006087 mWaitTimeMs(UINT_MAX)
6088{
6089 addOutputTrack(mainThread);
6090}
6091
6092AudioFlinger::DuplicatingThread::~DuplicatingThread()
6093{
6094 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6095 mOutputTracks[i]->destroy();
6096 }
6097}
6098
6099void AudioFlinger::DuplicatingThread::threadLoop_mix()
6100{
6101 // mix buffers...
6102 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006103 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006104 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006105 if (mMixerBufferValid) {
6106 memset(mMixerBuffer, 0, mMixerBufferSize);
6107 } else {
6108 memset(mSinkBuffer, 0, mSinkBufferSize);
6109 }
Eric Laurent81784c32012-11-19 14:55:58 -08006110 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006111 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006112 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006113 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006114 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006115}
6116
6117void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6118{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006119 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006120 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006121 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006122 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006123 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006124 }
6125 } else if (mBytesWritten != 0) {
6126 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6127 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006128 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006129 } else {
6130 // flush remaining overflow buffers in output tracks
6131 writeFrames = 0;
6132 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006133 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006134 }
6135}
6136
Eric Laurentbfb1b832013-01-07 09:53:42 -08006137ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006138{
6139 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006140 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6141
6142 // Consider the first OutputTrack for timestamp and frame counting.
6143
6144 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6145 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6146 // we always claim success.
6147 if (i == 0) {
6148 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6149 ALOGD_IF(correction != 0 && writeFrames != 0,
6150 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6151 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6152 mFramesWritten -= correction;
6153 }
6154
6155 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006156 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006157 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006158 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006159}
6160
6161void AudioFlinger::DuplicatingThread::threadLoop_standby()
6162{
6163 // DuplicatingThread implements standby by stopping all tracks
6164 for (size_t i = 0; i < outputTracks.size(); i++) {
6165 outputTracks[i]->stop();
6166 }
6167}
6168
Andy Hung1bc088a2018-02-09 15:57:31 -08006169void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6170{
6171 MixerThread::dumpInternals(fd, args);
6172
6173 std::stringstream ss;
6174 const size_t numTracks = mOutputTracks.size();
6175 ss << " " << numTracks << " OutputTracks";
6176 if (numTracks > 0) {
6177 ss << ":";
6178 for (const auto &track : mOutputTracks) {
6179 const sp<ThreadBase> thread = track->thread().promote();
6180 ss << " (" << track->name() << " : ";
6181 if (thread.get() != nullptr) {
6182 ss << thread.get() << ", " << thread->id();
6183 } else {
6184 ss << "null";
6185 }
6186 ss << ")";
6187 }
6188 }
6189 ss << "\n";
6190 std::string result = ss.str();
6191 write(fd, result.c_str(), result.size());
6192}
6193
Eric Laurent81784c32012-11-19 14:55:58 -08006194void AudioFlinger::DuplicatingThread::saveOutputTracks()
6195{
6196 outputTracks = mOutputTracks;
6197}
6198
6199void AudioFlinger::DuplicatingThread::clearOutputTracks()
6200{
6201 outputTracks.clear();
6202}
6203
6204void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6205{
6206 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006207 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6208 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6209 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6210 const size_t frameCount =
6211 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6212 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6213 // from different OutputTracks and their associated MixerThreads (e.g. one may
6214 // nearly empty and the other may be dropping data).
6215
6216 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006217 this,
6218 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006219 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006220 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006221 frameCount,
6222 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006223 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6224 if (status != NO_ERROR) {
6225 ALOGE("addOutputTrack() initCheck failed %d", status);
6226 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006227 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006228 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6229 mOutputTracks.add(outputTrack);
6230 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6231 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006232}
6233
6234void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6235{
6236 Mutex::Autolock _l(mLock);
6237 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6238 if (mOutputTracks[i]->thread() == thread) {
6239 mOutputTracks[i]->destroy();
6240 mOutputTracks.removeAt(i);
6241 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006242 if (thread->getOutput() == mOutput) {
6243 mOutput = NULL;
6244 }
Eric Laurent81784c32012-11-19 14:55:58 -08006245 return;
6246 }
6247 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006248 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006249}
6250
6251// caller must hold mLock
6252void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6253{
6254 mWaitTimeMs = UINT_MAX;
6255 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6256 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6257 if (strong != 0) {
6258 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6259 if (waitTimeMs < mWaitTimeMs) {
6260 mWaitTimeMs = waitTimeMs;
6261 }
6262 }
6263 }
6264}
6265
6266
6267bool AudioFlinger::DuplicatingThread::outputsReady(
6268 const SortedVector< sp<OutputTrack> > &outputTracks)
6269{
6270 for (size_t i = 0; i < outputTracks.size(); i++) {
6271 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6272 if (thread == 0) {
6273 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6274 outputTracks[i].get());
6275 return false;
6276 }
6277 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6278 // see note at standby() declaration
6279 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6280 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6281 thread.get());
6282 return false;
6283 }
6284 }
6285 return true;
6286}
6287
Kevin Rocard12381092018-04-11 09:19:59 -07006288void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6289 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006290{
Kevin Rocard12381092018-04-11 09:19:59 -07006291 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6292 outputTrack->setMetadatas(metadata.tracks);
6293 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006294}
6295
Eric Laurent81784c32012-11-19 14:55:58 -08006296uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6297{
6298 return (mWaitTimeMs * 1000) / 2;
6299}
6300
6301void AudioFlinger::DuplicatingThread::cacheParameters_l()
6302{
6303 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6304 updateWaitTime_l();
6305
6306 MixerThread::cacheParameters_l();
6307}
6308
Eric Laurent6acd1d42017-01-04 14:23:29 -08006309
Eric Laurent81784c32012-11-19 14:55:58 -08006310// ----------------------------------------------------------------------------
6311// Record
6312// ----------------------------------------------------------------------------
6313
6314AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6315 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006316 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006317 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006318 audio_devices_t inDevice,
6319 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006320 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006321 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006322 mInput(input),
6323 mActiveTracks(&this->mLocalLog),
6324 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006325 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006326 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006327 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6328 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006329 // mFastCapture below
6330 , mFastCaptureFutex(0)
6331 // mInputSource
6332 // mPipeSink
6333 // mPipeSource
6334 , mPipeFramesP2(0)
6335 // mPipeMemory
6336 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006337 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006338 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006339{
Glenn Kastend7dca052015-03-05 16:05:54 -08006340 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6341 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006342
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006343 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006344
6345 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006346 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006347 size_t numCounterOffers = 0;
6348 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006349#if !LOG_NDEBUG
6350 ssize_t index =
6351#else
6352 (void)
6353#endif
6354 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006355 ALOG_ASSERT(index == 0);
6356
6357 // initialize fast capture depending on configuration
6358 bool initFastCapture;
6359 switch (kUseFastCapture) {
6360 case FastCapture_Never:
6361 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006362 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006363 break;
6364 case FastCapture_Always:
6365 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006366 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006367 break;
6368 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006369 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006370 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6371 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6372 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006373 break;
6374 // case FastCapture_Dynamic:
6375 }
6376
6377 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006378 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006379 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006380 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6381 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006382 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006383 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006384 const sp<MemoryDealer> roHeap(readOnlyHeap());
6385 sp<IMemory> pipeMemory;
6386 if ((roHeap == 0) ||
6387 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006388 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6389 ALOGE("not enough memory for pipe buffer size=%zu; "
6390 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6391 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6392 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006393 goto failed;
6394 }
6395 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6396 memset(pipeBuffer, 0, pipeSize);
6397 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6398 const NBAIO_Format offers[1] = {format};
6399 size_t numCounterOffers = 0;
6400 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6401 ALOG_ASSERT(index == 0);
6402 mPipeSink = pipe;
6403 PipeReader *pipeReader = new PipeReader(*pipe);
6404 numCounterOffers = 0;
6405 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6406 ALOG_ASSERT(index == 0);
6407 mPipeSource = pipeReader;
6408 mPipeFramesP2 = pipeFramesP2;
6409 mPipeMemory = pipeMemory;
6410
6411 // create fast capture
6412 mFastCapture = new FastCapture();
6413 FastCaptureStateQueue *sq = mFastCapture->sq();
6414#ifdef STATE_QUEUE_DUMP
6415 // FIXME
6416#endif
6417 FastCaptureState *state = sq->begin();
6418 state->mCblk = NULL;
6419 state->mInputSource = mInputSource.get();
6420 state->mInputSourceGen++;
6421 state->mPipeSink = pipe;
6422 state->mPipeSinkGen++;
6423 state->mFrameCount = mFrameCount;
6424 state->mCommand = FastCaptureState::COLD_IDLE;
6425 // already done in constructor initialization list
6426 //mFastCaptureFutex = 0;
6427 state->mColdFutexAddr = &mFastCaptureFutex;
6428 state->mColdGen++;
6429 state->mDumpState = &mFastCaptureDumpState;
6430#ifdef TEE_SINK
6431 // FIXME
6432#endif
6433 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6434 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6435 sq->end();
6436 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6437
6438 // start the fast capture
6439 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6440 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006441 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006442 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006443#ifdef AUDIO_WATCHDOG
6444 // FIXME
6445#endif
6446
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006447 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006448 }
Andy Hung8946a282018-04-19 20:04:56 -07006449#ifdef TEE_SINK
6450 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6451 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6452#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006453failed: ;
6454
6455 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006456}
6457
Eric Laurent81784c32012-11-19 14:55:58 -08006458AudioFlinger::RecordThread::~RecordThread()
6459{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006460 if (mFastCapture != 0) {
6461 FastCaptureStateQueue *sq = mFastCapture->sq();
6462 FastCaptureState *state = sq->begin();
6463 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6464 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6465 if (old == -1) {
6466 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6467 }
6468 }
6469 state->mCommand = FastCaptureState::EXIT;
6470 sq->end();
6471 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6472 mFastCapture->join();
6473 mFastCapture.clear();
6474 }
6475 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006476 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006477 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006478}
6479
6480void AudioFlinger::RecordThread::onFirstRef()
6481{
Glenn Kastend7dca052015-03-05 16:05:54 -08006482 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006483}
6484
Eric Laurent555530a2017-02-07 18:17:24 -08006485void AudioFlinger::RecordThread::preExit()
6486{
6487 ALOGV(" preExit()");
6488 Mutex::Autolock _l(mLock);
6489 for (size_t i = 0; i < mTracks.size(); i++) {
6490 sp<RecordTrack> track = mTracks[i];
6491 track->invalidate();
6492 }
6493 mActiveTracks.clear();
6494 mStartStopCond.broadcast();
6495}
6496
Eric Laurent81784c32012-11-19 14:55:58 -08006497bool AudioFlinger::RecordThread::threadLoop()
6498{
Eric Laurent81784c32012-11-19 14:55:58 -08006499 nsecs_t lastWarning = 0;
6500
6501 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006502
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006503reacquire_wakelock:
6504 sp<RecordTrack> activeTrack;
6505 {
6506 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006507 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006508 }
6509
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006510 // used to request a deferred sleep, to be executed later while mutex is unlocked
6511 uint32_t sleepUs = 0;
6512
6513 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006514 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006515 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006516
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006517 // activeTracks accumulates a copy of a subset of mActiveTracks
6518 Vector< sp<RecordTrack> > activeTracks;
6519
Glenn Kasten735f45f2014-08-18 15:51:59 -07006520 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006521 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006522
Glenn Kasten735f45f2014-08-18 15:51:59 -07006523 // reference to a fast track which is about to be removed
6524 sp<RecordTrack> fastTrackToRemove;
6525
Eric Laurent81784c32012-11-19 14:55:58 -08006526 { // scope for mLock
6527 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006528
Eric Laurent021cf962014-05-13 10:18:14 -07006529 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006530
Eric Laurent000a4192014-01-29 15:17:32 -08006531 // check exitPending here because checkForNewParameters_l() and
6532 // checkForNewParameters_l() can temporarily release mLock
6533 if (exitPending()) {
6534 break;
6535 }
6536
Eric Laurent5c25d562016-07-13 17:17:45 -07006537 // sleep with mutex unlocked
6538 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006539 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006540 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6541 ATRACE_END();
6542 sleepUs = 0;
6543 continue;
6544 }
6545
Glenn Kasten2b806402013-11-20 16:37:38 -08006546 // if no active track(s), then standby and release wakelock
6547 size_t size = mActiveTracks.size();
6548 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006549 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006550 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006551 releaseWakeLock_l();
6552 ALOGV("RecordThread: loop stopping");
6553 // go to sleep
6554 mWaitWorkCV.wait(mLock);
6555 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006556 goto reacquire_wakelock;
6557 }
6558
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006559 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006560 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006561 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006562
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006563 activeTrack = mActiveTracks[i];
6564 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006565 if (activeTrack->isFastTrack()) {
6566 ALOG_ASSERT(fastTrackToRemove == 0);
6567 fastTrackToRemove = activeTrack;
6568 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006569 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006570 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006571 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006572 continue;
6573 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006574
6575 TrackBase::track_state activeTrackState = activeTrack->mState;
6576 switch (activeTrackState) {
6577
6578 case TrackBase::PAUSING:
6579 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006580 doBroadcast = true;
6581 size--;
6582 continue;
6583
6584 case TrackBase::STARTING_1:
6585 sleepUs = 10000;
6586 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006587 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006588 continue;
6589
6590 case TrackBase::STARTING_2:
6591 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006592 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006593 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006594 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006595 break;
6596
6597 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006598 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006599 break;
6600
6601 case TrackBase::IDLE:
6602 i++;
6603 continue;
6604
6605 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006606 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006607 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006608
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006609 activeTracks.add(activeTrack);
6610 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006611
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006612 if (activeTrack->isFastTrack()) {
6613 ALOG_ASSERT(!mFastTrackAvail);
6614 ALOG_ASSERT(fastTrack == 0);
6615 fastTrack = activeTrack;
6616 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006617 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006618
Andy Hungdae27702016-10-31 14:01:16 -07006619 mActiveTracks.updatePowerState(this);
6620
Kevin Rocard069c2712018-03-29 19:09:14 -07006621 updateMetadata_l();
6622
Eric Laurent5c25d562016-07-13 17:17:45 -07006623 if (allStopped) {
6624 standbyIfNotAlreadyInStandby();
6625 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006626 if (doBroadcast) {
6627 mStartStopCond.broadcast();
6628 }
6629
6630 // sleep if there are no active tracks to process
6631 if (activeTracks.size() == 0) {
6632 if (sleepUs == 0) {
6633 sleepUs = kRecordThreadSleepUs;
6634 }
6635 continue;
6636 }
6637 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006638
Eric Laurent81784c32012-11-19 14:55:58 -08006639 lockEffectChains_l(effectChains);
6640 }
6641
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006642 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006643
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006644 size_t size = effectChains.size();
6645 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006646 // thread mutex is not locked, but effect chain is locked
6647 effectChains[i]->process_l();
6648 }
6649
Glenn Kasten735f45f2014-08-18 15:51:59 -07006650 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006651 if (mFastCapture != 0) {
6652 FastCaptureStateQueue *sq = mFastCapture->sq();
6653 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006654 bool didModify = false;
6655 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006656 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6657 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6658 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6659 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6660 if (old == -1) {
6661 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6662 }
6663 }
6664 state->mCommand = FastCaptureState::READ_WRITE;
6665#if 0 // FIXME
6666 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006667 FastThreadDumpState::kSamplingNforLowRamDevice :
6668 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006669#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006670 didModify = true;
6671 }
6672 audio_track_cblk_t *cblkOld = state->mCblk;
6673 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6674 if (cblkNew != cblkOld) {
6675 state->mCblk = cblkNew;
6676 // block until acked if removing a fast track
6677 if (cblkOld != NULL) {
6678 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6679 }
6680 didModify = true;
6681 }
6682 sq->end(didModify);
6683 if (didModify) {
6684 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006685#if 0
6686 if (kUseFastCapture == FastCapture_Dynamic) {
6687 mNormalSource = mPipeSource;
6688 }
6689#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006690 }
6691 }
6692
Glenn Kasten735f45f2014-08-18 15:51:59 -07006693 // now run the fast track destructor with thread mutex unlocked
6694 fastTrackToRemove.clear();
6695
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006696 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6697 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6698 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6699 // If destination is non-contiguous, first read past the nominal end of buffer, then
6700 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006701
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006702 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006703 ssize_t framesRead;
6704
6705 // If an NBAIO source is present, use it to read the normal capture's data
6706 if (mPipeSource != 0) {
6707 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006708 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006709
6710 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6711 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6712 // we immediately retry the read() to get data and prevent another overflow.
6713 for (int retries = 0; retries <= 2; ++retries) {
6714 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6715 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6716 framesToRead);
6717 if (framesRead != OVERRUN) break;
6718 }
6719
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006720 const ssize_t availableToRead = mPipeSource->availableToRead();
6721 if (availableToRead >= 0) {
6722 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6723 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6724 "more frames to read than fifo size, %zd > %zu",
6725 availableToRead, mPipeFramesP2);
6726 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6727 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6728 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6729 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006730 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6731 }
6732 if (framesRead < 0) {
6733 status_t status = (status_t) framesRead;
6734 switch (status) {
6735 case OVERRUN:
6736 ALOGW("overrun on read from pipe");
6737 framesRead = 0;
6738 break;
6739 case NEGOTIATE:
6740 ALOGE("re-negotiation is needed");
6741 framesRead = -1; // Will cause an attempt to recover.
6742 break;
6743 default:
6744 ALOGE("unknown error %d on read from pipe", status);
6745 break;
6746 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006747 }
6748 // otherwise use the HAL / AudioStreamIn directly
6749 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006750 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006751 size_t bytesRead;
6752 status_t result = mInput->stream->read(
6753 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006754 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006755 if (result < 0) {
6756 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006757 } else {
6758 framesRead = bytesRead / mFrameSize;
6759 }
6760 }
6761
Andy Hung3f0c9022016-01-15 17:49:46 -08006762 // Update server timestamp with server stats
6763 // systemTime() is optional if the hardware supports timestamps.
6764 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6765 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6766
6767 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006768 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006769 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006770 if (mStandby) {
6771 mTimestampVerifier.discontinuity();
6772 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006773 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6774 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6775 // Note: In general record buffers should tend to be empty in
6776 // a properly running pipeline.
6777 //
6778 // Also, it is not advantageous to call get_presentation_position during the read
6779 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006780
6781 mTimestampVerifier.add(mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
6782 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
6783 mSampleRate);
6784 } else {
6785 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08006786 }
6787 }
6788 // Use this to track timestamp information
6789 // ALOGD("%s", mTimestamp.toString().c_str());
6790
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006791 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006792 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006793 // Force input into standby so that it tries to recover at next read attempt
6794 inputStandBy();
6795 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006796 }
6797 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006798 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006799 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006800 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006801
Andy Hung8946a282018-04-19 20:04:56 -07006802#ifdef TEE_SINK
6803 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6804#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006805 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006806 {
6807 size_t part1 = mRsmpInFramesP2 - rear;
6808 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006809 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006810 (framesRead - part1) * mFrameSize);
6811 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006812 }
6813 rear = mRsmpInRear += framesRead;
6814
6815 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006816
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006817 // loop over each active track
6818 for (size_t i = 0; i < size; i++) {
6819 activeTrack = activeTracks[i];
6820
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006821 // skip fast tracks, as those are handled directly by FastCapture
6822 if (activeTrack->isFastTrack()) {
6823 continue;
6824 }
6825
Andy Hung73c02e42015-03-29 01:13:58 -07006826 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006827 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6828
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006829 enum {
6830 OVERRUN_UNKNOWN,
6831 OVERRUN_TRUE,
6832 OVERRUN_FALSE
6833 } overrun = OVERRUN_UNKNOWN;
6834
6835 // loop over getNextBuffer to handle circular sink
6836 for (;;) {
6837
6838 activeTrack->mSink.frameCount = ~0;
6839 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6840 size_t framesOut = activeTrack->mSink.frameCount;
6841 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6842
Andy Hung73c02e42015-03-29 01:13:58 -07006843 // check available frames and handle overrun conditions
6844 // if the record track isn't draining fast enough.
6845 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006846 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006847 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6848 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006849 overrun = OVERRUN_TRUE;
6850 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006851 if (framesOut == 0 || framesIn == 0) {
6852 break;
6853 }
6854
Andy Hung6770c6f2015-04-07 13:43:36 -07006855 // Don't allow framesOut to be larger than what is possible with resampling
6856 // from framesIn.
6857 // This isn't strictly necessary but helps limit buffer resizing in
6858 // RecordBufferConverter. TODO: remove when no longer needed.
6859 framesOut = min(framesOut,
6860 destinationFramesPossible(
6861 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006862
6863 if (activeTrack->isDirect()) {
6864 // No RecordBufferConverter used for compressed formats. Pass
6865 // straight from RecordThread buffer to RecordTrack buffer.
6866 AudioBufferProvider::Buffer buffer;
6867 buffer.frameCount = framesOut;
6868 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
6869 if (status == OK && buffer.frameCount != 0) {
6870 ALOGV_IF(buffer.frameCount != framesOut,
6871 "%s() read less than expected (%zu vs %zu)",
6872 __func__, buffer.frameCount, framesOut);
6873 framesOut = buffer.frameCount;
6874 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount);
6875 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
6876 } else {
6877 framesOut = 0;
6878 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
6879 __func__, status, buffer.frameCount);
6880 }
6881 } else {
6882 // process frames from the RecordThread buffer provider to the RecordTrack
6883 // buffer
6884 framesOut = activeTrack->mRecordBufferConverter->convert(
6885 activeTrack->mSink.raw,
6886 activeTrack->mResamplerBufferProvider,
6887 framesOut);
6888 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006889
6890 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6891 overrun = OVERRUN_FALSE;
6892 }
6893
6894 if (activeTrack->mFramesToDrop == 0) {
6895 if (framesOut > 0) {
6896 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006897 // Sanitize before releasing if the track has no access to the source data
6898 // An idle UID receives silence from non virtual devices until active
6899 if (activeTrack->isSilenced()) {
6900 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6901 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006902 activeTrack->releaseBuffer(&activeTrack->mSink);
6903 }
6904 } else {
6905 // FIXME could do a partial drop of framesOut
6906 if (activeTrack->mFramesToDrop > 0) {
6907 activeTrack->mFramesToDrop -= framesOut;
6908 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006909 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006910 }
6911 } else {
6912 activeTrack->mFramesToDrop += framesOut;
6913 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6914 activeTrack->mSyncStartEvent->isCancelled()) {
6915 ALOGW("Synced record %s, session %d, trigger session %d",
6916 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6917 activeTrack->sessionId(),
6918 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006919 activeTrack->mSyncStartEvent->triggerSession() :
6920 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006921 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006922 }
6923 }
6924 }
6925
6926 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006927 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006928 }
6929 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006930
6931 switch (overrun) {
6932 case OVERRUN_TRUE:
6933 // client isn't retrieving buffers fast enough
6934 if (!activeTrack->setOverflow()) {
6935 nsecs_t now = systemTime();
6936 // FIXME should lastWarning per track?
6937 if ((now - lastWarning) > kWarningThrottleNs) {
6938 ALOGW("RecordThread: buffer overflow");
6939 lastWarning = now;
6940 }
6941 }
6942 break;
6943 case OVERRUN_FALSE:
6944 activeTrack->clearOverflow();
6945 break;
6946 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006947 break;
6948 }
6949
Andy Hung3f0c9022016-01-15 17:49:46 -08006950 // update frame information and push timestamp out
6951 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006952 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006953 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6954 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006955 }
6956
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006957unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006958 // enable changes in effect chain
6959 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006960 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006961 }
6962
Glenn Kasten93e471f2013-08-19 08:40:07 -07006963 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006964
6965 {
6966 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006967 for (size_t i = 0; i < mTracks.size(); i++) {
6968 sp<RecordTrack> track = mTracks[i];
6969 track->invalidate();
6970 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006971 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006972 mStartStopCond.broadcast();
6973 }
6974
6975 releaseWakeLock();
6976
6977 ALOGV("RecordThread %p exiting", this);
6978 return false;
6979}
6980
Glenn Kasten93e471f2013-08-19 08:40:07 -07006981void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006982{
6983 if (!mStandby) {
6984 inputStandBy();
6985 mStandby = true;
6986 }
6987}
6988
6989void AudioFlinger::RecordThread::inputStandBy()
6990{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006991 // Idle the fast capture if it's currently running
6992 if (mFastCapture != 0) {
6993 FastCaptureStateQueue *sq = mFastCapture->sq();
6994 FastCaptureState *state = sq->begin();
6995 if (!(state->mCommand & FastCaptureState::IDLE)) {
6996 state->mCommand = FastCaptureState::COLD_IDLE;
6997 state->mColdFutexAddr = &mFastCaptureFutex;
6998 state->mColdGen++;
6999 mFastCaptureFutex = 0;
7000 sq->end();
7001 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7002 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7003#if 0
7004 if (kUseFastCapture == FastCapture_Dynamic) {
7005 // FIXME
7006 }
7007#endif
7008#ifdef AUDIO_WATCHDOG
7009 // FIXME
7010#endif
7011 } else {
7012 sq->end(false /*didModify*/);
7013 }
7014 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007015 status_t result = mInput->stream->standby();
7016 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007017
7018 // If going into standby, flush the pipe source.
7019 if (mPipeSource.get() != nullptr) {
7020 const ssize_t flushed = mPipeSource->flush();
7021 if (flushed > 0) {
7022 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7023 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7024 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7025 }
7026 }
Eric Laurent81784c32012-11-19 14:55:58 -08007027}
7028
Glenn Kasten05997e22014-03-13 15:08:33 -07007029// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007030sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007031 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007032 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007033 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007034 audio_format_t format,
7035 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007036 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007037 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007038 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007039 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007040 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007041 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007042 status_t *status,
7043 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007044{
Glenn Kasten74935e42013-12-19 08:56:45 -08007045 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007046 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007047 sp<RecordTrack> track;
7048 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007049 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007050 audio_input_flags_t requestedFlags = *flags;
7051 uint32_t sampleRate;
7052
7053 lStatus = initCheck();
7054 if (lStatus != NO_ERROR) {
7055 ALOGE("createRecordTrack_l() audio driver not initialized");
7056 goto Exit;
7057 }
7058
7059 if (*pSampleRate == 0) {
7060 *pSampleRate = mSampleRate;
7061 }
7062 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007063
7064 // special case for FAST flag considered OK if fast capture is present
7065 if (hasFastCapture()) {
7066 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7067 }
7068
Eric Laurentf14db3c2017-12-08 14:20:36 -08007069 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007070 if ((*flags & inputFlags) != *flags) {
7071 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7072 " input flags (%08x)",
7073 *flags, inputFlags);
7074 *flags = (audio_input_flags_t)(*flags & inputFlags);
7075 }
Eric Laurent81784c32012-11-19 14:55:58 -08007076
Glenn Kasten90e58b12013-07-31 16:16:02 -07007077 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007078 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007079 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007080 // we formerly checked for a callback handler (non-0 tid),
7081 // but that is no longer required for TRANSFER_OBTAIN mode
7082 //
Glenn Kasten74105912014-07-03 12:28:53 -07007083 // frame count is not specified, or is exactly the pipe depth
7084 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007085 // PCM data
7086 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007087 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007088 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007089 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007090 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007091 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007092 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007093 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007094 hasFastCapture() &&
7095 // there are sufficient fast track slots available
7096 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007097 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007098 // check compatibility with audio effects.
7099 Mutex::Autolock _l(mLock);
7100 // Do not accept FAST flag if the session has software effects
7101 sp<EffectChain> chain = getEffectChain_l(sessionId);
7102 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007103 audio_input_flags_t old = *flags;
7104 chain->checkInputFlagCompatibility(flags);
7105 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007106 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7107 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007108 }
7109 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007110 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007111 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7112 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007113 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007114 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7115 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007116 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007117 this, frameCount, mFrameCount, mPipeFramesP2,
7118 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007119 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007120 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007121 }
7122 }
7123
Eric Laurentf14db3c2017-12-08 14:20:36 -08007124 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7125 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7126 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7127 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7128 lStatus = BAD_TYPE;
7129 goto Exit;
7130 }
7131
Glenn Kasten74105912014-07-03 12:28:53 -07007132 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007133 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007134 // fast track: frame count is exactly the pipe depth
7135 frameCount = mPipeFramesP2;
7136 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007137 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007138 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007139 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7140 // or 20 ms if there is a fast capture
7141 // TODO This could be a roundupRatio inline, and const
7142 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7143 * sampleRate + mSampleRate - 1) / mSampleRate;
7144 // minimum number of notification periods is at least kMinNotifications,
7145 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7146 static const size_t kMinNotifications = 3;
7147 static const uint32_t kMinMs = 30;
7148 // TODO This could be a roundupRatio inline
7149 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7150 // TODO This could be a roundupRatio inline
7151 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7152 maxNotificationFrames;
7153 const size_t minFrameCount = maxNotificationFrames *
7154 max(kMinNotifications, minNotificationsByMs);
7155 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007156 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7157 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007158 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007159 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007160 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007161 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007162
7163 { // scope for mLock
7164 Mutex::Autolock _l(mLock);
7165
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007166 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007167 format, channelMask, frameCount,
7168 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007169 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007170
Glenn Kasten03003332013-08-06 15:40:54 -07007171 lStatus = track->initCheck();
7172 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007173 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007174 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007175 goto Exit;
7176 }
7177 mTracks.add(track);
7178
Eric Laurent05067782016-06-01 18:27:28 -07007179 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007180 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7181 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7182 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007183 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007184 }
Eric Laurent81784c32012-11-19 14:55:58 -08007185 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007186
Eric Laurent81784c32012-11-19 14:55:58 -08007187 lStatus = NO_ERROR;
7188
7189Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007190 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007191 return track;
7192}
7193
7194status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7195 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007196 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007197{
7198 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7199 sp<ThreadBase> strongMe = this;
7200 status_t status = NO_ERROR;
7201
7202 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007203 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007204 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007205 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007206 triggerSession,
7207 recordTrack->sessionId(),
7208 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007209 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007210 // Sync event can be cancelled by the trigger session if the track is not in a
7211 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007212 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007213 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007214 } else {
7215 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007216 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007217 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007218 }
7219 }
7220
7221 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007222 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007223 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007224 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7225 if (recordTrack->mState == TrackBase::PAUSING) {
7226 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007227 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007228 } else {
7229 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007230 }
7231 return status;
7232 }
7233
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007234 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7235 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7236 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007237 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007238 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007239 status_t status = NO_ERROR;
7240 if (recordTrack->isExternalTrack()) {
7241 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007242 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007243 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007244 mLock.lock();
7245 // FIXME should verify that recordTrack is still in mActiveTracks
7246 if (status != NO_ERROR) {
7247 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007248 recordTrack->clearSyncStartEvent();
7249 ALOGV("RecordThread::start error %d", status);
7250 return status;
7251 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007252 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007253 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007254 // Catch up with current buffer indices if thread is already running.
7255 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7256 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7257 // see previously buffered data before it called start(), but with greater risk of overrun.
7258
Andy Hung73c02e42015-03-29 01:13:58 -07007259 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007260 if (!recordTrack->isDirect()) {
7261 // clear any converter state as new data will be discontinuous
7262 recordTrack->mRecordBufferConverter->reset();
7263 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007264 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007265 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007266 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007267 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007268 ALOGV("Record failed to start");
7269 status = BAD_VALUE;
7270 goto startError;
7271 }
Eric Laurent81784c32012-11-19 14:55:58 -08007272 return status;
7273 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007274
Eric Laurent81784c32012-11-19 14:55:58 -08007275startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007276 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007277 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007278 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007279 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007280 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007281 return status;
7282}
7283
Eric Laurent81784c32012-11-19 14:55:58 -08007284void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7285{
7286 sp<SyncEvent> strongEvent = event.promote();
7287
7288 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007289 sp<RefBase> ptr = strongEvent->cookie().promote();
7290 if (ptr != 0) {
7291 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7292 recordTrack->handleSyncStartEvent(strongEvent);
7293 }
Eric Laurent81784c32012-11-19 14:55:58 -08007294 }
7295}
7296
Glenn Kastena8356f62013-07-25 14:37:52 -07007297bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007298 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007299 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007300 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007301 return false;
7302 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007303 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007304 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007305 // signal thread to stop
7306 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007307 // do not wait for mStartStopCond if exiting
7308 if (exitPending()) {
7309 return true;
7310 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007311 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007312 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007313 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007314 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007315 ALOGV("Record stopped OK");
7316 return true;
7317 }
7318 return false;
7319}
7320
Glenn Kasten0f11b512014-01-31 16:18:54 -08007321bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007322{
7323 return false;
7324}
7325
Glenn Kasten0f11b512014-01-31 16:18:54 -08007326status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007327{
7328#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7329 if (!isValidSyncEvent(event)) {
7330 return BAD_VALUE;
7331 }
7332
Glenn Kastend848eb42016-03-08 13:42:11 -08007333 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007334 status_t ret = NAME_NOT_FOUND;
7335
7336 Mutex::Autolock _l(mLock);
7337
7338 for (size_t i = 0; i < mTracks.size(); i++) {
7339 sp<RecordTrack> track = mTracks[i];
7340 if (eventSession == track->sessionId()) {
7341 (void) track->setSyncEvent(event);
7342 ret = NO_ERROR;
7343 }
7344 }
7345 return ret;
7346#else
7347 return BAD_VALUE;
7348#endif
7349}
7350
jiabin653cc0a2018-01-17 17:54:10 -08007351status_t AudioFlinger::RecordThread::getActiveMicrophones(
7352 std::vector<media::MicrophoneInfo>* activeMicrophones)
7353{
7354 ALOGV("RecordThread::getActiveMicrophones");
7355 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007356 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7357 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007358}
7359
Kevin Rocard069c2712018-03-29 19:09:14 -07007360void AudioFlinger::RecordThread::updateMetadata_l()
7361{
7362 if (mInput == nullptr || mInput->stream == nullptr ||
7363 !mActiveTracks.readAndClearHasChanged()) {
7364 return;
7365 }
7366 StreamInHalInterface::SinkMetadata metadata;
7367 for (const sp<RecordTrack> &track : mActiveTracks) {
7368 // No track is invalid as this is called after prepareTrack_l in the same critical section
7369 metadata.tracks.push_back({
7370 .source = track->attributes().source,
7371 .gain = 1, // capture tracks do not have volumes
7372 });
7373 }
7374 mInput->stream->updateSinkMetadata(metadata);
7375}
7376
Eric Laurent81784c32012-11-19 14:55:58 -08007377// destroyTrack_l() must be called with ThreadBase::mLock held
7378void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7379{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007380 track->terminate();
7381 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007382 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007383 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007384 removeTrack_l(track);
7385 }
7386}
7387
7388void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7389{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007390 String8 result;
7391 track->appendDump(result, false /* active */);
7392 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7393
Eric Laurent81784c32012-11-19 14:55:58 -08007394 mTracks.remove(track);
7395 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007396 if (track->isFastTrack()) {
7397 ALOG_ASSERT(!mFastTrackAvail);
7398 mFastTrackAvail = true;
7399 }
Eric Laurent81784c32012-11-19 14:55:58 -08007400}
7401
7402void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7403{
7404 dumpInternals(fd, args);
7405 dumpTracks(fd, args);
7406 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007407 dprintf(fd, " Local log:\n");
7408 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007409}
7410
7411void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7412{
Glenn Kasten44182c22015-03-05 17:12:23 -08007413 dumpBase(fd, args);
7414
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007415 AudioStreamIn *input = mInput;
7416 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7417 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7418 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007419 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007420 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007421 }
Andy Hungbfa64962017-06-12 14:43:19 -07007422
7423 if (input != nullptr) {
7424 dprintf(fd, " Hal stream dump:\n");
7425 (void)input->stream->dump(fd);
7426 }
7427
Andy Hung20bd30b2018-06-01 15:39:35 -07007428 const double latencyMs = - mTimestamp.getOutputServerLatencyMs(mSampleRate);
7429 if (latencyMs != 0.) {
7430 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7431 } else {
7432 dprintf(fd, " NormalRecord latency ms: unavail\n");
7433 }
7434
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007435 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007436 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007437
Glenn Kasten2f90c512015-12-02 11:40:09 -08007438 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7439 // while we are dumping it. It may be inconsistent, but it won't mutate!
7440 // This is a large object so we place it on the heap.
7441 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan7b651152018-07-13 10:17:19 -07007442 std::unique_ptr<FastCaptureDumpState> copy(new FastCaptureDumpState(mFastCaptureDumpState));
Glenn Kasten2f90c512015-12-02 11:40:09 -08007443 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007444}
7445
Glenn Kasten0f11b512014-01-31 16:18:54 -08007446void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007447{
Eric Laurent81784c32012-11-19 14:55:58 -08007448 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007449 size_t numtracks = mTracks.size();
7450 size_t numactive = mActiveTracks.size();
7451 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007452 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007453 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007454 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007455 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007456 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007457 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007458 for (size_t i = 0; i < numtracks ; ++i) {
7459 sp<RecordTrack> track = mTracks[i];
7460 if (track != 0) {
7461 bool active = mActiveTracks.indexOf(track) >= 0;
7462 if (active) {
7463 numactiveseen++;
7464 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007465 result.append(prefix);
7466 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007467 }
Eric Laurent81784c32012-11-19 14:55:58 -08007468 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007469 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007470 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007471 }
7472
Marco Nelissenb2208842014-02-07 14:00:50 -08007473 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007474 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007475 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007476 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007477 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007478 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007479 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007480 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007481 result.append(prefix);
7482 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007483 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007484 }
Eric Laurent81784c32012-11-19 14:55:58 -08007485
7486 }
7487 write(fd, result.string(), result.size());
7488}
7489
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007490void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7491{
7492 Mutex::Autolock _l(mLock);
7493 for (size_t i = 0; i < mTracks.size() ; i++) {
7494 sp<RecordTrack> track = mTracks[i];
7495 if (track != 0 && track->uid() == uid) {
7496 track->setSilenced(silenced);
7497 }
7498 }
7499}
Andy Hung73c02e42015-03-29 01:13:58 -07007500
7501void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7502{
7503 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7504 RecordThread *recordThread = (RecordThread *) threadBase.get();
7505 mRsmpInFront = recordThread->mRsmpInRear;
7506 mRsmpInUnrel = 0;
7507}
7508
7509void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7510 size_t *framesAvailable, bool *hasOverrun)
7511{
7512 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7513 RecordThread *recordThread = (RecordThread *) threadBase.get();
7514 const int32_t rear = recordThread->mRsmpInRear;
7515 const int32_t front = mRsmpInFront;
7516 const ssize_t filled = rear - front;
7517
7518 size_t framesIn;
7519 bool overrun = false;
7520 if (filled < 0) {
7521 // should not happen, but treat like a massive overrun and re-sync
7522 framesIn = 0;
7523 mRsmpInFront = rear;
7524 overrun = true;
7525 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7526 framesIn = (size_t) filled;
7527 } else {
7528 // client is not keeping up with server, but give it latest data
7529 framesIn = recordThread->mRsmpInFrames;
7530 mRsmpInFront = /* front = */ rear - framesIn;
7531 overrun = true;
7532 }
7533 if (framesAvailable != NULL) {
7534 *framesAvailable = framesIn;
7535 }
7536 if (hasOverrun != NULL) {
7537 *hasOverrun = overrun;
7538 }
7539}
7540
Eric Laurent81784c32012-11-19 14:55:58 -08007541// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007542status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007543 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007544{
Andy Hung73c02e42015-03-29 01:13:58 -07007545 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007546 if (threadBase == 0) {
7547 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007548 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007549 return NOT_ENOUGH_DATA;
7550 }
7551 RecordThread *recordThread = (RecordThread *) threadBase.get();
7552 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007553 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007554 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007555 // FIXME should not be P2 (don't want to increase latency)
7556 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007557 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007558 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007559 front &= recordThread->mRsmpInFramesP2 - 1;
7560 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007561 if (part1 > (size_t) filled) {
7562 part1 = filled;
7563 }
7564 size_t ask = buffer->frameCount;
7565 ALOG_ASSERT(ask > 0);
7566 if (part1 > ask) {
7567 part1 = ask;
7568 }
7569 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007570 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007571 buffer->raw = NULL;
7572 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007573 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007574 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007575 }
7576
Andy Hung57446612015-04-19 23:56:46 -07007577 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007578 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007579 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007580 return NO_ERROR;
7581}
7582
7583// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007584void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7585 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007586{
Glenn Kasten85948432013-08-19 12:09:05 -07007587 size_t stepCount = buffer->frameCount;
7588 if (stepCount == 0) {
7589 return;
7590 }
Andy Hung73c02e42015-03-29 01:13:58 -07007591 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7592 mRsmpInUnrel -= stepCount;
7593 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007594 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007595 buffer->frameCount = 0;
7596}
7597
Eric Laurentd8365c52017-07-16 15:27:05 -07007598void AudioFlinger::RecordThread::checkBtNrec()
7599{
7600 Mutex::Autolock _l(mLock);
7601 checkBtNrec_l();
7602}
7603
7604void AudioFlinger::RecordThread::checkBtNrec_l()
7605{
7606 // disable AEC and NS if the device is a BT SCO headset supporting those
7607 // pre processings
7608 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7609 mAudioFlinger->btNrecIsOff();
7610 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7611 for (size_t i = 0; i < mEffectChains.size(); i++) {
7612 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7613 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7614 }
7615 }
7616}
7617
Andy Hung97a893e2015-03-29 01:03:07 -07007618
Eric Laurent10351942014-05-08 18:49:52 -07007619bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7620 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007621{
7622 bool reconfig = false;
7623
Eric Laurent10351942014-05-08 18:49:52 -07007624 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007625
Eric Laurent10351942014-05-08 18:49:52 -07007626 audio_format_t reqFormat = mFormat;
7627 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007628 // 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 -07007629 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7630
7631 AudioParameter param = AudioParameter(keyValuePair);
7632 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007633
7634 // scope for AutoPark extends to end of method
7635 AutoPark<FastCapture> park(mFastCapture);
7636
Eric Laurent10351942014-05-08 18:49:52 -07007637 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7638 // channel count change can be requested. Do we mandate the first client defines the
7639 // HAL sampling rate and channel count or do we allow changes on the fly?
7640 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7641 samplingRate = value;
7642 reconfig = true;
7643 }
7644 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007645 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007646 status = BAD_VALUE;
7647 } else {
7648 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007649 reconfig = true;
7650 }
Eric Laurent10351942014-05-08 18:49:52 -07007651 }
7652 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7653 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007654 if (!audio_is_input_channel(mask) ||
7655 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007656 status = BAD_VALUE;
7657 } else {
7658 channelMask = mask;
7659 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007660 }
Eric Laurent10351942014-05-08 18:49:52 -07007661 }
7662 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7663 // do not accept frame count changes if tracks are open as the track buffer
7664 // size depends on frame count and correct behavior would not be guaranteed
7665 // if frame count is changed after track creation
7666 if (mActiveTracks.size() > 0) {
7667 status = INVALID_OPERATION;
7668 } else {
7669 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007670 }
Eric Laurent10351942014-05-08 18:49:52 -07007671 }
7672 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7673 // forward device change to effects that have requested to be
7674 // aware of attached audio device.
7675 for (size_t i = 0; i < mEffectChains.size(); i++) {
7676 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007677 }
Eric Laurent81784c32012-11-19 14:55:58 -08007678
Eric Laurent10351942014-05-08 18:49:52 -07007679 // store input device and output device but do not forward output device to audio HAL.
7680 // Note that status is ignored by the caller for output device
7681 // (see AudioFlinger::setParameters()
7682 if (audio_is_output_devices(value)) {
7683 mOutDevice = value;
7684 status = BAD_VALUE;
7685 } else {
7686 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007687 if (value != AUDIO_DEVICE_NONE) {
7688 mPrevInDevice = value;
7689 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007690 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007691 }
Eric Laurent10351942014-05-08 18:49:52 -07007692 }
7693 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7694 mAudioSource != (audio_source_t)value) {
7695 // forward device change to effects that have requested to be
7696 // aware of attached audio device.
7697 for (size_t i = 0; i < mEffectChains.size(); i++) {
7698 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007699 }
Eric Laurent10351942014-05-08 18:49:52 -07007700 mAudioSource = (audio_source_t)value;
7701 }
Glenn Kastene198c362013-08-13 09:13:36 -07007702
Eric Laurent10351942014-05-08 18:49:52 -07007703 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007704 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007705 if (status == INVALID_OPERATION) {
7706 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007707 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007708 }
7709 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007710 if (status == BAD_VALUE) {
7711 uint32_t sRate;
7712 audio_channel_mask_t channelMask;
7713 audio_format_t format;
7714 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7715 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7716 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7717 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7718 status = NO_ERROR;
7719 }
Eric Laurent81784c32012-11-19 14:55:58 -08007720 }
Eric Laurent10351942014-05-08 18:49:52 -07007721 if (status == NO_ERROR) {
7722 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007723 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007724 }
7725 }
Eric Laurent81784c32012-11-19 14:55:58 -08007726 }
Eric Laurent10351942014-05-08 18:49:52 -07007727
Eric Laurent81784c32012-11-19 14:55:58 -08007728 return reconfig;
7729}
7730
7731String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7732{
Eric Laurent81784c32012-11-19 14:55:58 -08007733 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007734 if (initCheck() == NO_ERROR) {
7735 String8 out_s8;
7736 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7737 return out_s8;
7738 }
Eric Laurent81784c32012-11-19 14:55:58 -08007739 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007740 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007741}
7742
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007743void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007744 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7745
7746 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007747
7748 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007749 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007750 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007751 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007752 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007753 desc->mChannelMask = mChannelMask;
7754 desc->mSamplingRate = mSampleRate;
7755 desc->mFormat = mFormat;
7756 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007757 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007758 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007759 break;
7760
Eric Laurent73e26b62015-04-27 16:55:58 -07007761 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007762 default:
7763 break;
7764 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007765 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007766}
7767
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007768void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007769{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007770 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7771 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007772 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007773 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007774 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007775 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7776 result = mInput->stream->getFrameSize(&mFrameSize);
7777 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7778 result = mInput->stream->getBufferSize(&mBufferSize);
7779 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007780 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007781 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7782 "mBufferSize=%lld, mFrameCount=%lld",
7783 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7784 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007785 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007786 // 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 -07007787 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007788 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007789 // A larger value should allow more old data to be read after a track calls start(),
7790 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007791 //
7792 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007793 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007794 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007795 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007796 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007797
7798 // TODO optimize audio capture buffer sizes ...
7799 // Here we calculate the size of the sliding buffer used as a source
7800 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7801 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7802 // be better to have it derived from the pipe depth in the long term.
7803 // The current value is higher than necessary. However it should not add to latency.
7804
Glenn Kasten85948432013-08-19 12:09:05 -07007805 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007806 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7807 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007808 // if posix_memalign fails, will segv here.
7809 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007810
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007811 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7812 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007813}
7814
Glenn Kasten5f972c02014-01-13 09:59:31 -08007815uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007816{
7817 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007818 uint32_t result;
7819 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7820 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007821 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007822 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007823}
7824
Eric Laurent4c415062016-06-17 16:14:16 -07007825// hasAudioSession_l() must be called with ThreadBase::mLock held
7826uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007827{
Eric Laurent81784c32012-11-19 14:55:58 -08007828 uint32_t result = 0;
7829 if (getEffectChain_l(sessionId) != 0) {
7830 result = EFFECT_SESSION;
7831 }
7832
7833 for (size_t i = 0; i < mTracks.size(); ++i) {
7834 if (sessionId == mTracks[i]->sessionId()) {
7835 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007836 if (mTracks[i]->isFastTrack()) {
7837 result |= FAST_SESSION;
7838 }
Eric Laurent81784c32012-11-19 14:55:58 -08007839 break;
7840 }
7841 }
7842
7843 return result;
7844}
7845
Glenn Kastend848eb42016-03-08 13:42:11 -08007846KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007847{
Glenn Kastend848eb42016-03-08 13:42:11 -08007848 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007849 Mutex::Autolock _l(mLock);
7850 for (size_t j = 0; j < mTracks.size(); ++j) {
7851 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007852 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007853 if (ids.indexOfKey(sessionId) < 0) {
7854 ids.add(sessionId, true);
7855 }
7856 }
7857 return ids;
7858}
7859
7860AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7861{
7862 Mutex::Autolock _l(mLock);
7863 AudioStreamIn *input = mInput;
7864 mInput = NULL;
7865 return input;
7866}
7867
7868// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007869sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007870{
7871 if (mInput == NULL) {
7872 return NULL;
7873 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007874 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007875}
7876
7877status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7878{
7879 // only one chain per input thread
7880 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007881 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007882 return INVALID_OPERATION;
7883 }
7884 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007885 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007886 chain->setInBuffer(NULL);
7887 chain->setOutBuffer(NULL);
7888
7889 checkSuspendOnAddEffectChain_l(chain);
7890
Eric Laurent1b928682014-10-02 19:41:47 -07007891 // make sure enabled pre processing effects state is communicated to the HAL as we
7892 // just moved them to a new input stream.
7893 chain->syncHalEffectsState();
7894
Eric Laurent81784c32012-11-19 14:55:58 -08007895 mEffectChains.add(chain);
7896
7897 return NO_ERROR;
7898}
7899
7900size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7901{
7902 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7903 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007904 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007905 chain.get(), mEffectChains.size(), this);
7906 if (mEffectChains.size() == 1) {
7907 mEffectChains.removeAt(0);
7908 }
7909 return 0;
7910}
7911
Eric Laurent1c333e22014-05-20 10:48:17 -07007912status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7913 audio_patch_handle_t *handle)
7914{
7915 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007916
7917 // store new device and send to effects
7918 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007919 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007920 for (size_t i = 0; i < mEffectChains.size(); i++) {
7921 mEffectChains[i]->setDevice_l(mInDevice);
7922 }
7923
Eric Laurentd8365c52017-07-16 15:27:05 -07007924 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007925
7926 // store new source and send to effects
7927 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7928 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007929 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007930 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007931 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007932 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007933
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007934 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007935 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7936 status = hwDevice->createAudioPatch(patch->num_sources,
7937 patch->sources,
7938 patch->num_sinks,
7939 patch->sinks,
7940 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007941 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007942 char *address;
7943 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7944 address = audio_device_address_to_parameter(
7945 patch->sources[0].ext.device.type,
7946 patch->sources[0].ext.device.address);
7947 } else {
7948 address = (char *)calloc(1, 1);
7949 }
7950 AudioParameter param = AudioParameter(String8(address));
7951 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007952 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007953 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007954 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007955 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007956 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007957 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007958 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007959
Eric Laurente8726fe2015-06-26 09:39:24 -07007960 if (mInDevice != mPrevInDevice) {
7961 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7962 mPrevInDevice = mInDevice;
7963 }
Eric Laurent296fb132015-05-01 11:38:42 -07007964
Eric Laurent1c333e22014-05-20 10:48:17 -07007965 return status;
7966}
7967
7968status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7969{
7970 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007971
7972 mInDevice = AUDIO_DEVICE_NONE;
7973
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007974 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007975 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7976 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007977 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007978 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007979 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007980 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007981 }
7982 return status;
7983}
7984
Mikhail Naganov444ecc32018-05-01 17:40:05 -07007985void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07007986{
7987 Mutex::Autolock _l(mLock);
7988 mTracks.add(record);
7989}
7990
Mikhail Naganov444ecc32018-05-01 17:40:05 -07007991void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07007992{
7993 Mutex::Autolock _l(mLock);
7994 destroyTrack_l(record);
7995}
7996
Mikhail Naganovdc769682018-05-04 15:34:08 -07007997void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07007998{
Mikhail Naganovdc769682018-05-04 15:34:08 -07007999 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008000 config->role = AUDIO_PORT_ROLE_SINK;
8001 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8002 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008003 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8004 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8005 config->flags.input = mInput->flags;
8006 }
Eric Laurent83b88082014-06-20 18:31:16 -07008007}
Eric Laurent1c333e22014-05-20 10:48:17 -07008008
Eric Laurent6acd1d42017-01-04 14:23:29 -08008009// ----------------------------------------------------------------------------
8010// Mmap
8011// ----------------------------------------------------------------------------
8012
8013AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8014 : mThread(thread)
8015{
Phil Burk9fabbf82017-08-03 12:02:00 -07008016 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008017}
8018
8019AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8020{
Phil Burk9fabbf82017-08-03 12:02:00 -07008021 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008022}
8023
8024status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8025 struct audio_mmap_buffer_info *info)
8026{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008027 return mThread->createMmapBuffer(minSizeFrames, info);
8028}
8029
8030status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8031{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008032 return mThread->getMmapPosition(position);
8033}
8034
Eric Laurenta54f1282017-07-01 19:39:32 -07008035status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008036 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008037
8038{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008039 return mThread->start(client, handle);
8040}
8041
8042status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8043{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008044 return mThread->stop(handle);
8045}
8046
Eric Laurent18b57012017-02-13 16:23:52 -08008047status_t AudioFlinger::MmapThreadHandle::standby()
8048{
Eric Laurent18b57012017-02-13 16:23:52 -08008049 return mThread->standby();
8050}
8051
Eric Laurent6acd1d42017-01-04 14:23:29 -08008052
8053AudioFlinger::MmapThread::MmapThread(
8054 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8055 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8056 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8057 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008058 mSessionId(AUDIO_SESSION_NONE),
8059 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008060 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008061 mActiveTracks(&this->mLocalLog),
8062 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8063 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008064{
Eric Laurent18b57012017-02-13 16:23:52 -08008065 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008066 readHalParameters_l();
8067}
8068
8069AudioFlinger::MmapThread::~MmapThread()
8070{
Eric Laurent18b57012017-02-13 16:23:52 -08008071 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008072}
8073
8074void AudioFlinger::MmapThread::onFirstRef()
8075{
8076 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8077}
8078
8079void AudioFlinger::MmapThread::disconnect()
8080{
Eric Laurent331679c2018-04-16 17:03:16 -07008081 ActiveTracks<MmapTrack> activeTracks;
8082 {
8083 Mutex::Autolock _l(mLock);
8084 for (const sp<MmapTrack> &t : mActiveTracks) {
8085 activeTracks.add(t);
8086 }
8087 }
8088 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008089 stop(t->portId());
8090 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008091 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008092 if (isOutput()) {
8093 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
8094 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008095 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008096 }
8097}
8098
8099
8100void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8101 audio_stream_type_t streamType __unused,
8102 audio_session_t sessionId,
8103 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008104 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008105 audio_port_handle_t portId)
8106{
8107 mAttr = *attr;
8108 mSessionId = sessionId;
8109 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008110 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008111 mPortId = portId;
8112}
8113
8114status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8115 struct audio_mmap_buffer_info *info)
8116{
8117 if (mHalStream == 0) {
8118 return NO_INIT;
8119 }
Eric Laurent18b57012017-02-13 16:23:52 -08008120 mStandby = true;
8121 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008122 return mHalStream->createMmapBuffer(minSizeFrames, info);
8123}
8124
8125status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8126{
8127 if (mHalStream == 0) {
8128 return NO_INIT;
8129 }
8130 return mHalStream->getMmapPosition(position);
8131}
8132
Eric Laurent331679c2018-04-16 17:03:16 -07008133status_t AudioFlinger::MmapThread::exitStandby()
8134{
8135 status_t ret = mHalStream->start();
8136 if (ret != NO_ERROR) {
8137 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8138 return ret;
8139 }
8140 mStandby = false;
8141 return NO_ERROR;
8142}
8143
Eric Laurenta54f1282017-07-01 19:39:32 -07008144status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008145 audio_port_handle_t *handle)
8146{
Eric Laurenta54f1282017-07-01 19:39:32 -07008147 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8148 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008149 if (mHalStream == 0) {
8150 return NO_INIT;
8151 }
8152
8153 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008154
Eric Laurenta54f1282017-07-01 19:39:32 -07008155 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008156 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008157 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008158 }
8159
8160 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8161
8162 audio_io_handle_t io = mId;
8163 if (isOutput()) {
8164 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8165 config.sample_rate = mSampleRate;
8166 config.channel_mask = mChannelMask;
8167 config.format = mFormat;
8168 audio_stream_type_t stream = streamType();
8169 audio_output_flags_t flags =
8170 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008171 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008172 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8173 mSessionId,
8174 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008175 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008176 client.clientUid,
8177 &config,
8178 flags,
8179 &deviceId,
8180 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008181 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008182 audio_config_base_t config;
8183 config.sample_rate = mSampleRate;
8184 config.channel_mask = mChannelMask;
8185 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008186 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008187 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8188 mSessionId,
8189 client.clientPid,
8190 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008191 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008192 &config,
8193 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8194 &deviceId,
8195 &portId);
8196 }
8197 // APM should not chose a different input or output stream for the same set of attributes
8198 // and audo configuration
8199 if (ret != NO_ERROR || io != mId) {
8200 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8201 __FUNCTION__, ret, io, mId);
8202 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008203 }
8204
Eric Laurent331679c2018-04-16 17:03:16 -07008205 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008206 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008207 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008208 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008209 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008210 }
8211
Eric Laurent331679c2018-04-16 17:03:16 -07008212 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008213 // abort if start is rejected by audio policy manager
8214 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008215 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008216 if (mActiveTracks.size() != 0) {
Eric Laurent331679c2018-04-16 17:03:16 -07008217 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008218 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008219 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008220 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008221 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008222 }
Eric Laurent331679c2018-04-16 17:03:16 -07008223 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008224 } else {
8225 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008226 }
8227 return PERMISSION_DENIED;
8228 }
8229
Eric Laurent67f97292018-04-20 18:05:41 -07008230 if (isOutput()) {
8231 // force volume update when a new track is added
8232 mHalVolFloat = -1.0f;
8233 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008234 for (const sp<MmapTrack> &track : mActiveTracks) {
8235 if (track->isSilenced_l() && track->uid() != client.clientUid)
8236 track->invalidate();
8237 }
8238 }
8239
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008240 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8241 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008242 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008243
Eric Laurent331679c2018-04-16 17:03:16 -07008244 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008245 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008246 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008247 if (chain != 0) {
8248 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8249 chain->incTrackCnt();
8250 chain->incActiveTrackCnt();
8251 }
8252
8253 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008254 broadcast_l();
8255
Eric Laurenta54f1282017-07-01 19:39:32 -07008256 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008257
8258 return NO_ERROR;
8259}
8260
8261status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8262{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008263 ALOGV("%s handle %d", __FUNCTION__, handle);
8264
8265 if (mHalStream == 0) {
8266 return NO_INIT;
8267 }
8268
Eric Laurenta54f1282017-07-01 19:39:32 -07008269 if (handle == mPortId) {
8270 mHalStream->stop();
8271 return NO_ERROR;
8272 }
8273
Eric Laurent331679c2018-04-16 17:03:16 -07008274 Mutex::Autolock _l(mLock);
8275
Eric Laurent6acd1d42017-01-04 14:23:29 -08008276 sp<MmapTrack> track;
8277 for (const sp<MmapTrack> &t : mActiveTracks) {
8278 if (handle == t->portId()) {
8279 track = t;
8280 break;
8281 }
8282 }
8283 if (track == 0) {
8284 return BAD_VALUE;
8285 }
8286
8287 mActiveTracks.remove(track);
8288
Eric Laurent331679c2018-04-16 17:03:16 -07008289 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008290 if (isOutput()) {
8291 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07008292 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008293 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008294 AudioSystem::stopInput(track->portId());
8295 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008296 }
Eric Laurent331679c2018-04-16 17:03:16 -07008297 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008298
8299 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8300 if (chain != 0) {
8301 chain->decActiveTrackCnt();
8302 chain->decTrackCnt();
8303 }
8304
8305 broadcast_l();
8306
Eric Laurent6acd1d42017-01-04 14:23:29 -08008307 return NO_ERROR;
8308}
8309
Eric Laurent18b57012017-02-13 16:23:52 -08008310status_t AudioFlinger::MmapThread::standby()
8311{
8312 ALOGV("%s", __FUNCTION__);
8313
8314 if (mHalStream == 0) {
8315 return NO_INIT;
8316 }
8317 if (mActiveTracks.size() != 0) {
8318 return INVALID_OPERATION;
8319 }
8320 mHalStream->standby();
8321 mStandby = true;
8322 releaseWakeLock();
8323 return NO_ERROR;
8324}
8325
Eric Laurent6acd1d42017-01-04 14:23:29 -08008326
8327void AudioFlinger::MmapThread::readHalParameters_l()
8328{
8329 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8330 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8331 mFormat = mHALFormat;
8332 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8333 result = mHalStream->getFrameSize(&mFrameSize);
8334 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8335 result = mHalStream->getBufferSize(&mBufferSize);
8336 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8337 mFrameCount = mBufferSize / mFrameSize;
8338}
8339
8340bool AudioFlinger::MmapThread::threadLoop()
8341{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008342 checkSilentMode_l();
8343
8344 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8345
8346 while (!exitPending())
8347 {
8348 Mutex::Autolock _l(mLock);
8349 Vector< sp<EffectChain> > effectChains;
8350
8351 if (mSignalPending) {
8352 // A signal was raised while we were unlocked
8353 mSignalPending = false;
8354 } else {
8355 if (mConfigEvents.isEmpty()) {
8356 // we're about to wait, flush the binder command buffer
8357 IPCThreadState::self()->flushCommands();
8358
8359 if (exitPending()) {
8360 break;
8361 }
8362
Eric Laurent6acd1d42017-01-04 14:23:29 -08008363 // wait until we have something to do...
8364 ALOGV("%s going to sleep", myName.string());
8365 mWaitWorkCV.wait(mLock);
8366 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008367
8368 checkSilentMode_l();
8369
8370 continue;
8371 }
8372 }
8373
8374 processConfigEvents_l();
8375
8376 processVolume_l();
8377
8378 checkInvalidTracks_l();
8379
8380 mActiveTracks.updatePowerState(this);
8381
Kevin Rocard069c2712018-03-29 19:09:14 -07008382 updateMetadata_l();
8383
Eric Laurent6acd1d42017-01-04 14:23:29 -08008384 lockEffectChains_l(effectChains);
8385 for (size_t i = 0; i < effectChains.size(); i ++) {
8386 effectChains[i]->process_l();
8387 }
8388 // enable changes in effect chain
8389 unlockEffectChains(effectChains);
8390 // Effect chains will be actually deleted here if they were removed from
8391 // mEffectChains list during mixing or effects processing
8392 }
8393
8394 threadLoop_exit();
8395
8396 if (!mStandby) {
8397 threadLoop_standby();
8398 mStandby = true;
8399 }
8400
Eric Laurent6acd1d42017-01-04 14:23:29 -08008401 ALOGV("Thread %p type %d exiting", this, mType);
8402 return false;
8403}
8404
8405// checkForNewParameter_l() must be called with ThreadBase::mLock held
8406bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8407 status_t& status)
8408{
8409 AudioParameter param = AudioParameter(keyValuePair);
8410 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008411 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008412 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008413 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008414 // forward device change to effects that have requested to be
8415 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008416 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008417 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008418 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008419 }
8420 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008421 if (audio_is_output_devices(device)) {
8422 mOutDevice = device;
8423 if (!isOutput()) {
8424 sendToHal = false;
8425 }
8426 } else {
8427 mInDevice = device;
8428 if (device != AUDIO_DEVICE_NONE) {
8429 mPrevInDevice = value;
8430 }
8431 // TODO: implement and call checkBtNrec_l();
8432 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008433 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008434 if (sendToHal) {
8435 status = mHalStream->setParameters(keyValuePair);
8436 } else {
8437 status = NO_ERROR;
8438 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008439
8440 return false;
8441}
8442
8443String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8444{
8445 Mutex::Autolock _l(mLock);
8446 String8 out_s8;
8447 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8448 return out_s8;
8449 }
8450 return String8();
8451}
8452
8453void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8454 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8455
8456 desc->mIoHandle = mId;
8457
8458 switch (event) {
8459 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008460 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008461 case AUDIO_INPUT_CONFIG_CHANGED:
8462 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008463 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008464 case AUDIO_OUTPUT_CONFIG_CHANGED:
8465 desc->mPatch = mPatch;
8466 desc->mChannelMask = mChannelMask;
8467 desc->mSamplingRate = mSampleRate;
8468 desc->mFormat = mFormat;
8469 desc->mFrameCount = mFrameCount;
8470 desc->mFrameCountHAL = mFrameCount;
8471 desc->mLatency = 0;
8472 break;
8473
8474 case AUDIO_INPUT_CLOSED:
8475 case AUDIO_OUTPUT_CLOSED:
8476 default:
8477 break;
8478 }
8479 mAudioFlinger->ioConfigChanged(event, desc, pid);
8480}
8481
8482status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8483 audio_patch_handle_t *handle)
8484{
8485 status_t status = NO_ERROR;
8486
8487 // store new device and send to effects
8488 audio_devices_t type = AUDIO_DEVICE_NONE;
8489 audio_port_handle_t deviceId;
8490 if (isOutput()) {
8491 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8492 type |= patch->sinks[i].ext.device.type;
8493 }
8494 deviceId = patch->sinks[0].id;
8495 } else {
8496 type = patch->sources[0].ext.device.type;
8497 deviceId = patch->sources[0].id;
8498 }
8499
8500 for (size_t i = 0; i < mEffectChains.size(); i++) {
8501 mEffectChains[i]->setDevice_l(type);
8502 }
8503
8504 if (isOutput()) {
8505 mOutDevice = type;
8506 } else {
8507 mInDevice = type;
8508 // store new source and send to effects
8509 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8510 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8511 for (size_t i = 0; i < mEffectChains.size(); i++) {
8512 mEffectChains[i]->setAudioSource_l(mAudioSource);
8513 }
8514 }
8515 }
8516
8517 if (mAudioHwDev->supportsAudioPatches()) {
8518 status = mHalDevice->createAudioPatch(patch->num_sources,
8519 patch->sources,
8520 patch->num_sinks,
8521 patch->sinks,
8522 handle);
8523 } else {
8524 char *address;
8525 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8526 //FIXME: we only support address on first sink with HAL version < 3.0
8527 address = audio_device_address_to_parameter(
8528 patch->sinks[0].ext.device.type,
8529 patch->sinks[0].ext.device.address);
8530 } else {
8531 address = (char *)calloc(1, 1);
8532 }
8533 AudioParameter param = AudioParameter(String8(address));
8534 free(address);
8535 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8536 if (!isOutput()) {
8537 param.addInt(String8(AudioParameter::keyInputSource),
8538 (int)patch->sinks[0].ext.mix.usecase.source);
8539 }
8540 status = mHalStream->setParameters(param.toString());
8541 *handle = AUDIO_PATCH_HANDLE_NONE;
8542 }
8543
8544 if (isOutput() && mPrevOutDevice != mOutDevice) {
8545 mPrevOutDevice = type;
8546 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008547 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008548 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008549 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008550 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008551 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008552 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008553 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008554 }
8555 if (!isOutput() && mPrevInDevice != mInDevice) {
8556 mPrevInDevice = type;
8557 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008558 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008559 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008560 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008561 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008562 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008563 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008564 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008565 }
8566 return status;
8567}
8568
8569status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8570{
8571 status_t status = NO_ERROR;
8572
8573 mInDevice = AUDIO_DEVICE_NONE;
8574
8575 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8576 supportsAudioPatches : false;
8577
8578 if (supportsAudioPatches) {
8579 status = mHalDevice->releaseAudioPatch(handle);
8580 } else {
8581 AudioParameter param;
8582 param.addInt(String8(AudioParameter::keyRouting), 0);
8583 status = mHalStream->setParameters(param.toString());
8584 }
8585 return status;
8586}
8587
Mikhail Naganovdc769682018-05-04 15:34:08 -07008588void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008589{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008590 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008591 if (isOutput()) {
8592 config->role = AUDIO_PORT_ROLE_SOURCE;
8593 config->ext.mix.hw_module = mAudioHwDev->handle();
8594 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8595 } else {
8596 config->role = AUDIO_PORT_ROLE_SINK;
8597 config->ext.mix.hw_module = mAudioHwDev->handle();
8598 config->ext.mix.usecase.source = mAudioSource;
8599 }
8600}
8601
8602status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8603{
8604 audio_session_t session = chain->sessionId();
8605
8606 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8607 // Attach all tracks with same session ID to this chain.
8608 // indicate all active tracks in the chain
8609 for (const sp<MmapTrack> &track : mActiveTracks) {
8610 if (session == track->sessionId()) {
8611 chain->incTrackCnt();
8612 chain->incActiveTrackCnt();
8613 }
8614 }
8615
8616 chain->setThread(this);
8617 chain->setInBuffer(nullptr);
8618 chain->setOutBuffer(nullptr);
8619 chain->syncHalEffectsState();
8620
8621 mEffectChains.add(chain);
8622 checkSuspendOnAddEffectChain_l(chain);
8623 return NO_ERROR;
8624}
8625
8626size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8627{
8628 audio_session_t session = chain->sessionId();
8629
8630 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8631
8632 for (size_t i = 0; i < mEffectChains.size(); i++) {
8633 if (chain == mEffectChains[i]) {
8634 mEffectChains.removeAt(i);
8635 // detach all active tracks from the chain
8636 // detach all tracks with same session ID from this chain
8637 for (const sp<MmapTrack> &track : mActiveTracks) {
8638 if (session == track->sessionId()) {
8639 chain->decActiveTrackCnt();
8640 chain->decTrackCnt();
8641 }
8642 }
8643 break;
8644 }
8645 }
8646 return mEffectChains.size();
8647}
8648
8649// hasAudioSession_l() must be called with ThreadBase::mLock held
8650uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8651{
8652 uint32_t result = 0;
8653 if (getEffectChain_l(sessionId) != 0) {
8654 result = EFFECT_SESSION;
8655 }
8656
8657 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8658 sp<MmapTrack> track = mActiveTracks[i];
8659 if (sessionId == track->sessionId()) {
8660 result |= TRACK_SESSION;
8661 if (track->isFastTrack()) {
8662 result |= FAST_SESSION;
8663 }
8664 break;
8665 }
8666 }
8667
8668 return result;
8669}
8670
8671void AudioFlinger::MmapThread::threadLoop_standby()
8672{
8673 mHalStream->standby();
8674}
8675
8676void AudioFlinger::MmapThread::threadLoop_exit()
8677{
Phil Burk7dce7282017-09-27 13:51:41 -07008678 // Do not call callback->onTearDown() because it is redundant for thread exit
8679 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008680}
8681
8682status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8683{
8684 return BAD_VALUE;
8685}
8686
8687bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8688{
8689 return false;
8690}
8691
8692status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8693 const effect_descriptor_t *desc, audio_session_t sessionId)
8694{
8695 // No global effect sessions on mmap threads
8696 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8697 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8698 desc->name, mThreadName);
8699 return BAD_VALUE;
8700 }
8701
8702 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8703 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8704 desc->name);
8705 return BAD_VALUE;
8706 }
8707 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008708 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8709 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008710 return BAD_VALUE;
8711 }
8712
8713 // Only allow effects without processing load or latency
8714 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8715 return BAD_VALUE;
8716 }
8717
8718 return NO_ERROR;
8719
8720}
8721
8722void AudioFlinger::MmapThread::checkInvalidTracks_l()
8723{
8724 for (const sp<MmapTrack> &track : mActiveTracks) {
8725 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008726 sp<MmapStreamCallback> callback = mCallback.promote();
8727 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008728 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008729 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008730 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008731 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8732 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8733 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008734 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008735 }
8736 }
8737}
8738
8739void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8740{
8741 dumpInternals(fd, args);
8742 dumpTracks(fd, args);
8743 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008744 dprintf(fd, " Local log:\n");
8745 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008746}
8747
8748void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8749{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008750 dumpBase(fd, args);
8751
8752 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8753 mAttr.content_type, mAttr.usage, mAttr.source);
8754 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8755 if (mActiveTracks.size() == 0) {
8756 dprintf(fd, " No active clients\n");
8757 }
8758}
8759
8760void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8761{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008762 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008763 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008764 dprintf(fd, " %zu Tracks\n", numtracks);
8765 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008766 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008767 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008768 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008769 for (size_t i = 0; i < numtracks ; ++i) {
8770 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008771 result.append(prefix);
8772 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008773 }
8774 } else {
8775 dprintf(fd, "\n");
8776 }
8777 write(fd, result.string(), result.size());
8778}
8779
8780AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8781 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8782 AudioHwDevice *hwDev, AudioStreamOut *output,
8783 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8784 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8785 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008786 mStreamVolume(1.0),
8787 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008788 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008789{
8790 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8791 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8792 mMasterVolume = audioFlinger->masterVolume_l();
8793 mMasterMute = audioFlinger->masterMute_l();
8794 if (mAudioHwDev) {
8795 if (mAudioHwDev->canSetMasterVolume()) {
8796 mMasterVolume = 1.0;
8797 }
8798
8799 if (mAudioHwDev->canSetMasterMute()) {
8800 mMasterMute = false;
8801 }
8802 }
8803}
8804
8805void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8806 audio_stream_type_t streamType,
8807 audio_session_t sessionId,
8808 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008809 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008810 audio_port_handle_t portId)
8811{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008812 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008813 mStreamType = streamType;
8814}
8815
8816AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8817{
8818 Mutex::Autolock _l(mLock);
8819 AudioStreamOut *output = mOutput;
8820 mOutput = NULL;
8821 return output;
8822}
8823
8824void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8825{
8826 Mutex::Autolock _l(mLock);
8827 // Don't apply master volume in SW if our HAL can do it for us.
8828 if (mAudioHwDev &&
8829 mAudioHwDev->canSetMasterVolume()) {
8830 mMasterVolume = 1.0;
8831 } else {
8832 mMasterVolume = value;
8833 }
8834}
8835
8836void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8837{
8838 Mutex::Autolock _l(mLock);
8839 // Don't apply master mute in SW if our HAL can do it for us.
8840 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8841 mMasterMute = false;
8842 } else {
8843 mMasterMute = muted;
8844 }
8845}
8846
8847void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8848{
8849 Mutex::Autolock _l(mLock);
8850 if (stream == mStreamType) {
8851 mStreamVolume = value;
8852 broadcast_l();
8853 }
8854}
8855
8856float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8857{
8858 Mutex::Autolock _l(mLock);
8859 if (stream == mStreamType) {
8860 return mStreamVolume;
8861 }
8862 return 0.0f;
8863}
8864
8865void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8866{
8867 Mutex::Autolock _l(mLock);
8868 if (stream == mStreamType) {
8869 mStreamMute= muted;
8870 broadcast_l();
8871 }
8872}
8873
8874void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8875{
8876 Mutex::Autolock _l(mLock);
8877 if (streamType == mStreamType) {
8878 for (const sp<MmapTrack> &track : mActiveTracks) {
8879 track->invalidate();
8880 }
8881 broadcast_l();
8882 }
8883}
8884
8885void AudioFlinger::MmapPlaybackThread::processVolume_l()
8886{
8887 float volume;
8888
8889 if (mMasterMute || mStreamMute) {
8890 volume = 0;
8891 } else {
8892 volume = mMasterVolume * mStreamVolume;
8893 }
8894
8895 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008896
8897 // Convert volumes from float to 8.24
8898 uint32_t vol = (uint32_t)(volume * (1 << 24));
8899
8900 // Delegate volume control to effect in track effect chain if needed
8901 // only one effect chain can be present on DirectOutputThread, so if
8902 // there is one, the track is connected to it
8903 if (!mEffectChains.isEmpty()) {
8904 mEffectChains[0]->setVolume_l(&vol, &vol);
8905 volume = (float)vol / (1 << 24);
8906 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008907 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008908 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8909 mHalVolFloat = volume; // HW volume control worked, so update value.
8910 mNoCallbackWarningCount = 0;
8911 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008912 sp<MmapStreamCallback> callback = mCallback.promote();
8913 if (callback != 0) {
8914 int channelCount;
8915 if (isOutput()) {
8916 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8917 } else {
8918 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8919 }
8920 Vector<float> values;
8921 for (int i = 0; i < channelCount; i++) {
8922 values.add(volume);
8923 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07008924 mHalVolFloat = volume; // SW volume control worked, so update value.
8925 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07008926 mLock.unlock();
8927 callback->onVolumeChanged(mChannelMask, values);
8928 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008929 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008930 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8931 ALOGW("Could not set MMAP stream volume: no volume callback!");
8932 mNoCallbackWarningCount++;
8933 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008934 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008935 }
8936 }
8937}
8938
Kevin Rocard069c2712018-03-29 19:09:14 -07008939void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
8940{
8941 if (mOutput == nullptr || mOutput->stream == nullptr ||
8942 !mActiveTracks.readAndClearHasChanged()) {
8943 return;
8944 }
8945 StreamOutHalInterface::SourceMetadata metadata;
8946 for (const sp<MmapTrack> &track : mActiveTracks) {
8947 // No track is invalid as this is called after prepareTrack_l in the same critical section
8948 metadata.tracks.push_back({
8949 .usage = track->attributes().usage,
8950 .content_type = track->attributes().content_type,
8951 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
8952 });
8953 }
8954 mOutput->stream->updateSourceMetadata(metadata);
8955}
8956
Eric Laurent6acd1d42017-01-04 14:23:29 -08008957void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8958{
8959 if (!mMasterMute) {
8960 char value[PROPERTY_VALUE_MAX];
8961 if (property_get("ro.audio.silent", value, "0") > 0) {
8962 char *endptr;
8963 unsigned long ul = strtoul(value, &endptr, 0);
8964 if (*endptr == '\0' && ul != 0) {
8965 ALOGD("Silence is golden");
8966 // The setprop command will not allow a property to be changed after
8967 // the first time it is set, so we don't have to worry about un-muting.
8968 setMasterMute_l(true);
8969 }
8970 }
8971 }
8972}
8973
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008974void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
8975{
8976 MmapThread::toAudioPortConfig(config);
8977 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
8978 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8979 config->flags.output = mOutput->flags;
8980 }
8981}
8982
Eric Laurent6acd1d42017-01-04 14:23:29 -08008983void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8984{
8985 MmapThread::dumpInternals(fd, args);
8986
Glenn Kastend3bb6452016-12-05 18:14:37 -08008987 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8988 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008989 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8990}
8991
8992AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8993 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8994 AudioHwDevice *hwDev, AudioStreamIn *input,
8995 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8996 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8997 mInput(input)
8998{
8999 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9000 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9001}
9002
Eric Laurent331679c2018-04-16 17:03:16 -07009003status_t AudioFlinger::MmapCaptureThread::exitStandby()
9004{
9005 mInput->stream->setGain(1.0f);
9006 return MmapThread::exitStandby();
9007}
9008
Eric Laurent6acd1d42017-01-04 14:23:29 -08009009AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9010{
9011 Mutex::Autolock _l(mLock);
9012 AudioStreamIn *input = mInput;
9013 mInput = NULL;
9014 return input;
9015}
Kevin Rocard069c2712018-03-29 19:09:14 -07009016
Eric Laurent331679c2018-04-16 17:03:16 -07009017
9018void AudioFlinger::MmapCaptureThread::processVolume_l()
9019{
9020 bool changed = false;
9021 bool silenced = false;
9022
9023 sp<MmapStreamCallback> callback = mCallback.promote();
9024 if (callback == 0) {
9025 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9026 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9027 mNoCallbackWarningCount++;
9028 }
9029 }
9030
9031 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9032 // track is silenced and unmute otherwise
9033 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9034 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9035 changed = true;
9036 silenced = mActiveTracks[i]->isSilenced_l();
9037 }
9038 }
9039
9040 if (changed) {
9041 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9042 }
9043}
9044
Kevin Rocard069c2712018-03-29 19:09:14 -07009045void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9046{
9047 if (mInput == nullptr || mInput->stream == nullptr ||
9048 !mActiveTracks.readAndClearHasChanged()) {
9049 return;
9050 }
9051 StreamInHalInterface::SinkMetadata metadata;
9052 for (const sp<MmapTrack> &track : mActiveTracks) {
9053 // No track is invalid as this is called after prepareTrack_l in the same critical section
9054 metadata.tracks.push_back({
9055 .source = track->attributes().source,
9056 .gain = 1, // capture tracks do not have volumes
9057 });
9058 }
9059 mInput->stream->updateSinkMetadata(metadata);
9060}
9061
Eric Laurent331679c2018-04-16 17:03:16 -07009062void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9063{
9064 Mutex::Autolock _l(mLock);
9065 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9066 if (mActiveTracks[i]->uid() == uid) {
9067 mActiveTracks[i]->setSilenced_l(silenced);
9068 broadcast_l();
9069 }
9070 }
9071}
9072
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009073void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9074{
9075 MmapThread::toAudioPortConfig(config);
9076 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9077 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9078 config->flags.input = mInput->flags;
9079 }
9080}
9081
Glenn Kasten63238ef2015-03-02 15:50:29 -08009082} // namespace android