blob: 1e411c725683c653472b176d0dd0c8978665ec2e [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
Andy Hungf3234512018-07-03 14:51:47 -0700862 || mType == DIRECT
863 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700864 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
865 }
866
Eric Laurent81784c32012-11-19 14:55:58 -0800867 if (locked) {
868 mLock.unlock();
869 }
870}
871
872void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
873{
874 const size_t SIZE = 256;
875 char buffer[SIZE];
876 String8 result;
877
Marco Nelissenb2208842014-02-07 14:00:50 -0800878 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000879 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800880 write(fd, buffer, strlen(buffer));
881
Marco Nelissenb2208842014-02-07 14:00:50 -0800882 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800883 sp<EffectChain> chain = mEffectChains[i];
884 if (chain != 0) {
885 chain->dump(fd, args);
886 }
887 }
888}
889
Andy Hungdae27702016-10-31 14:01:16 -0700890void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800891{
892 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700893 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800894}
895
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100896String16 AudioFlinger::ThreadBase::getWakeLockTag()
897{
898 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800899 case MIXER:
900 return String16("AudioMix");
901 case DIRECT:
902 return String16("AudioDirectOut");
903 case DUPLICATING:
904 return String16("AudioDup");
905 case RECORD:
906 return String16("AudioIn");
907 case OFFLOAD:
908 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800909 case MMAP:
910 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800911 default:
912 ALOG_ASSERT(false);
913 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100914 }
915}
916
Andy Hungdae27702016-10-31 14:01:16 -0700917void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800918{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800919 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800920 if (mPowerManager != 0) {
921 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700922 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
923 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700924 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100925 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700926 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700927 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (status == NO_ERROR) {
929 mWakeLockToken = binder;
930 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800931 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
Wei Jia3f273d12015-11-24 09:06:49 -0800933
Andy Hung3f0c9022016-01-15 17:49:46 -0800934 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800935 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
936 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800937}
938
939void AudioFlinger::ThreadBase::releaseWakeLock()
940{
941 Mutex::Autolock _l(mLock);
942 releaseWakeLock_l();
943}
944
945void AudioFlinger::ThreadBase::releaseWakeLock_l()
946{
Andy Hung3f0c9022016-01-15 17:49:46 -0800947 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800948 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800949 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800950 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700951 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
952 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800953 }
954 mWakeLockToken.clear();
955 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800956}
957
958void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700959 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800960 // use checkService() to avoid blocking if power service is not up yet
961 sp<IBinder> binder =
962 defaultServiceManager()->checkService(String16("power"));
963 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800964 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800965 } else {
966 mPowerManager = interface_cast<IPowerManager>(binder);
967 binder->linkToDeath(mDeathRecipient);
968 }
969 }
970}
971
Andy Hungd01b0f12016-11-07 16:10:30 -0800972void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800973 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700974
975#if !LOG_NDEBUG
976 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800977 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700978 s << uid << " ";
979 }
980 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
981#endif
982
Andy Hung438e7572015-12-14 15:51:17 -0800983 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
984 if (mSystemReady) {
985 ALOGE("no wake lock to update, but system ready!");
986 } else {
987 ALOGW("no wake lock to update, system not ready yet");
988 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800989 return;
990 }
991 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800992 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
993 status_t status = mPowerManager->updateWakeLockUids(
994 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
995 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800996 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800997 }
998}
999
Eric Laurent81784c32012-11-19 14:55:58 -08001000void AudioFlinger::ThreadBase::clearPowerManager()
1001{
1002 Mutex::Autolock _l(mLock);
1003 releaseWakeLock_l();
1004 mPowerManager.clear();
1005}
1006
Glenn Kasten0f11b512014-01-31 16:18:54 -08001007void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001008{
1009 sp<ThreadBase> thread = mThread.promote();
1010 if (thread != 0) {
1011 thread->clearPowerManager();
1012 }
1013 ALOGW("power manager service died !!!");
1014}
1015
Eric Laurent81784c32012-11-19 14:55:58 -08001016void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001017 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001018{
1019 sp<EffectChain> chain = getEffectChain_l(sessionId);
1020 if (chain != 0) {
1021 if (type != NULL) {
1022 chain->setEffectSuspended_l(type, suspend);
1023 } else {
1024 chain->setEffectSuspendedAll_l(suspend);
1025 }
1026 }
1027
1028 updateSuspendedSessions_l(type, suspend, sessionId);
1029}
1030
1031void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1032{
1033 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1034 if (index < 0) {
1035 return;
1036 }
1037
1038 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1039 mSuspendedSessions.valueAt(index);
1040
1041 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001042 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001043 for (int j = 0; j < desc->mRefCount; j++) {
1044 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1045 chain->setEffectSuspendedAll_l(true);
1046 } else {
1047 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1048 desc->mType.timeLow);
1049 chain->setEffectSuspended_l(&desc->mType, true);
1050 }
1051 }
1052 }
1053}
1054
1055void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1056 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001057 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001058{
1059 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1060
1061 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1062
1063 if (suspend) {
1064 if (index >= 0) {
1065 sessionEffects = mSuspendedSessions.valueAt(index);
1066 } else {
1067 mSuspendedSessions.add(sessionId, sessionEffects);
1068 }
1069 } else {
1070 if (index < 0) {
1071 return;
1072 }
1073 sessionEffects = mSuspendedSessions.valueAt(index);
1074 }
1075
1076
1077 int key = EffectChain::kKeyForSuspendAll;
1078 if (type != NULL) {
1079 key = type->timeLow;
1080 }
1081 index = sessionEffects.indexOfKey(key);
1082
1083 sp<SuspendedSessionDesc> desc;
1084 if (suspend) {
1085 if (index >= 0) {
1086 desc = sessionEffects.valueAt(index);
1087 } else {
1088 desc = new SuspendedSessionDesc();
1089 if (type != NULL) {
1090 desc->mType = *type;
1091 }
1092 sessionEffects.add(key, desc);
1093 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1094 }
1095 desc->mRefCount++;
1096 } else {
1097 if (index < 0) {
1098 return;
1099 }
1100 desc = sessionEffects.valueAt(index);
1101 if (--desc->mRefCount == 0) {
1102 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1103 sessionEffects.removeItemsAt(index);
1104 if (sessionEffects.isEmpty()) {
1105 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1106 sessionId);
1107 mSuspendedSessions.removeItem(sessionId);
1108 }
1109 }
1110 }
1111 if (!sessionEffects.isEmpty()) {
1112 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1113 }
1114}
1115
1116void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1117 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001118 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001119{
1120 Mutex::Autolock _l(mLock);
1121 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1122}
1123
1124void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1125 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001126 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001127{
1128 if (mType != RECORD) {
1129 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1130 // another session. This gives the priority to well behaved effect control panels
1131 // and applications not using global effects.
1132 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1133 // global effects
1134 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1135 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1136 }
1137 }
1138
1139 sp<EffectChain> chain = getEffectChain_l(sessionId);
1140 if (chain != 0) {
1141 chain->checkSuspendOnEffectEnabled(effect, enabled);
1142 }
1143}
1144
Eric Laurent4c415062016-06-17 16:14:16 -07001145// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1146status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1147 const effect_descriptor_t *desc, audio_session_t sessionId)
1148{
1149 // No global effect sessions on record threads
1150 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1151 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1152 desc->name, mThreadName);
1153 return BAD_VALUE;
1154 }
1155 // only pre processing effects on record thread
1156 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1157 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1158 desc->name, mThreadName);
1159 return BAD_VALUE;
1160 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001161
1162 // always allow effects without processing load or latency
1163 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1164 return NO_ERROR;
1165 }
1166
Eric Laurent4c415062016-06-17 16:14:16 -07001167 audio_input_flags_t flags = mInput->flags;
1168 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1169 if (flags & AUDIO_INPUT_FLAG_RAW) {
1170 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1171 desc->name, mThreadName);
1172 return BAD_VALUE;
1173 }
1174 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1175 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1176 desc->name, mThreadName);
1177 return BAD_VALUE;
1178 }
1179 }
1180 return NO_ERROR;
1181}
1182
1183// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1184status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1185 const effect_descriptor_t *desc, audio_session_t sessionId)
1186{
1187 // no preprocessing on playback threads
1188 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1189 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1190 " thread %s", desc->name, mThreadName);
1191 return BAD_VALUE;
1192 }
1193
Eric Laurent3e4de772017-07-16 16:55:08 -07001194 // always allow effects without processing load or latency
1195 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1196 return NO_ERROR;
1197 }
1198
Eric Laurent4c415062016-06-17 16:14:16 -07001199 switch (mType) {
1200 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001201#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001202 // Reject any effect on mixer multichannel sinks.
1203 // TODO: fix both format and multichannel issues with effects.
1204 if (mChannelCount != FCC_2) {
1205 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1206 " thread %s", desc->name, mChannelCount, mThreadName);
1207 return BAD_VALUE;
1208 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001209#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001210 audio_output_flags_t flags = mOutput->flags;
1211 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1212 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1213 // global effects are applied only to non fast tracks if they are SW
1214 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1215 break;
1216 }
1217 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1218 // only post processing on output stage session
1219 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1220 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1221 " on output stage session", desc->name);
1222 return BAD_VALUE;
1223 }
1224 } else {
1225 // no restriction on effects applied on non fast tracks
1226 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1227 break;
1228 }
1229 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001230
Eric Laurent4c415062016-06-17 16:14:16 -07001231 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1232 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1233 desc->name);
1234 return BAD_VALUE;
1235 }
1236 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1237 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1238 " in fast mode", desc->name);
1239 return BAD_VALUE;
1240 }
1241 }
1242 } break;
1243 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001244 // nothing actionable on offload threads, if the effect:
1245 // - is offloadable: the effect can be created
1246 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1247 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001248 break;
1249 case DIRECT:
1250 // Reject any effect on Direct output threads for now, since the format of
1251 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1252 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1253 desc->name, mThreadName);
1254 return BAD_VALUE;
1255 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001256#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001257 // Reject any effect on mixer multichannel sinks.
1258 // TODO: fix both format and multichannel issues with effects.
1259 if (mChannelCount != FCC_2) {
1260 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1261 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1262 return BAD_VALUE;
1263 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001264#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001265 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1266 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1267 " thread %s", desc->name, mThreadName);
1268 return BAD_VALUE;
1269 }
1270 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1271 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1272 " DUPLICATING thread %s", desc->name, mThreadName);
1273 return BAD_VALUE;
1274 }
1275 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1276 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1277 " DUPLICATING thread %s", desc->name, mThreadName);
1278 return BAD_VALUE;
1279 }
1280 break;
1281 default:
1282 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1283 }
1284
1285 return NO_ERROR;
1286}
1287
Eric Laurent81784c32012-11-19 14:55:58 -08001288// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1289sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1290 const sp<AudioFlinger::Client>& client,
1291 const sp<IEffectClient>& effectClient,
1292 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001293 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001294 effect_descriptor_t *desc,
1295 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001296 status_t *status,
1297 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001298{
1299 sp<EffectModule> effect;
1300 sp<EffectHandle> handle;
1301 status_t lStatus;
1302 sp<EffectChain> chain;
1303 bool chainCreated = false;
1304 bool effectCreated = false;
1305 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001306 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001307
1308 lStatus = initCheck();
1309 if (lStatus != NO_ERROR) {
1310 ALOGW("createEffect_l() Audio driver not initialized.");
1311 goto Exit;
1312 }
1313
Eric Laurent81784c32012-11-19 14:55:58 -08001314 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1315
1316 { // scope for mLock
1317 Mutex::Autolock _l(mLock);
1318
Eric Laurent4c415062016-06-17 16:14:16 -07001319 lStatus = checkEffectCompatibility_l(desc, sessionId);
1320 if (lStatus != NO_ERROR) {
1321 goto Exit;
1322 }
1323
Eric Laurent81784c32012-11-19 14:55:58 -08001324 // check for existing effect chain with the requested audio session
1325 chain = getEffectChain_l(sessionId);
1326 if (chain == 0) {
1327 // create a new chain for this session
1328 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1329 chain = new EffectChain(this, sessionId);
1330 addEffectChain_l(chain);
1331 chain->setStrategy(getStrategyForSession_l(sessionId));
1332 chainCreated = true;
1333 } else {
1334 effect = chain->getEffectFromDesc_l(desc);
1335 }
1336
1337 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1338
1339 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001340 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001341 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001342 lStatus = AudioSystem::registerEffect(
1343 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001344 if (lStatus != NO_ERROR) {
1345 goto Exit;
1346 }
1347 effectRegistered = true;
1348 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001349 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001350 if (lStatus != NO_ERROR) {
1351 goto Exit;
1352 }
1353 effectCreated = true;
1354
1355 effect->setDevice(mOutDevice);
1356 effect->setDevice(mInDevice);
1357 effect->setMode(mAudioFlinger->getMode());
1358 effect->setAudioSource(mAudioSource);
1359 }
1360 // create effect handle and connect it to effect module
1361 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001362 lStatus = handle->initCheck();
1363 if (lStatus == OK) {
1364 lStatus = effect->addHandle(handle.get());
1365 }
Eric Laurent81784c32012-11-19 14:55:58 -08001366 if (enabled != NULL) {
1367 *enabled = (int)effect->isEnabled();
1368 }
1369 }
1370
1371Exit:
1372 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1373 Mutex::Autolock _l(mLock);
1374 if (effectCreated) {
1375 chain->removeEffect_l(effect);
1376 }
1377 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001378 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001379 }
1380 if (chainCreated) {
1381 removeEffectChain_l(chain);
1382 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001383 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001384 }
1385
Glenn Kasten9156ef32013-08-06 15:39:08 -07001386 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001387 return handle;
1388}
1389
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001390void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1391 bool unpinIfLast)
1392{
1393 bool remove = false;
1394 sp<EffectModule> effect;
1395 {
1396 Mutex::Autolock _l(mLock);
1397
1398 effect = handle->effect().promote();
1399 if (effect == 0) {
1400 return;
1401 }
1402 // restore suspended effects if the disconnected handle was enabled and the last one.
1403 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1404 if (remove) {
1405 removeEffect_l(effect, true);
1406 }
1407 }
1408 if (remove) {
1409 mAudioFlinger->updateOrphanEffectChains(effect);
1410 AudioSystem::unregisterEffect(effect->id());
1411 if (handle->enabled()) {
1412 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1413 }
1414 }
1415}
1416
Glenn Kastend848eb42016-03-08 13:42:11 -08001417sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1418 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001419{
1420 Mutex::Autolock _l(mLock);
1421 return getEffect_l(sessionId, effectId);
1422}
1423
Glenn Kastend848eb42016-03-08 13:42:11 -08001424sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1425 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001426{
1427 sp<EffectChain> chain = getEffectChain_l(sessionId);
1428 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1429}
1430
1431// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1432// PlaybackThread::mLock held
1433status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1434{
1435 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001436 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001437 sp<EffectChain> chain = getEffectChain_l(sessionId);
1438 bool chainCreated = false;
1439
Eric Laurent5baf2af2013-09-12 17:37:00 -07001440 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001441 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001442 this, effect->desc().name, effect->desc().flags);
1443
Eric Laurent81784c32012-11-19 14:55:58 -08001444 if (chain == 0) {
1445 // create a new chain for this session
1446 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1447 chain = new EffectChain(this, sessionId);
1448 addEffectChain_l(chain);
1449 chain->setStrategy(getStrategyForSession_l(sessionId));
1450 chainCreated = true;
1451 }
1452 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1453
1454 if (chain->getEffectFromId_l(effect->id()) != 0) {
1455 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1456 this, effect->desc().name, chain.get());
1457 return BAD_VALUE;
1458 }
1459
Eric Laurent5baf2af2013-09-12 17:37:00 -07001460 effect->setOffloaded(mType == OFFLOAD, mId);
1461
Eric Laurent81784c32012-11-19 14:55:58 -08001462 status_t status = chain->addEffect_l(effect);
1463 if (status != NO_ERROR) {
1464 if (chainCreated) {
1465 removeEffectChain_l(chain);
1466 }
1467 return status;
1468 }
1469
1470 effect->setDevice(mOutDevice);
1471 effect->setDevice(mInDevice);
1472 effect->setMode(mAudioFlinger->getMode());
1473 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001474
Eric Laurent81784c32012-11-19 14:55:58 -08001475 return NO_ERROR;
1476}
1477
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001478void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001479
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001480 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001481 effect_descriptor_t desc = effect->desc();
1482 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1483 detachAuxEffect_l(effect->id());
1484 }
1485
1486 sp<EffectChain> chain = effect->chain().promote();
1487 if (chain != 0) {
1488 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001489 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001490 removeEffectChain_l(chain);
1491 }
1492 } else {
1493 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1494 }
1495}
1496
1497void AudioFlinger::ThreadBase::lockEffectChains_l(
1498 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1499{
1500 effectChains = mEffectChains;
1501 for (size_t i = 0; i < mEffectChains.size(); i++) {
1502 mEffectChains[i]->lock();
1503 }
1504}
1505
1506void AudioFlinger::ThreadBase::unlockEffectChains(
1507 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1508{
1509 for (size_t i = 0; i < effectChains.size(); i++) {
1510 effectChains[i]->unlock();
1511 }
1512}
1513
Glenn Kastend848eb42016-03-08 13:42:11 -08001514sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001515{
1516 Mutex::Autolock _l(mLock);
1517 return getEffectChain_l(sessionId);
1518}
1519
Glenn Kastend848eb42016-03-08 13:42:11 -08001520sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1521 const
Eric Laurent81784c32012-11-19 14:55:58 -08001522{
1523 size_t size = mEffectChains.size();
1524 for (size_t i = 0; i < size; i++) {
1525 if (mEffectChains[i]->sessionId() == sessionId) {
1526 return mEffectChains[i];
1527 }
1528 }
1529 return 0;
1530}
1531
1532void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1533{
1534 Mutex::Autolock _l(mLock);
1535 size_t size = mEffectChains.size();
1536 for (size_t i = 0; i < size; i++) {
1537 mEffectChains[i]->setMode_l(mode);
1538 }
1539}
1540
Mikhail Naganovdc769682018-05-04 15:34:08 -07001541void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001542{
1543 config->type = AUDIO_PORT_TYPE_MIX;
1544 config->ext.mix.handle = mId;
1545 config->sample_rate = mSampleRate;
1546 config->format = mFormat;
1547 config->channel_mask = mChannelMask;
1548 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1549 AUDIO_PORT_CONFIG_FORMAT;
1550}
1551
Eric Laurent72e3f392015-05-20 14:43:50 -07001552void AudioFlinger::ThreadBase::systemReady()
1553{
1554 Mutex::Autolock _l(mLock);
1555 if (mSystemReady) {
1556 return;
1557 }
1558 mSystemReady = true;
1559
1560 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1561 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1562 }
1563 mPendingConfigEvents.clear();
1564}
1565
Andy Hungdae27702016-10-31 14:01:16 -07001566template <typename T>
1567ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1568 ssize_t index = mActiveTracks.indexOf(track);
1569 if (index >= 0) {
1570 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1571 return index;
1572 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001573 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001574 mActiveTracksGeneration++;
1575 mLatestActiveTrack = track;
1576 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001577 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001578 return mActiveTracks.add(track);
1579}
1580
1581template <typename T>
1582ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1583 ssize_t index = mActiveTracks.remove(track);
1584 if (index < 0) {
1585 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1586 return index;
1587 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001588 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001589 mActiveTracksGeneration++;
1590 --mBatteryCounter[track->uid()].second;
1591 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001592 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001593#ifdef TEE_SINK
1594 track->dumpTee(-1 /* fd */, "_REMOVE");
1595#endif
Andy Hungdae27702016-10-31 14:01:16 -07001596 return index;
1597}
1598
1599template <typename T>
1600void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1601 for (const sp<T> &track : mActiveTracks) {
1602 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001603 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001604 }
1605 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001606 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001607 mActiveTracks.clear();
1608 mLatestActiveTrack.clear();
1609 mBatteryCounter.clear();
1610}
1611
1612template <typename T>
1613void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1614 sp<ThreadBase> thread, bool force) {
1615 // Updates ActiveTracks client uids to the thread wakelock.
1616 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1617 thread->updateWakeLockUids_l(getWakeLockUids());
1618 mLastActiveTracksGeneration = mActiveTracksGeneration;
1619 }
1620
1621 // Updates BatteryNotifier uids
1622 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1623 const uid_t uid = it->first;
1624 ssize_t &previous = it->second.first;
1625 ssize_t &current = it->second.second;
1626 if (current > 0) {
1627 if (previous == 0) {
1628 BatteryNotifier::getInstance().noteStartAudio(uid);
1629 }
1630 previous = current;
1631 ++it;
1632 } else if (current == 0) {
1633 if (previous > 0) {
1634 BatteryNotifier::getInstance().noteStopAudio(uid);
1635 }
1636 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1637 } else /* (current < 0) */ {
1638 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1639 }
1640 }
1641}
Eric Laurent83b88082014-06-20 18:31:16 -07001642
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001643template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001644bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1645 const bool hasChanged = mHasChanged;
1646 mHasChanged = false;
1647 return hasChanged;
1648}
1649
1650template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001651void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1652 const char *funcName, const sp<T> &track) const {
1653 if (mLocalLog != nullptr) {
1654 String8 result;
1655 track->appendDump(result, false /* active */);
1656 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1657 }
1658}
1659
Eric Laurent6acd1d42017-01-04 14:23:29 -08001660void AudioFlinger::ThreadBase::broadcast_l()
1661{
1662 // Thread could be blocked waiting for async
1663 // so signal it to handle state changes immediately
1664 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1665 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1666 mSignalPending = true;
1667 mWaitWorkCV.broadcast();
1668}
1669
Eric Laurent81784c32012-11-19 14:55:58 -08001670// ----------------------------------------------------------------------------
1671// Playback
1672// ----------------------------------------------------------------------------
1673
1674AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1675 AudioStreamOut* output,
1676 audio_io_handle_t id,
1677 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001678 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001679 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001680 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001681 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001682 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001683 mMixerBuffer(NULL),
1684 mMixerBufferSize(0),
1685 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1686 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001687 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001688 mEffectBuffer(NULL),
1689 mEffectBufferSize(0),
1690 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1691 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001692 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001693 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001694 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001695 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001696 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001697 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001698 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001699 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001700 mMixerStatus(MIXER_IDLE),
1701 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001702 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001703 mBytesRemaining(0),
1704 mCurrentWriteLength(0),
1705 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001706 mWriteAckSequence(0),
1707 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001708 mScreenState(AudioFlinger::mScreenState),
1709 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001710 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001711 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1712 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001713{
Glenn Kastend7dca052015-03-05 16:05:54 -08001714 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1715 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001716
1717 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1718 // it would be safer to explicitly pass initial masterVolume/masterMute as
1719 // parameter.
1720 //
1721 // If the HAL we are using has support for master volume or master mute,
1722 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1723 // and the mute set to false).
1724 mMasterVolume = audioFlinger->masterVolume_l();
1725 mMasterMute = audioFlinger->masterMute_l();
1726 if (mOutput && mOutput->audioHwDev) {
1727 if (mOutput->audioHwDev->canSetMasterVolume()) {
1728 mMasterVolume = 1.0;
1729 }
1730
1731 if (mOutput->audioHwDev->canSetMasterMute()) {
1732 mMasterMute = false;
1733 }
1734 }
1735
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001736 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001737
Eric Laurent223fd5c2014-11-11 13:43:36 -08001738 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001739 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001740 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001741 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001742 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1743 }
Eric Laurent98e38192018-02-15 18:31:53 -08001744 // Audio patch volume is always max
1745 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1746 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001747}
1748
1749AudioFlinger::PlaybackThread::~PlaybackThread()
1750{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001751 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001752 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001753 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001754 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001755}
1756
1757void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1758{
1759 dumpInternals(fd, args);
1760 dumpTracks(fd, args);
1761 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001762 dprintf(fd, " Local log:\n");
1763 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001764}
1765
Eric Tan7b651152018-07-13 10:17:19 -07001766std::string AudioFlinger::PlaybackThread::getJsonString() const
1767{
1768 return "{}";
1769}
1770
Glenn Kasten0f11b512014-01-31 16:18:54 -08001771void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001772{
Eric Laurent81784c32012-11-19 14:55:58 -08001773 String8 result;
1774
Marco Nelissenb2208842014-02-07 14:00:50 -08001775 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001776 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1777 const stream_type_t *st = &mStreamTypes[i];
1778 if (i > 0) {
1779 result.appendFormat(", ");
1780 }
1781 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1782 if (st->mute) {
1783 result.append("M");
1784 }
1785 }
1786 result.append("\n");
1787 write(fd, result.string(), result.length());
1788 result.clear();
1789
Eric Laurent81784c32012-11-19 14:55:58 -08001790 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1791 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001792 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001793 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001794
1795 size_t numtracks = mTracks.size();
1796 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001797 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001798 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001799 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001800 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001801 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001802 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001803 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001804 for (size_t i = 0; i < numtracks; ++i) {
1805 sp<Track> track = mTracks[i];
1806 if (track != 0) {
1807 bool active = mActiveTracks.indexOf(track) >= 0;
1808 if (active) {
1809 numactiveseen++;
1810 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001811 result.append(prefix);
1812 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001813 }
1814 }
1815 } else {
1816 result.append("\n");
1817 }
1818 if (numactiveseen != numactive) {
1819 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001820 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001821 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001822 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001823 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001824 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001825 sp<Track> track = mActiveTracks[i];
1826 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001827 result.append(prefix);
1828 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001829 }
1830 }
1831 }
1832
1833 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001834}
1835
1836void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1837{
Glenn Kasten44182c22015-03-05 17:12:23 -08001838 dumpBase(fd, args);
1839
Elliott Hughes87cebad2014-05-22 10:14:43 -07001840 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001841 dprintf(fd, " Last write occurred (msecs): %llu\n",
1842 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001843 dprintf(fd, " Total writes: %d\n", mNumWrites);
1844 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1845 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1846 dprintf(fd, " Suspend count: %d\n", mSuspended);
1847 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1848 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1849 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1850 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001851 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001852 AudioStreamOut *output = mOutput;
1853 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001854 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1855 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001856 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1857 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1858 if (mPipeSink.get() != nullptr) {
1859 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1860 }
1861 if (output != nullptr) {
1862 dprintf(fd, " Hal stream dump:\n");
1863 (void)output->stream->dump(fd);
1864 }
Eric Laurent81784c32012-11-19 14:55:58 -08001865}
1866
1867// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001868
1869void AudioFlinger::PlaybackThread::onFirstRef()
1870{
Glenn Kastend7dca052015-03-05 16:05:54 -08001871 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001872}
1873
1874// ThreadBase virtuals
1875void AudioFlinger::PlaybackThread::preExit()
1876{
1877 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001878 // FIXME this is using hard-coded strings but in the future, this functionality will be
1879 // converted to use audio HAL extensions required to support tunneling
1880 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1881 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001882}
1883
1884// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1885sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1886 const sp<AudioFlinger::Client>& client,
1887 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001888 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001889 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001890 audio_format_t format,
1891 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001892 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001893 size_t *pNotificationFrameCount,
1894 uint32_t notificationsPerBuffer,
1895 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001896 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001897 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001898 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001899 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001900 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001901 status_t *status,
1902 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001903{
Glenn Kasten74935e42013-12-19 08:56:45 -08001904 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001905 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001906 sp<Track> track;
1907 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001908 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001909 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001910 uint32_t sampleRate;
1911
1912 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1913 lStatus = BAD_VALUE;
1914 goto Exit;
1915 }
Eric Laurent21da6472017-11-09 16:29:26 -08001916
1917 if (*pSampleRate == 0) {
1918 *pSampleRate = mSampleRate;
1919 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001920 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001921
1922 // special case for FAST flag considered OK if fast mixer is present
1923 if (hasFastMixer()) {
1924 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1925 }
1926
1927 // Check if requested flags are compatible with output stream flags
1928 if ((*flags & outputFlags) != *flags) {
1929 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1930 *flags, outputFlags);
1931 *flags = (audio_output_flags_t)(*flags & outputFlags);
1932 }
Eric Laurent81784c32012-11-19 14:55:58 -08001933
Eric Laurent81784c32012-11-19 14:55:58 -08001934 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001935 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001936 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001937 // PCM data
1938 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001939 // TODO: extract as a data library function that checks that a computationally
1940 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001941 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001942 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1943 (channelMask == AUDIO_CHANNEL_OUT_MONO
1944 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001945 // hardware sample rate
1946 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001947 // normal mixer has an associated fast mixer
1948 hasFastMixer() &&
1949 // there are sufficient fast track slots available
1950 (mFastTrackAvailMask != 0)
1951 // FIXME test that MixerThread for this fast track has a capable output HAL
1952 // FIXME add a permission test also?
1953 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001954 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1955 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001956 // read the fast track multiplier property the first time it is needed
1957 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1958 if (ok != 0) {
1959 ALOGE("%s pthread_once failed: %d", __func__, ok);
1960 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001961 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001962 }
Eric Laurent4c415062016-06-17 16:14:16 -07001963
1964 // check compatibility with audio effects.
1965 { // scope for mLock
1966 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001967 for (audio_session_t session : {
1968 AUDIO_SESSION_OUTPUT_STAGE,
1969 AUDIO_SESSION_OUTPUT_MIX,
1970 sessionId,
1971 }) {
1972 sp<EffectChain> chain = getEffectChain_l(session);
1973 if (chain.get() != nullptr) {
1974 audio_output_flags_t old = *flags;
1975 chain->checkOutputFlagCompatibility(flags);
1976 if (old != *flags) {
1977 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1978 (int)session, (int)old, (int)*flags);
1979 }
Eric Laurent4c415062016-06-17 16:14:16 -07001980 }
1981 }
1982 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001983 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001984 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1985 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001986 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001987 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1988 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001989 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001990 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001991 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001992 audio_is_linear_pcm(format),
1993 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001994 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001995 }
1996 }
Eric Laurent21da6472017-11-09 16:29:26 -08001997
1998 if (!audio_has_proportional_frames(format)) {
1999 if (sharedBuffer != 0) {
2000 // Same comment as below about ignoring frameCount parameter for set()
2001 frameCount = sharedBuffer->size();
2002 } else if (frameCount == 0) {
2003 frameCount = mNormalFrameCount;
2004 }
2005 if (notificationFrameCount != frameCount) {
2006 notificationFrameCount = frameCount;
2007 }
2008 } else if (sharedBuffer != 0) {
2009 // FIXME: Ensure client side memory buffers need
2010 // not have additional alignment beyond sample
2011 // (e.g. 16 bit stereo accessed as 32 bit frame).
2012 size_t alignment = audio_bytes_per_sample(format);
2013 if (alignment & 1) {
2014 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2015 alignment = 1;
2016 }
2017 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2018 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2019 if (channelCount > 1) {
2020 // More than 2 channels does not require stronger alignment than stereo
2021 alignment <<= 1;
2022 }
2023 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2024 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2025 sharedBuffer->pointer(), channelCount);
2026 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002027 goto Exit;
2028 }
Eric Laurent21da6472017-11-09 16:29:26 -08002029
2030 // When initializing a shared buffer AudioTrack via constructors,
2031 // there's no frameCount parameter.
2032 // But when initializing a shared buffer AudioTrack via set(),
2033 // there _is_ a frameCount parameter. We silently ignore it.
2034 frameCount = sharedBuffer->size() / frameSize;
2035 } else {
2036 size_t minFrameCount = 0;
2037 // For fast tracks we try to respect the application's request for notifications per buffer.
2038 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2039 if (notificationsPerBuffer > 0) {
2040 // Avoid possible arithmetic overflow during multiplication.
2041 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2042 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2043 notificationsPerBuffer, mFrameCount);
2044 } else {
2045 minFrameCount = mFrameCount * notificationsPerBuffer;
2046 }
2047 }
2048 } else {
2049 // For normal PCM streaming tracks, update minimum frame count.
2050 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2051 // cover audio hardware latency.
2052 // This is probably too conservative, but legacy application code may depend on it.
2053 // If you change this calculation, also review the start threshold which is related.
2054 uint32_t latencyMs = latency_l();
2055 if (latencyMs == 0) {
2056 ALOGE("Error when retrieving output stream latency");
2057 lStatus = UNKNOWN_ERROR;
2058 goto Exit;
2059 }
2060
2061 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2062 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2063
Eric Laurent81784c32012-11-19 14:55:58 -08002064 }
Eric Laurent21da6472017-11-09 16:29:26 -08002065 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002066 frameCount = minFrameCount;
2067 }
Eric Laurent81784c32012-11-19 14:55:58 -08002068 }
Eric Laurent21da6472017-11-09 16:29:26 -08002069
2070 // Make sure that application is notified with sufficient margin before underrun.
2071 // The client can divide the AudioTrack buffer into sub-buffers,
2072 // and expresses its desire to server as the notification frame count.
2073 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2074 size_t maxNotificationFrames;
2075 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2076 // notify every HAL buffer, regardless of the size of the track buffer
2077 maxNotificationFrames = mFrameCount;
2078 } else {
2079 // For normal tracks, use at least double-buffering if no sample rate conversion,
2080 // or at least triple-buffering if there is sample rate conversion
2081 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2082 maxNotificationFrames = frameCount / nBuffering;
2083 // If client requested a fast track but this was denied, then use the smaller maximum.
2084 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2085 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2086 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2087 maxNotificationFrames = maxNotificationFramesFastDenied;
2088 }
2089 }
2090 }
2091 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2092 if (notificationFrameCount == 0) {
2093 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2094 maxNotificationFrames, frameCount);
2095 } else {
2096 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2097 notificationFrameCount, maxNotificationFrames, frameCount);
2098 }
2099 notificationFrameCount = maxNotificationFrames;
2100 }
2101 }
2102
Glenn Kasten74935e42013-12-19 08:56:45 -08002103 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002104 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002105
Glenn Kastenc3df8382014-03-13 15:05:25 -07002106 switch (mType) {
2107
2108 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002109 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002110 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002111 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2112 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002113 sampleRate, format, channelMask, mOutput, mFormat);
2114 lStatus = BAD_VALUE;
2115 goto Exit;
2116 }
2117 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002118 break;
2119
2120 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002121 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002122 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2123 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002124 sampleRate, format, channelMask, mOutput, mFormat);
2125 lStatus = BAD_VALUE;
2126 goto Exit;
2127 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002128 break;
2129
2130 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002131 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002132 ALOGE("createTrack_l() Bad parameter: format %#x \""
2133 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002134 format, mOutput, mFormat);
2135 lStatus = BAD_VALUE;
2136 goto Exit;
2137 }
Andy Hungcd044842014-08-07 11:04:34 -07002138 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002139 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2140 lStatus = BAD_VALUE;
2141 goto Exit;
2142 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002143 break;
2144
Eric Laurent81784c32012-11-19 14:55:58 -08002145 }
2146
2147 lStatus = initCheck();
2148 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002149 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002150 goto Exit;
2151 }
2152
2153 { // scope for mLock
2154 Mutex::Autolock _l(mLock);
2155
2156 // all tracks in same audio session must share the same routing strategy otherwise
2157 // conflicts will happen when tracks are moved from one output to another by audio policy
2158 // manager
2159 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2160 for (size_t i = 0; i < mTracks.size(); ++i) {
2161 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002162 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002163 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2164 if (sessionId == t->sessionId() && strategy != actual) {
2165 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2166 strategy, actual);
2167 lStatus = BAD_VALUE;
2168 goto Exit;
2169 }
2170 }
2171 }
2172
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002173 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002174 channelMask, frameCount,
2175 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002176 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002177
Glenn Kasten03003332013-08-06 15:40:54 -07002178 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2179 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002180 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002181 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002182 goto Exit;
2183 }
2184 mTracks.add(track);
2185
2186 sp<EffectChain> chain = getEffectChain_l(sessionId);
2187 if (chain != 0) {
2188 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2189 track->setMainBuffer(chain->inBuffer());
2190 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2191 chain->incTrackCnt();
2192 }
2193
Eric Laurent05067782016-06-01 18:27:28 -07002194 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002195 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2196 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2197 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002198 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002199 }
2200 }
2201
2202 lStatus = NO_ERROR;
2203
2204Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002205 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002206 return track;
2207}
2208
Andy Hung1bc088a2018-02-09 15:57:31 -08002209template<typename T>
2210ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track)
2211{
2212 const ssize_t index = mTracks.add(track);
2213 if (index >= 0) {
2214 // set name for track when adding.
2215 int name;
2216 if (mUnusedTrackNames.empty()) {
2217 name = mTracks.size() - 1; // new name {0 ... size-1}.
2218 } else {
2219 // reuse smallest name for deleted track.
2220 auto it = mUnusedTrackNames.begin();
2221 name = *it;
2222 (void)mUnusedTrackNames.erase(it);
2223 }
2224 track->setName(name);
2225 } else {
2226 LOG_ALWAYS_FATAL("cannot add track");
2227 }
2228 return index;
2229}
2230
2231template<typename T>
2232ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2233{
2234 const int name = track->name();
2235 const ssize_t index = mTracks.remove(track);
2236 if (index >= 0) {
2237 // invalidate name when removing from mTracks.
2238 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name);
2239
2240 if (mSaveDeletedTrackNames) {
2241 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2242 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update,
2243 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2244 mDeletedTrackNames.emplace(name);
2245 }
2246
2247 mUnusedTrackNames.emplace(name);
2248 track->setName(T::TRACK_NAME_PENDING);
2249 } else {
2250 LOG_ALWAYS_FATAL_IF(name >= 0,
2251 "valid name %d for track not in mTracks (returned %zd)", name, index);
2252 }
2253 return index;
2254}
2255
Eric Laurent81784c32012-11-19 14:55:58 -08002256uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2257{
2258 return latency;
2259}
2260
2261uint32_t AudioFlinger::PlaybackThread::latency() const
2262{
2263 Mutex::Autolock _l(mLock);
2264 return latency_l();
2265}
2266uint32_t AudioFlinger::PlaybackThread::latency_l() const
2267{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002268 uint32_t latency;
2269 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2270 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002271 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002272 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002273}
2274
2275void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2276{
2277 Mutex::Autolock _l(mLock);
2278 // Don't apply master volume in SW if our HAL can do it for us.
2279 if (mOutput && mOutput->audioHwDev &&
2280 mOutput->audioHwDev->canSetMasterVolume()) {
2281 mMasterVolume = 1.0;
2282 } else {
2283 mMasterVolume = value;
2284 }
2285}
2286
2287void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2288{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002289 if (isDuplicating()) {
2290 return;
2291 }
Eric Laurent81784c32012-11-19 14:55:58 -08002292 Mutex::Autolock _l(mLock);
2293 // Don't apply master mute in SW if our HAL can do it for us.
2294 if (mOutput && mOutput->audioHwDev &&
2295 mOutput->audioHwDev->canSetMasterMute()) {
2296 mMasterMute = false;
2297 } else {
2298 mMasterMute = muted;
2299 }
2300}
2301
2302void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2303{
2304 Mutex::Autolock _l(mLock);
2305 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002306 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002307}
2308
2309void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2310{
2311 Mutex::Autolock _l(mLock);
2312 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002313 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002314}
2315
2316float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2317{
2318 Mutex::Autolock _l(mLock);
2319 return mStreamTypes[stream].volume;
2320}
2321
2322// addTrack_l() must be called with ThreadBase::mLock held
2323status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2324{
2325 status_t status = ALREADY_EXISTS;
2326
Eric Laurent81784c32012-11-19 14:55:58 -08002327 if (mActiveTracks.indexOf(track) < 0) {
2328 // the track is newly added, make sure it fills up all its
2329 // buffers before playing. This is to ensure the client will
2330 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002331 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002332 TrackBase::track_state state = track->mState;
2333 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002334 status = AudioSystem::startOutput(track->portId());
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 Laurentd7fe0862018-07-14 16:48:01 -07002340 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002341 mLock.lock();
2342 }
2343 return INVALID_OPERATION;
2344 }
2345 // abort if start is rejected by audio policy manager
2346 if (status != NO_ERROR) {
2347 return PERMISSION_DENIED;
2348 }
2349#ifdef ADD_BATTERY_DATA
2350 // to track the speaker usage
2351 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2352#endif
2353 }
2354
Eric Laurent51716182016-02-29 18:00:56 -08002355 // set retry count for buffer fill
2356 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002357 if (track->isStopping_1()) {
2358 track->mRetryCount = kMaxTrackStopRetriesOffload;
2359 } else {
2360 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2361 }
2362 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002363 } else {
2364 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002365 track->mFillingUpStatus =
2366 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002367 }
2368
Eric Laurent81784c32012-11-19 14:55:58 -08002369 track->mResetDone = false;
2370 track->mPresentationCompleteFrames = 0;
2371 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002372 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2373 if (chain != 0) {
2374 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2375 track->sessionId());
2376 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002377 }
2378
2379 status = NO_ERROR;
2380 }
2381
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002382 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002383 return status;
2384}
2385
Eric Laurentbfb1b832013-01-07 09:53:42 -08002386bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002387{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002388 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002389 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2391 track->mState = TrackBase::STOPPED;
2392 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002393 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002394 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002396 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002397
2398 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002399}
2400
2401void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2402{
2403 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002404
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002405 String8 result;
2406 track->appendDump(result, false /* active */);
2407 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002408
Eric Laurent81784c32012-11-19 14:55:58 -08002409 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002410 if (track->isFastTrack()) {
2411 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002412 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002413 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2414 mFastTrackAvailMask |= 1 << index;
2415 // redundant as track is about to be destroyed, for dumpsys only
2416 track->mFastIndex = -1;
2417 }
2418 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2419 if (chain != 0) {
2420 chain->decTrackCnt();
2421 }
2422}
2423
2424String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2425{
Eric Laurent81784c32012-11-19 14:55:58 -08002426 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002427 String8 out_s8;
2428 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2429 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002430 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002431 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002432}
2433
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002434void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002435 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2436 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002437
Eric Laurent73e26b62015-04-27 16:55:58 -07002438 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002439
2440 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002441 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002442 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002443 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002444 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002445 desc->mChannelMask = mChannelMask;
2446 desc->mSamplingRate = mSampleRate;
2447 desc->mFormat = mFormat;
2448 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002449 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002450 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002451 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002452 break;
2453
Eric Laurent73e26b62015-04-27 16:55:58 -07002454 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002455 default:
2456 break;
2457 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002458 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002459}
2460
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002461void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002462{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002463 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002464}
2465
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002466void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002467{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002468 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002469}
2470
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002471void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002472{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002473 mCallbackThread->setAsyncError();
2474}
2475
Eric Laurent3b4529e2013-09-05 18:09:19 -07002476void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002477{
2478 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002479 // reject out of sequence requests
2480 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2481 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002482 mWaitWorkCV.signal();
2483 }
2484}
2485
Eric Laurent3b4529e2013-09-05 18:09:19 -07002486void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002487{
2488 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002489 // reject out of sequence requests
2490 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002491 // Register discontinuity when HW drain is completed because that can cause
2492 // the timestamp frame position to reset to 0 for direct and offload threads.
2493 // (Out of sequence requests are ignored, since the discontinuity would be handled
2494 // elsewhere, e.g. in flush).
2495 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002496 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497 mWaitWorkCV.signal();
2498 }
2499}
2500
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002501void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002502{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002503 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002504 mSampleRate = mOutput->getSampleRate();
2505 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002506 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002507 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002508 }
Andy Hung9a592762014-07-21 21:56:01 -07002509 if ((mType == MIXER || mType == DUPLICATING)
2510 && !isValidPcmSinkChannelMask(mChannelMask)) {
2511 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2512 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002513 }
Andy Hunge5412692014-05-16 11:25:07 -07002514 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002515
2516 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002517 status_t result = mOutput->stream->getFormat(&mHALFormat);
2518 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002519 // Get format from the shim, which will be different than the HAL format
2520 // if playing compressed audio over HDMI passthrough.
2521 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002522 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002523 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002524 }
Andy Hung6146c082014-03-18 11:56:15 -07002525 if ((mType == MIXER || mType == DUPLICATING)
2526 && !isValidPcmSinkFormat(mFormat)) {
2527 LOG_FATAL("HAL format %#x not supported for mixed output",
2528 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002529 }
Phil Burk062e67a2015-02-11 13:40:50 -08002530 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002531 result = mOutput->stream->getBufferSize(&mBufferSize);
2532 LOG_ALWAYS_FATAL_IF(result != OK,
2533 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002534 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002535 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002536 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002537 mFrameCount);
2538 }
2539
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002540 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2541 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002542 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002543 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002544 }
2545 }
2546
Eric Laurentd1f69b02014-12-15 14:33:13 -08002547 mHwSupportsPause = false;
2548 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002549 bool supportsPause = false, supportsResume = false;
2550 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2551 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002552 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002553 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002554 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002555 } else if (supportsResume) {
2556 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002557 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002558 }
2559 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002560 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2561 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2562 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002563
Andy Hungfbfc3952015-01-15 13:33:51 -08002564 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2565 // For best precision, we use float instead of the associated output
2566 // device format (typically PCM 16 bit).
2567
2568 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2569 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2570 mBufferSize = mFrameSize * mFrameCount;
2571
2572 // TODO: We currently use the associated output device channel mask and sample rate.
2573 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2574 // (if a valid mask) to avoid premature downmix.
2575 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2576 // instead of the output device sample rate to avoid loss of high frequency information.
2577 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2578 }
2579
Andy Hung09a50072014-02-27 14:30:47 -08002580 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002581 double multiplier = 1.0;
2582 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2583 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002584 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2585 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002586
Eric Laurent81784c32012-11-19 14:55:58 -08002587 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2588 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2589 maxNormalFrameCount = maxNormalFrameCount & ~15;
2590 if (maxNormalFrameCount < minNormalFrameCount) {
2591 maxNormalFrameCount = minNormalFrameCount;
2592 }
2593 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2594 if (multiplier <= 1.0) {
2595 multiplier = 1.0;
2596 } else if (multiplier <= 2.0) {
2597 if (2 * mFrameCount <= maxNormalFrameCount) {
2598 multiplier = 2.0;
2599 } else {
2600 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2601 }
2602 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002603 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002604 }
2605 }
2606 mNormalFrameCount = multiplier * mFrameCount;
2607 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002608 if (mType == MIXER || mType == DUPLICATING) {
2609 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2610 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002611 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002612 mNormalFrameCount);
2613
Andy Hung08fb1742015-05-31 23:22:10 -07002614 // Check if we want to throttle the processing to no more than 2x normal rate
2615 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002616 mThreadThrottleTimeMs = 0;
2617 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002618 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2619
Andy Hung010a1a12014-03-13 13:57:33 -07002620 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2621 // Originally this was int16_t[] array, need to remove legacy implications.
2622 free(mSinkBuffer);
2623 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002624 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2625 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2626 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002627 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002628
Andy Hung69aed5f2014-02-25 17:24:40 -08002629 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2630 // drives the output.
2631 free(mMixerBuffer);
2632 mMixerBuffer = NULL;
2633 if (mMixerBufferEnabled) {
2634 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2635 mMixerBufferSize = mNormalFrameCount * mChannelCount
2636 * audio_bytes_per_sample(mMixerBufferFormat);
2637 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2638 }
Andy Hung98ef9782014-03-04 14:46:50 -08002639 free(mEffectBuffer);
2640 mEffectBuffer = NULL;
2641 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002642 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002643 mEffectBufferSize = mNormalFrameCount * mChannelCount
2644 * audio_bytes_per_sample(mEffectBufferFormat);
2645 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2646 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002647
Eric Laurent81784c32012-11-19 14:55:58 -08002648 // force reconfiguration of effect chains and engines to take new buffer size and audio
2649 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002650 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002651 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2652 // matter.
2653 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2654 Vector< sp<EffectChain> > effectChains = mEffectChains;
2655 for (size_t i = 0; i < effectChains.size(); i ++) {
2656 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2657 }
2658}
2659
Kevin Rocard069c2712018-03-29 19:09:14 -07002660void AudioFlinger::PlaybackThread::updateMetadata_l()
2661{
Kevin Rocard12381092018-04-11 09:19:59 -07002662 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2663 return; // That should not happen
2664 }
2665 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2666 for (const sp<Track> &track : mActiveTracks) {
2667 // Do not short-circuit as all hasChanged states must be reset
2668 // as all the metadata are going to be sent
2669 hasChanged |= track->readAndClearHasChanged();
2670 }
2671 if (!hasChanged) {
2672 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002673 }
2674 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002675 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002676 for (const sp<Track> &track : mActiveTracks) {
2677 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002678 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002679 }
Kevin Rocard12381092018-04-11 09:19:59 -07002680 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002681}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002682
Kevin Rocard12381092018-04-11 09:19:59 -07002683void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2684 const StreamOutHalInterface::SourceMetadata& metadata)
2685{
2686 mOutput->stream->updateSourceMetadata(metadata);
2687};
2688
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002689status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002690{
2691 if (halFrames == NULL || dspFrames == NULL) {
2692 return BAD_VALUE;
2693 }
2694 Mutex::Autolock _l(mLock);
2695 if (initCheck() != NO_ERROR) {
2696 return INVALID_OPERATION;
2697 }
Andy Hung818e7a32016-02-16 18:08:07 -08002698 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002699 *halFrames = framesWritten;
2700
2701 if (isSuspended()) {
2702 // return an estimation of rendered frames when the output is suspended
2703 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002704 *dspFrames = (uint32_t)
2705 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002706 return NO_ERROR;
2707 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002708 status_t status;
2709 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002710 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002711 *dspFrames = (size_t)frames;
2712 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002713 }
2714}
2715
Eric Laurent4c415062016-06-17 16:14:16 -07002716// hasAudioSession_l() must be called with ThreadBase::mLock held
2717uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002718{
Eric Laurent81784c32012-11-19 14:55:58 -08002719 uint32_t result = 0;
2720 if (getEffectChain_l(sessionId) != 0) {
2721 result = EFFECT_SESSION;
2722 }
2723
2724 for (size_t i = 0; i < mTracks.size(); ++i) {
2725 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002726 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002727 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002728 if (track->isFastTrack()) {
2729 result |= FAST_SESSION;
2730 }
Eric Laurent81784c32012-11-19 14:55:58 -08002731 break;
2732 }
2733 }
2734
2735 return result;
2736}
2737
Glenn Kastend848eb42016-03-08 13:42:11 -08002738uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002739{
2740 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2741 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2742 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2743 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2744 }
2745 for (size_t i = 0; i < mTracks.size(); i++) {
2746 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002747 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002748 return AudioSystem::getStrategyForStream(track->streamType());
2749 }
2750 }
2751 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2752}
2753
2754
Phil Burk062e67a2015-02-11 13:40:50 -08002755AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002756{
2757 Mutex::Autolock _l(mLock);
2758 return mOutput;
2759}
2760
Phil Burk062e67a2015-02-11 13:40:50 -08002761AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002762{
2763 Mutex::Autolock _l(mLock);
2764 AudioStreamOut *output = mOutput;
2765 mOutput = NULL;
2766 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2767 // must push a NULL and wait for ack
2768 mOutputSink.clear();
2769 mPipeSink.clear();
2770 mNormalSink.clear();
2771 return output;
2772}
2773
2774// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002775sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002776{
2777 if (mOutput == NULL) {
2778 return NULL;
2779 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002780 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002781}
2782
2783uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2784{
2785 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2786}
2787
2788status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2789{
2790 if (!isValidSyncEvent(event)) {
2791 return BAD_VALUE;
2792 }
2793
2794 Mutex::Autolock _l(mLock);
2795
2796 for (size_t i = 0; i < mTracks.size(); ++i) {
2797 sp<Track> track = mTracks[i];
2798 if (event->triggerSession() == track->sessionId()) {
2799 (void) track->setSyncEvent(event);
2800 return NO_ERROR;
2801 }
2802 }
2803
2804 return NAME_NOT_FOUND;
2805}
2806
2807bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2808{
2809 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2810}
2811
2812void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2813 const Vector< sp<Track> >& tracksToRemove)
2814{
2815 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002816 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002817 for (size_t i = 0 ; i < count ; i++) {
2818 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002819 if (track->isExternalTrack()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07002820 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002821#ifdef ADD_BATTERY_DATA
2822 // to track the speaker usage
2823 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2824#endif
2825 if (track->isTerminated()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07002826 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002827 }
Eric Laurent81784c32012-11-19 14:55:58 -08002828 }
2829 }
2830 }
Eric Laurent81784c32012-11-19 14:55:58 -08002831}
2832
2833void AudioFlinger::PlaybackThread::checkSilentMode_l()
2834{
2835 if (!mMasterMute) {
2836 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002837 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2838 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2839 return;
2840 }
Eric Laurent81784c32012-11-19 14:55:58 -08002841 if (property_get("ro.audio.silent", value, "0") > 0) {
2842 char *endptr;
2843 unsigned long ul = strtoul(value, &endptr, 0);
2844 if (*endptr == '\0' && ul != 0) {
2845 ALOGD("Silence is golden");
2846 // The setprop command will not allow a property to be changed after
2847 // the first time it is set, so we don't have to worry about un-muting.
2848 setMasterMute_l(true);
2849 }
2850 }
2851 }
2852}
2853
2854// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002855ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002856{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002857 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002858 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002859 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002860 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002861
2862 // If an NBAIO sink is present, use it to write the normal mixer's submix
2863 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002864
Andy Hung010a1a12014-03-13 13:57:33 -07002865 const size_t count = mBytesRemaining / mFrameSize;
2866
Simon Wilson2d590962012-11-29 15:18:50 -08002867 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002868 // update the setpoint when AudioFlinger::mScreenState changes
2869 uint32_t screenState = AudioFlinger::mScreenState;
2870 if (screenState != mScreenState) {
2871 mScreenState = screenState;
2872 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2873 if (pipe != NULL) {
2874 pipe->setAvgFrames((mScreenState & 1) ?
2875 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2876 }
2877 }
Andy Hung010a1a12014-03-13 13:57:33 -07002878 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002879 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002880 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002881 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002882#ifdef TEE_SINK
2883 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2884#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002885 } else {
2886 bytesWritten = framesWritten;
2887 }
2888 // otherwise use the HAL / AudioStreamOut directly
2889 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002890 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002891
Eric Laurentbfb1b832013-01-07 09:53:42 -08002892 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002893 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2894 mWriteAckSequence += 2;
2895 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002896 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002897 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002898 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002899 // FIXME We should have an implementation of timestamps for direct output threads.
2900 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002901 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002902
Eric Laurentbfb1b832013-01-07 09:53:42 -08002903 if (mUseAsyncWrite &&
2904 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2905 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002906 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002907 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002908 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002909 }
Eric Laurent81784c32012-11-19 14:55:58 -08002910 }
2911
Eric Laurent81784c32012-11-19 14:55:58 -08002912 mNumWrites++;
2913 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002914 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915 return bytesWritten;
2916}
2917
2918void AudioFlinger::PlaybackThread::threadLoop_drain()
2919{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002920 bool supportsDrain = false;
2921 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002922 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2923 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002924 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2925 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002926 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002927 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002928 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002929 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002930 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002931 }
2932}
2933
2934void AudioFlinger::PlaybackThread::threadLoop_exit()
2935{
Eric Laurent275e8e92014-11-30 15:14:47 -08002936 {
2937 Mutex::Autolock _l(mLock);
2938 for (size_t i = 0; i < mTracks.size(); i++) {
2939 sp<Track> track = mTracks[i];
2940 track->invalidate();
2941 }
Andy Hungdae27702016-10-31 14:01:16 -07002942 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2943 // After we exit there are no more track changes sent to BatteryNotifier
2944 // because that requires an active threadLoop.
2945 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2946 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002947 }
Eric Laurent81784c32012-11-19 14:55:58 -08002948}
2949
2950/*
2951The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002952 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002953 - mActiveSleepTimeUs from activeSleepTimeUs()
2954 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002955 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2956 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002957 - maxPeriod from frame count and sample rate (MIXER only)
2958
2959The parameters that affect these derived values are:
2960 - frame count
2961 - frame size
2962 - sample rate
2963 - device type: A2DP or not
2964 - device latency
2965 - format: PCM or not
2966 - active sleep time
2967 - idle sleep time
2968*/
2969
2970void AudioFlinger::PlaybackThread::cacheParameters_l()
2971{
Andy Hung25c2dac2014-02-27 14:56:00 -08002972 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002973 mActiveSleepTimeUs = activeSleepTimeUs();
2974 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002975
2976 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2977 // truncating audio when going to standby.
2978 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2979 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2980 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2981 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2982 }
2983 }
Eric Laurent81784c32012-11-19 14:55:58 -08002984}
2985
Eric Laurent13084622016-05-17 10:51:49 -07002986bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002987{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002988 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002989 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002990 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002991 size_t size = mTracks.size();
2992 for (size_t i = 0; i < size; i++) {
2993 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002994 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002995 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002996 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002997 }
2998 }
Eric Laurent13084622016-05-17 10:51:49 -07002999 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003000}
3001
Haynes Mathew George05317d22016-05-03 16:34:26 -07003002void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3003{
3004 Mutex::Autolock _l(mLock);
3005 invalidateTracks_l(streamType);
3006}
3007
Eric Laurent81784c32012-11-19 14:55:58 -08003008status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3009{
Glenn Kastend848eb42016-03-08 13:42:11 -08003010 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003011 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003012 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003013 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3014 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3015 &halInBuffer);
3016 if (result != OK) return result;
3017 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003018 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003019 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003020 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003021 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003022 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003023 if (mType != DIRECT) {
3024 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003025 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003026 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003027 &halInBuffer);
3028 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003029#ifdef FLOAT_EFFECT_CHAIN
3030 buffer = halInBuffer->audioBuffer()->f32;
3031#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003032 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003033#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003034 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3035 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003036 }
3037
3038 // Attach all tracks with same session ID to this chain.
3039 for (size_t i = 0; i < mTracks.size(); ++i) {
3040 sp<Track> track = mTracks[i];
3041 if (session == track->sessionId()) {
3042 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3043 buffer);
3044 track->setMainBuffer(buffer);
3045 chain->incTrackCnt();
3046 }
3047 }
3048
3049 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003050 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003051 if (session == track->sessionId()) {
3052 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3053 chain->incActiveTrackCnt();
3054 }
3055 }
3056 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003057 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003058 chain->setInBuffer(halInBuffer);
3059 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003060 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003061 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003062 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3063 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003064 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003065 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003066 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003067 // Effect chain for other sessions are inserted at beginning of effect
3068 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003069 // sessions is not important.
3070 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3071 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3072 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003073 size_t size = mEffectChains.size();
3074 size_t i = 0;
3075 for (i = 0; i < size; i++) {
3076 if (mEffectChains[i]->sessionId() < session) {
3077 break;
3078 }
3079 }
3080 mEffectChains.insertAt(chain, i);
3081 checkSuspendOnAddEffectChain_l(chain);
3082
3083 return NO_ERROR;
3084}
3085
3086size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3087{
Glenn Kastend848eb42016-03-08 13:42:11 -08003088 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003089
3090 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3091
3092 for (size_t i = 0; i < mEffectChains.size(); i++) {
3093 if (chain == mEffectChains[i]) {
3094 mEffectChains.removeAt(i);
3095 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003096 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003097 if (session == track->sessionId()) {
3098 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3099 chain.get(), session);
3100 chain->decActiveTrackCnt();
3101 }
3102 }
3103
3104 // detach all tracks with same session ID from this chain
3105 for (size_t i = 0; i < mTracks.size(); ++i) {
3106 sp<Track> track = mTracks[i];
3107 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003108 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003109 chain->decTrackCnt();
3110 }
3111 }
3112 break;
3113 }
3114 }
3115 return mEffectChains.size();
3116}
3117
3118status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003119 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003120{
3121 Mutex::Autolock _l(mLock);
3122 return attachAuxEffect_l(track, EffectId);
3123}
3124
3125status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003126 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003127{
3128 status_t status = NO_ERROR;
3129
3130 if (EffectId == 0) {
3131 track->setAuxBuffer(0, NULL);
3132 } else {
3133 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3134 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3135 if (effect != 0) {
3136 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3137 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3138 } else {
3139 status = INVALID_OPERATION;
3140 }
3141 } else {
3142 status = BAD_VALUE;
3143 }
3144 }
3145 return status;
3146}
3147
3148void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3149{
3150 for (size_t i = 0; i < mTracks.size(); ++i) {
3151 sp<Track> track = mTracks[i];
3152 if (track->auxEffectId() == effectId) {
3153 attachAuxEffect_l(track, 0);
3154 }
3155 }
3156}
3157
3158bool AudioFlinger::PlaybackThread::threadLoop()
3159{
Glenn Kasten388d5712017-04-07 14:38:41 -07003160 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003161
Eric Laurent81784c32012-11-19 14:55:58 -08003162 Vector< sp<Track> > tracksToRemove;
3163
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003164 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003165 nsecs_t lastWriteFinished = -1; // time last server write completed
3166 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003167
3168 // MIXER
3169 nsecs_t lastWarning = 0;
3170
3171 // DUPLICATING
3172 // FIXME could this be made local to while loop?
3173 writeFrames = 0;
3174
3175 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003176 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003177
3178 if (mType == MIXER) {
3179 sleepTimeShift = 0;
3180 }
3181
3182 CpuStats cpuStats;
3183 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3184
3185 acquireWakeLock();
3186
Glenn Kasteneef598c2017-04-03 14:41:13 -07003187 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3188 // thread associated with this PlaybackThread.
3189 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3190 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003191 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3192 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003193 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003194 const char *logString = NULL;
3195
rago1bb90822017-05-02 18:31:48 -07003196 // Estimated time for next buffer to be written to hal. This is used only on
3197 // suspended mode (for now) to help schedule the wait time until next iteration.
3198 nsecs_t timeLoopNextNs = 0;
3199
Eric Laurent664539d2013-09-23 18:24:31 -07003200 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003201
Andy Hungf3234512018-07-03 14:51:47 -07003202 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3203 // TODO: add confirmation checks:
3204 // 1) DIRECT threads and linear PCM format really resets to 0?
3205 // 2) Is frame count really valid if not linear pcm?
3206 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3207 if (mType == OFFLOAD || mType == DIRECT) {
3208 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3209 }
3210
Eric Laurent81784c32012-11-19 14:55:58 -08003211 while (!exitPending())
3212 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003213 // Log merge requests are performed during AudioFlinger binder transactions, but
3214 // that does not cover audio playback. It's requested here for that reason.
3215 mAudioFlinger->requestLogMerge();
3216
Eric Laurent81784c32012-11-19 14:55:58 -08003217 cpuStats.sample(myName);
3218
3219 Vector< sp<EffectChain> > effectChains;
3220
Eric Laurent81784c32012-11-19 14:55:58 -08003221 { // scope for mLock
3222
3223 Mutex::Autolock _l(mLock);
3224
Eric Laurent021cf962014-05-13 10:18:14 -07003225 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003226
Glenn Kasteneef598c2017-04-03 14:41:13 -07003227 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003228 if (logString != NULL) {
3229 mNBLogWriter->logTimestamp();
3230 mNBLogWriter->log(logString);
3231 logString = NULL;
3232 }
3233
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003234 // Collect timestamp statistics for the Playback Thread types that support it.
3235 if (mType == MIXER
3236 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003237 || mType == DIRECT
3238 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003239 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003240 // and associate with the sink frames written out. We need
3241 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003242 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003243 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003244 if (mStandby) {
3245 mTimestampVerifier.discontinuity();
3246 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3247 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3248 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3249 mSampleRate);
Andy Hung818e7a32016-02-16 18:08:07 -08003250 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003251 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003252
3253 // We keep track of the last valid kernel position in case we are in underrun
3254 // and the normal mixer period is the same as the fast mixer period, or there
3255 // is some error from the HAL.
3256 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3257 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3258 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3259 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3260 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3261
3262 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3263 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3264 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3265 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003266 }
3267
3268 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3269 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003270 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003271 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003272 }
3273
Andy Hung818e7a32016-02-16 18:08:07 -08003274 // copy over kernel info
3275 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003276 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3277 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003278 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3279 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003280 } else {
3281 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003282 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003283
Andy Hungc54b1ff2016-02-23 14:07:07 -08003284 // mFramesWritten for non-offloaded tracks are contiguous
3285 // even after standby() is called. This is useful for the track frame
3286 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003287 bool serverLocationUpdate = false;
3288 if (mFramesWritten != lastFramesWritten) {
3289 serverLocationUpdate = true;
3290 lastFramesWritten = mFramesWritten;
3291 }
3292 // Only update timestamps if there is a meaningful change.
3293 // Either the kernel timestamp must be valid or we have written something.
3294 if (kernelLocationUpdate || serverLocationUpdate) {
3295 if (serverLocationUpdate) {
3296 // use the time before we called the HAL write - it is a bit more accurate
3297 // to when the server last read data than the current time here.
3298 //
3299 // If we haven't written anything, mLastWriteTime will be -1
3300 // and we use systemTime().
3301 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3302 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3303 ? systemTime() : mLastWriteTime;
3304 }
Andy Hungdae27702016-10-31 14:01:16 -07003305
3306 for (const sp<Track> &t : mActiveTracks) {
3307 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003308 t->updateTrackFrameInfo(
3309 t->mAudioTrackServerProxy->framesReleased(),
3310 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003311 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003312 mTimestamp);
3313 }
Andy Hunge10393e2015-06-12 13:59:33 -07003314 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003315 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003316 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003317#if 0
3318 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003319 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003320 timespec ts;
3321 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003322 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003323 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003324 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003325 }
3326 ++z;
3327#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003328 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003329 if (mSignalPending) {
3330 // A signal was raised while we were unlocked
3331 mSignalPending = false;
3332 } else if (waitingAsyncCallback_l()) {
3333 if (exitPending()) {
3334 break;
3335 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003336 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003337 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003338 releaseWakeLock_l();
3339 released = true;
3340 }
Andy Hung10cbff12017-02-21 17:30:14 -08003341
3342 const int64_t waitNs = computeWaitTimeNs_l();
3343 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3344 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3345 if (status == TIMED_OUT) {
3346 mSignalPending = true; // if timeout recheck everything
3347 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003348 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003349 if (released) {
3350 acquireWakeLock_l();
3351 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003352 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3353 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003354
3355 continue;
3356 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003357 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003358 isSuspended()) {
3359 // put audio hardware into standby after short delay
3360 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003361
3362 threadLoop_standby();
3363
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003364 // This is where we go into standby
3365 if (!mStandby) {
3366 LOG_AUDIO_STATE();
3367 }
Eric Laurent81784c32012-11-19 14:55:58 -08003368 mStandby = true;
3369 }
3370
3371 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3372 // we're about to wait, flush the binder command buffer
3373 IPCThreadState::self()->flushCommands();
3374
3375 clearOutputTracks();
3376
3377 if (exitPending()) {
3378 break;
3379 }
3380
3381 releaseWakeLock_l();
3382 // wait until we have something to do...
3383 ALOGV("%s going to sleep", myName.string());
3384 mWaitWorkCV.wait(mLock);
3385 ALOGV("%s waking up", myName.string());
3386 acquireWakeLock_l();
3387
3388 mMixerStatus = MIXER_IDLE;
3389 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3390 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003391 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003392 checkSilentMode_l();
3393
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003394 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3395 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003396 if (mType == MIXER) {
3397 sleepTimeShift = 0;
3398 }
3399
3400 continue;
3401 }
3402 }
Eric Laurent81784c32012-11-19 14:55:58 -08003403 // mMixerStatusIgnoringFastTracks is also updated internally
3404 mMixerStatus = prepareTracks_l(&tracksToRemove);
3405
Andy Hungdae27702016-10-31 14:01:16 -07003406 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003407
Kevin Rocard069c2712018-03-29 19:09:14 -07003408 updateMetadata_l();
3409
Eric Laurent81784c32012-11-19 14:55:58 -08003410 // prevent any changes in effect chain list and in each effect chain
3411 // during mixing and effect process as the audio buffers could be deleted
3412 // or modified if an effect is created or deleted
3413 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003414 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003415
Eric Laurentbfb1b832013-01-07 09:53:42 -08003416 if (mBytesRemaining == 0) {
3417 mCurrentWriteLength = 0;
3418 if (mMixerStatus == MIXER_TRACKS_READY) {
3419 // threadLoop_mix() sets mCurrentWriteLength
3420 threadLoop_mix();
3421 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3422 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003423 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003424 // must be written to HAL
3425 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003426 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003427 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003428 }
3429 }
Andy Hung98ef9782014-03-04 14:46:50 -08003430 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003431 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003432 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3433 // or mSinkBuffer (if there are no effects).
3434 //
3435 // This is done pre-effects computation; if effects change to
3436 // support higher precision, this needs to move.
3437 //
3438 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003439 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003440 if (mMixerBufferValid) {
3441 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3442 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3443
Andy Hung2ddee192015-12-18 17:34:44 -08003444 // mono blend occurs for mixer threads only (not direct or offloaded)
3445 // and is handled here if we're going directly to the sink.
3446 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003447 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3448 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003449 }
3450
Andy Hung98ef9782014-03-04 14:46:50 -08003451 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3452 mNormalFrameCount * mChannelCount);
3453 }
3454
Eric Laurentbfb1b832013-01-07 09:53:42 -08003455 mBytesRemaining = mCurrentWriteLength;
3456 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003457 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3458 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3459 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3460 mBytesWritten += mBytesRemaining;
3461 mFramesWritten += framesRemaining;
3462 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003463 mBytesRemaining = 0;
3464 }
Eric Laurent81784c32012-11-19 14:55:58 -08003465
Eric Laurentbfb1b832013-01-07 09:53:42 -08003466 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003467 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003468 for (size_t i = 0; i < effectChains.size(); i ++) {
3469 effectChains[i]->process_l();
3470 }
Eric Laurent81784c32012-11-19 14:55:58 -08003471 }
3472 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003473 // Process effect chains for offloaded thread even if no audio
3474 // was read from audio track: process only updates effect state
3475 // and thus does have to be synchronized with audio writes but may have
3476 // to be called while waiting for async write callback
3477 if (mType == OFFLOAD) {
3478 for (size_t i = 0; i < effectChains.size(); i ++) {
3479 effectChains[i]->process_l();
3480 }
3481 }
Eric Laurent81784c32012-11-19 14:55:58 -08003482
Andy Hung98ef9782014-03-04 14:46:50 -08003483 // Only if the Effects buffer is enabled and there is data in the
3484 // Effects buffer (buffer valid), we need to
3485 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003486 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003487 if (mEffectBufferValid) {
3488 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003489
3490 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003491 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3492 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003493 }
3494
Andy Hung98ef9782014-03-04 14:46:50 -08003495 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3496 mNormalFrameCount * mChannelCount);
3497 }
3498
Eric Laurent81784c32012-11-19 14:55:58 -08003499 // enable changes in effect chain
3500 unlockEffectChains(effectChains);
3501
Eric Laurentbfb1b832013-01-07 09:53:42 -08003502 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003503 // mSleepTimeUs == 0 means we must write to audio hardware
3504 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003505 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003506 // We save lastWriteFinished here, as previousLastWriteFinished,
3507 // for throttling. On thread start, previousLastWriteFinished will be
3508 // set to -1, which properly results in no throttling after the first write.
3509 nsecs_t previousLastWriteFinished = lastWriteFinished;
3510 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003511 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003512 // FIXME rewrite to reduce number of system calls
3513 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003514 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003515 lastWriteFinished = systemTime();
3516 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003517 if (ret < 0) {
3518 mBytesRemaining = 0;
3519 } else {
3520 mBytesWritten += ret;
3521 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003522 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003523 }
3524 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3525 (mMixerStatus == MIXER_DRAIN_ALL)) {
3526 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003527 }
Andy Hung08fb1742015-05-31 23:22:10 -07003528 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003529 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003530 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003531 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003532 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003533 ATRACE_NAME("underrun");
3534 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003535 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003536 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003537 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003538 }
Andy Hung08fb1742015-05-31 23:22:10 -07003539
3540 if (mThreadThrottle
3541 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3542 && ret > 0) { // we wrote something
3543 // Limit MixerThread data processing to no more than twice the
3544 // expected processing rate.
3545 //
3546 // This helps prevent underruns with NuPlayer and other applications
3547 // which may set up buffers that are close to the minimum size, or use
3548 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3549 //
3550 // The throttle smooths out sudden large data drains from the device,
3551 // e.g. when it comes out of standby, which often causes problems with
3552 // (1) mixer threads without a fast mixer (which has its own warm-up)
3553 // (2) minimum buffer sized tracks (even if the track is full,
3554 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003555 //
3556 // Total time spent in last processing cycle equals time spent in
3557 // 1. threadLoop_write, as well as time spent in
3558 // 2. threadLoop_mix (significant for heavy mixing, especially
3559 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003560
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003561 // it's OK if deltaMs (and deltaNs) is an overestimate.
3562 nsecs_t deltaNs;
3563 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3564 __builtin_sub_overflow(
3565 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3566 const int32_t deltaMs = deltaNs / 1000000;
3567
Ivan Lozanoea04d392017-11-07 14:37:07 -08003568 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003569 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3570 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003571 // notify of throttle start on verbose log
3572 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3573 "mixer(%p) throttle begin:"
3574 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003575 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003576 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003577 // Throttle must be attributed to the previous mixer loop's write time
3578 // to allow back-to-back throttling.
3579 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003580 } else {
3581 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3582 if (diff > 0) {
3583 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003584 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003585 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3586 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003587 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003588 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3589 }
Andy Hung08fb1742015-05-31 23:22:10 -07003590 }
3591 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003592 }
Eric Laurent81784c32012-11-19 14:55:58 -08003593
Eric Laurentbfb1b832013-01-07 09:53:42 -08003594 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003595 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003596 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003597 // suspended requires accurate metering of sleep time.
3598 if (isSuspended()) {
3599 // advance by expected sleepTime
3600 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3601 const nsecs_t nowNs = systemTime();
3602
3603 // compute expected next time vs current time.
3604 // (negative deltas are treated as delays).
3605 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3606 if (deltaNs < -kMaxNextBufferDelayNs) {
3607 // Delays longer than the max allowed trigger a reset.
3608 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3609 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3610 timeLoopNextNs = nowNs + deltaNs;
3611 } else if (deltaNs < 0) {
3612 // Delays within the max delay allowed: zero the delta/sleepTime
3613 // to help the system catch up in the next iteration(s)
3614 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3615 deltaNs = 0;
3616 }
3617 // update sleep time (which is >= 0)
3618 mSleepTimeUs = deltaNs / 1000;
3619 }
Eric Laurente93cc032016-05-05 10:15:10 -07003620 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3621 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003622 }
Glenn Kastene7754022014-10-31 12:11:26 -07003623 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003624 }
Eric Laurent81784c32012-11-19 14:55:58 -08003625 }
3626
3627 // Finally let go of removed track(s), without the lock held
3628 // since we can't guarantee the destructors won't acquire that
3629 // same lock. This will also mutate and push a new fast mixer state.
3630 threadLoop_removeTracks(tracksToRemove);
3631 tracksToRemove.clear();
3632
3633 // FIXME I don't understand the need for this here;
3634 // it was in the original code but maybe the
3635 // assignment in saveOutputTracks() makes this unnecessary?
3636 clearOutputTracks();
3637
3638 // Effect chains will be actually deleted here if they were removed from
3639 // mEffectChains list during mixing or effects processing
3640 effectChains.clear();
3641
3642 // FIXME Note that the above .clear() is no longer necessary since effectChains
3643 // is now local to this block, but will keep it for now (at least until merge done).
3644 }
3645
Eric Laurentbfb1b832013-01-07 09:53:42 -08003646 threadLoop_exit();
3647
Eric Laurentcf817a22014-08-04 20:36:31 -07003648 if (!mStandby) {
3649 threadLoop_standby();
3650 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003651 }
3652
3653 releaseWakeLock();
3654
3655 ALOGV("Thread %p type %d exiting", this, mType);
3656 return false;
3657}
3658
Eric Laurentbfb1b832013-01-07 09:53:42 -08003659// removeTracks_l() must be called with ThreadBase::mLock held
3660void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3661{
3662 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003663 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003664 for (size_t i=0 ; i<count ; i++) {
3665 const sp<Track>& track = tracksToRemove.itemAt(i);
3666 mActiveTracks.remove(track);
3667 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3668 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3669 if (chain != 0) {
3670 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3671 track->sessionId());
3672 chain->decActiveTrackCnt();
3673 }
3674 if (track->isTerminated()) {
3675 removeTrack_l(track);
3676 }
3677 }
3678 }
3679
3680}
Eric Laurent81784c32012-11-19 14:55:58 -08003681
Eric Laurentaccc1472013-09-20 09:36:34 -07003682status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3683{
3684 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003685 ExtendedTimestamp ets;
3686 status_t status = mNormalSink->getTimestamp(ets);
3687 if (status == NO_ERROR) {
3688 status = ets.getBestTimestamp(&timestamp);
3689 }
3690 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003691 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003692 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003693 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003694 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003695 timestamp.mPosition = (uint32_t)position64;
3696 return NO_ERROR;
3697 }
3698 }
3699 return INVALID_OPERATION;
3700}
Eric Laurent1c333e22014-05-20 10:48:17 -07003701
Eric Laurent054d9d32015-04-24 08:48:48 -07003702status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3703 audio_patch_handle_t *handle)
3704{
Andy Hungf60abce2016-08-26 11:37:54 -07003705 status_t status;
3706 if (property_get_bool("af.patch_park", false /* default_value */)) {
3707 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3708 // or if HAL does not properly lock against access.
3709 AutoPark<FastMixer> park(mFastMixer);
3710 status = PlaybackThread::createAudioPatch_l(patch, handle);
3711 } else {
3712 status = PlaybackThread::createAudioPatch_l(patch, handle);
3713 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003714 return status;
3715}
3716
Eric Laurent1c333e22014-05-20 10:48:17 -07003717status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3718 audio_patch_handle_t *handle)
3719{
3720 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003721
3722 // store new device and send to effects
3723 audio_devices_t type = AUDIO_DEVICE_NONE;
3724 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3725 type |= patch->sinks[i].ext.device.type;
3726 }
3727
3728#ifdef ADD_BATTERY_DATA
3729 // when changing the audio output device, call addBatteryData to notify
3730 // the change
3731 if (mOutDevice != type) {
3732 uint32_t params = 0;
3733 // check whether speaker is on
3734 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3735 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003736 }
3737
Eric Laurent054d9d32015-04-24 08:48:48 -07003738 audio_devices_t deviceWithoutSpeaker
3739 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3740 // check if any other device (except speaker) is on
3741 if (type & deviceWithoutSpeaker) {
3742 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3743 }
3744
3745 if (params != 0) {
3746 addBatteryData(params);
3747 }
3748 }
3749#endif
3750
3751 for (size_t i = 0; i < mEffectChains.size(); i++) {
3752 mEffectChains[i]->setDevice_l(type);
3753 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003754
3755 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3756 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3757 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003758 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003759 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003760
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003761 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003762 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3763 status = hwDevice->createAudioPatch(patch->num_sources,
3764 patch->sources,
3765 patch->num_sinks,
3766 patch->sinks,
3767 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003768 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003769 char *address;
3770 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3771 //FIXME: we only support address on first sink with HAL version < 3.0
3772 address = audio_device_address_to_parameter(
3773 patch->sinks[0].ext.device.type,
3774 patch->sinks[0].ext.device.address);
3775 } else {
3776 address = (char *)calloc(1, 1);
3777 }
3778 AudioParameter param = AudioParameter(String8(address));
3779 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003780 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003781 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003782 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003783 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003784 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003785 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003786 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3787 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003788 return status;
3789}
3790
Eric Laurent054d9d32015-04-24 08:48:48 -07003791status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3792{
Andy Hungf60abce2016-08-26 11:37:54 -07003793 status_t status;
3794 if (property_get_bool("af.patch_park", false /* default_value */)) {
3795 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3796 // or if HAL does not properly lock against access.
3797 AutoPark<FastMixer> park(mFastMixer);
3798 status = PlaybackThread::releaseAudioPatch_l(handle);
3799 } else {
3800 status = PlaybackThread::releaseAudioPatch_l(handle);
3801 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003802 return status;
3803}
3804
Eric Laurent1c333e22014-05-20 10:48:17 -07003805status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3806{
3807 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003808
3809 mOutDevice = AUDIO_DEVICE_NONE;
3810
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003811 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003812 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3813 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003814 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003815 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003816 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003817 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003818 }
3819 return status;
3820}
3821
Eric Laurent83b88082014-06-20 18:31:16 -07003822void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3823{
3824 Mutex::Autolock _l(mLock);
3825 mTracks.add(track);
3826}
3827
3828void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3829{
3830 Mutex::Autolock _l(mLock);
3831 destroyTrack_l(track);
3832}
3833
Mikhail Naganovdc769682018-05-04 15:34:08 -07003834void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003835{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003836 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003837 config->role = AUDIO_PORT_ROLE_SOURCE;
3838 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3839 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003840 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3841 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3842 config->flags.output = mOutput->flags;
3843 }
Eric Laurent83b88082014-06-20 18:31:16 -07003844}
3845
Eric Laurent81784c32012-11-19 14:55:58 -08003846// ----------------------------------------------------------------------------
3847
3848AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003849 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3850 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003851 // mAudioMixer below
3852 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003853 mFastMixerFutex(0),
3854 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003855 // mOutputSink below
3856 // mPipeSink below
3857 // mNormalSink below
3858{
3859 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003860 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003861 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003862 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3863 mNormalFrameCount);
3864 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3865
Andy Hungfbfc3952015-01-15 13:33:51 -08003866 if (type == DUPLICATING) {
3867 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3868 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3869 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3870 return;
3871 }
Eric Laurent81784c32012-11-19 14:55:58 -08003872 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003873 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003874 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003875 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003876#if !LOG_NDEBUG
3877 ssize_t index =
3878#else
3879 (void)
3880#endif
3881 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003882 ALOG_ASSERT(index == 0);
3883
3884 // initialize fast mixer depending on configuration
3885 bool initFastMixer;
3886 switch (kUseFastMixer) {
3887 case FastMixer_Never:
3888 initFastMixer = false;
3889 break;
3890 case FastMixer_Always:
3891 initFastMixer = true;
3892 break;
3893 case FastMixer_Static:
3894 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003895 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3896 // where the period is less than an experimentally determined threshold that can be
3897 // scheduled reliably with CFS. However, the BT A2DP HAL is
3898 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3899 initFastMixer = mFrameCount < mNormalFrameCount
3900 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003901 break;
3902 }
Andy Hungfda69402017-02-15 14:33:12 -08003903 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3904 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3905 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003906 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003907 audio_format_t fastMixerFormat;
3908 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3909 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3910 } else {
3911 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3912 }
3913 if (mFormat != fastMixerFormat) {
3914 // change our Sink format to accept our intermediate precision
3915 mFormat = fastMixerFormat;
3916 free(mSinkBuffer);
3917 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3918 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3919 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3920 }
Eric Laurent81784c32012-11-19 14:55:58 -08003921
3922 // create a MonoPipe to connect our submix to FastMixer
3923 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07003924
Andy Hung1258c1a2014-05-23 21:22:17 -07003925 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003926 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003927 format.mFormat = fastMixerFormat;
3928 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3929
Eric Laurent81784c32012-11-19 14:55:58 -08003930 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3931 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3932 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3933 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3934 const NBAIO_Format offers[1] = {format};
3935 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07003936#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003937 ssize_t index =
3938#else
3939 (void)
3940#endif
3941 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003942 ALOG_ASSERT(index == 0);
3943 monoPipe->setAvgFrames((mScreenState & 1) ?
3944 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3945 mPipeSink = monoPipe;
3946
Eric Laurent81784c32012-11-19 14:55:58 -08003947 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07003948 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003949 FastMixerStateQueue *sq = mFastMixer->sq();
3950#ifdef STATE_QUEUE_DUMP
3951 sq->setObserverDump(&mStateQueueObserverDump);
3952 sq->setMutatorDump(&mStateQueueMutatorDump);
3953#endif
3954 FastMixerState *state = sq->begin();
3955 FastTrack *fastTrack = &state->mFastTracks[0];
3956 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3957 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3958 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003959 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3960 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003961 fastTrack->mGeneration++;
3962 state->mFastTracksGen++;
3963 state->mTrackMask = 1;
3964 // fast mixer will use the HAL output sink
3965 state->mOutputSink = mOutputSink.get();
3966 state->mOutputSinkGen++;
3967 state->mFrameCount = mFrameCount;
3968 state->mCommand = FastMixerState::COLD_IDLE;
3969 // already done in constructor initialization list
3970 //mFastMixerFutex = 0;
3971 state->mColdFutexAddr = &mFastMixerFutex;
3972 state->mColdGen++;
3973 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08003974 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3975 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003976 sq->end();
3977 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3978
3979 // start the fast mixer
3980 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3981 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003982 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003983 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003984
3985#ifdef AUDIO_WATCHDOG
3986 // create and start the watchdog
3987 mAudioWatchdog = new AudioWatchdog();
3988 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3989 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3990 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003991 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003992#endif
Andy Hung8946a282018-04-19 20:04:56 -07003993 } else {
3994#ifdef TEE_SINK
3995 // Only use the MixerThread tee if there is no FastMixer.
3996 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
3997 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
3998#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003999 }
4000
4001 switch (kUseFastMixer) {
4002 case FastMixer_Never:
4003 case FastMixer_Dynamic:
4004 mNormalSink = mOutputSink;
4005 break;
4006 case FastMixer_Always:
4007 mNormalSink = mPipeSink;
4008 break;
4009 case FastMixer_Static:
4010 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4011 break;
4012 }
4013}
4014
4015AudioFlinger::MixerThread::~MixerThread()
4016{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004017 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004018 FastMixerStateQueue *sq = mFastMixer->sq();
4019 FastMixerState *state = sq->begin();
4020 if (state->mCommand == FastMixerState::COLD_IDLE) {
4021 int32_t old = android_atomic_inc(&mFastMixerFutex);
4022 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004023 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004024 }
4025 }
4026 state->mCommand = FastMixerState::EXIT;
4027 sq->end();
4028 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4029 mFastMixer->join();
4030 // Though the fast mixer thread has exited, it's state queue is still valid.
4031 // We'll use that extract the final state which contains one remaining fast track
4032 // corresponding to our sub-mix.
4033 state = sq->begin();
4034 ALOG_ASSERT(state->mTrackMask == 1);
4035 FastTrack *fastTrack = &state->mFastTracks[0];
4036 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4037 delete fastTrack->mBufferProvider;
4038 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004039 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004040#ifdef AUDIO_WATCHDOG
4041 if (mAudioWatchdog != 0) {
4042 mAudioWatchdog->requestExit();
4043 mAudioWatchdog->requestExitAndWait();
4044 mAudioWatchdog.clear();
4045 }
4046#endif
4047 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004048 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004049 delete mAudioMixer;
4050}
4051
4052
4053uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4054{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004055 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004056 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4057 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4058 }
4059 return latency;
4060}
4061
4062
4063void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4064{
4065 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4066}
4067
Eric Laurentbfb1b832013-01-07 09:53:42 -08004068ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004069{
4070 // FIXME we should only do one push per cycle; confirm this is true
4071 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004072 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004073 FastMixerStateQueue *sq = mFastMixer->sq();
4074 FastMixerState *state = sq->begin();
4075 if (state->mCommand != FastMixerState::MIX_WRITE &&
4076 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4077 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004078
4079 // FIXME workaround for first HAL write being CPU bound on some devices
4080 ATRACE_BEGIN("write");
4081 mOutput->write((char *)mSinkBuffer, 0);
4082 ATRACE_END();
4083
Eric Laurent81784c32012-11-19 14:55:58 -08004084 int32_t old = android_atomic_inc(&mFastMixerFutex);
4085 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004086 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004087 }
4088#ifdef AUDIO_WATCHDOG
4089 if (mAudioWatchdog != 0) {
4090 mAudioWatchdog->resume();
4091 }
4092#endif
4093 }
4094 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004095#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004096 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004097 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004098#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004099 sq->end();
4100 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4101 if (kUseFastMixer == FastMixer_Dynamic) {
4102 mNormalSink = mPipeSink;
4103 }
4104 } else {
4105 sq->end(false /*didModify*/);
4106 }
4107 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004108 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004109}
4110
4111void AudioFlinger::MixerThread::threadLoop_standby()
4112{
4113 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004114 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004115 FastMixerStateQueue *sq = mFastMixer->sq();
4116 FastMixerState *state = sq->begin();
4117 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004118 // Report any frames trapped in the Monopipe
4119 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4120 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4121 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4122 "monoPipeWritten:%lld monoPipeLeft:%lld",
4123 (long long)mFramesWritten, (long long)mSuspendedFrames,
4124 (long long)mPipeSink->framesWritten(), pipeFrames);
4125 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4126
Eric Laurent81784c32012-11-19 14:55:58 -08004127 state->mCommand = FastMixerState::COLD_IDLE;
4128 state->mColdFutexAddr = &mFastMixerFutex;
4129 state->mColdGen++;
4130 mFastMixerFutex = 0;
4131 sq->end();
4132 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4133 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4134 if (kUseFastMixer == FastMixer_Dynamic) {
4135 mNormalSink = mOutputSink;
4136 }
4137#ifdef AUDIO_WATCHDOG
4138 if (mAudioWatchdog != 0) {
4139 mAudioWatchdog->pause();
4140 }
4141#endif
4142 } else {
4143 sq->end(false /*didModify*/);
4144 }
4145 }
4146 PlaybackThread::threadLoop_standby();
4147}
4148
Eric Laurentbfb1b832013-01-07 09:53:42 -08004149bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4150{
4151 return false;
4152}
4153
4154bool AudioFlinger::PlaybackThread::shouldStandby_l()
4155{
4156 return !mStandby;
4157}
4158
4159bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4160{
4161 Mutex::Autolock _l(mLock);
4162 return waitingAsyncCallback_l();
4163}
4164
Eric Laurent81784c32012-11-19 14:55:58 -08004165// shared by MIXER and DIRECT, overridden by DUPLICATING
4166void AudioFlinger::PlaybackThread::threadLoop_standby()
4167{
4168 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004169 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004170 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004171 // discard any pending drain or write ack by incrementing sequence
4172 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4173 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004174 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004175 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4176 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004177 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004178 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004179}
4180
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004181void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4182{
4183 ALOGV("signal playback thread");
4184 broadcast_l();
4185}
4186
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004187void AudioFlinger::PlaybackThread::onAsyncError()
4188{
4189 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4190 invalidateTracks((audio_stream_type_t)i);
4191 }
4192}
4193
Eric Laurent81784c32012-11-19 14:55:58 -08004194void AudioFlinger::MixerThread::threadLoop_mix()
4195{
Eric Laurent81784c32012-11-19 14:55:58 -08004196 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004197 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004198 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004199 // increase sleep time progressively when application underrun condition clears.
4200 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4201 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4202 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004203 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004204 sleepTimeShift--;
4205 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004206 mSleepTimeUs = 0;
4207 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004208 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004209
Eric Laurent81784c32012-11-19 14:55:58 -08004210}
4211
4212void AudioFlinger::MixerThread::threadLoop_sleepTime()
4213{
4214 // If no tracks are ready, sleep once for the duration of an output
4215 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004216 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004217 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004218 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4219 // Using the Monopipe availableToWrite, we estimate the
4220 // sleep time to retry for more data (before we underrun).
4221 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4222 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4223 const size_t pipeFrames = monoPipe->maxFrames();
4224 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4225 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4226 const size_t framesDelay = std::min(
4227 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4228 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4229 pipeFrames, framesLeft, framesDelay);
4230 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4231 } else {
4232 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4233 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4234 mSleepTimeUs = kMinThreadSleepTimeUs;
4235 }
4236 // reduce sleep time in case of consecutive application underruns to avoid
4237 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4238 // duration we would end up writing less data than needed by the audio HAL if
4239 // the condition persists.
4240 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4241 sleepTimeShift++;
4242 }
Eric Laurent81784c32012-11-19 14:55:58 -08004243 }
4244 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004245 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004246 }
4247 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004248 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4249 // before effects processing or output.
4250 if (mMixerBufferValid) {
4251 memset(mMixerBuffer, 0, mMixerBufferSize);
4252 } else {
4253 memset(mSinkBuffer, 0, mSinkBufferSize);
4254 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004255 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004256 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4257 "anticipated start");
4258 }
4259 // TODO add standby time extension fct of effect tail
4260}
4261
4262// prepareTracks_l() must be called with ThreadBase::mLock held
4263AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4264 Vector< sp<Track> > *tracksToRemove)
4265{
Andy Hung1bc088a2018-02-09 15:57:31 -08004266 // clean up deleted track names in AudioMixer before allocating new tracks
4267 (void)mTracks.processDeletedTrackNames([this](int name) {
4268 // for each name, destroy it in the AudioMixer
4269 if (mAudioMixer->exists(name)) {
4270 mAudioMixer->destroy(name);
4271 }
4272 });
4273 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004274
4275 mixer_state mixerStatus = MIXER_IDLE;
4276 // find out which tracks need to be processed
4277 size_t count = mActiveTracks.size();
4278 size_t mixedTracks = 0;
4279 size_t tracksWithEffect = 0;
4280 // counts only _active_ fast tracks
4281 size_t fastTracks = 0;
4282 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4283
4284 float masterVolume = mMasterVolume;
4285 bool masterMute = mMasterMute;
4286
4287 if (masterMute) {
4288 masterVolume = 0;
4289 }
4290 // Delegate master volume control to effect in output mix effect chain if needed
4291 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4292 if (chain != 0) {
4293 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4294 chain->setVolume_l(&v, &v);
4295 masterVolume = (float)((v + (1 << 23)) >> 24);
4296 chain.clear();
4297 }
4298
4299 // prepare a new state to push
4300 FastMixerStateQueue *sq = NULL;
4301 FastMixerState *state = NULL;
4302 bool didModify = false;
4303 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004304 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004305 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004306 sq = mFastMixer->sq();
4307 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004308 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004309 }
4310
Andy Hung69aed5f2014-02-25 17:24:40 -08004311 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004312 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004313
Andy Hungbd3b2b02018-05-21 10:53:11 -07004314 // DeferredOperations handles statistics after setting mixerStatus.
4315 class DeferredOperations {
4316 public:
4317 DeferredOperations(mixer_state *mixerStatus)
4318 : mMixerStatus(mixerStatus) { }
4319
4320 // when leaving scope, tally frames properly.
4321 ~DeferredOperations() {
4322 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4323 // because that is when the underrun occurs.
4324 // We do not distinguish between FastTracks and NormalTracks here.
4325 if (*mMixerStatus == MIXER_TRACKS_READY) {
4326 for (const auto &underrun : mUnderrunFrames) {
4327 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4328 underrun.second);
4329 }
4330 }
4331 }
4332
4333 // tallyUnderrunFrames() is called to update the track counters
4334 // with the number of underrun frames for a particular mixer period.
4335 // We defer tallying until we know the final mixer status.
4336 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4337 mUnderrunFrames.emplace_back(track, underrunFrames);
4338 }
4339
4340 private:
4341 const mixer_state * const mMixerStatus;
4342 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4343 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4344
Eric Laurent81784c32012-11-19 14:55:58 -08004345 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004346 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004347
4348 // this const just means the local variable doesn't change
4349 Track* const track = t.get();
4350
4351 // process fast tracks
4352 if (track->isFastTrack()) {
4353
4354 // It's theoretically possible (though unlikely) for a fast track to be created
4355 // and then removed within the same normal mix cycle. This is not a problem, as
4356 // the track never becomes active so it's fast mixer slot is never touched.
4357 // The converse, of removing an (active) track and then creating a new track
4358 // at the identical fast mixer slot within the same normal mix cycle,
4359 // is impossible because the slot isn't marked available until the end of each cycle.
4360 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004361 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004362 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4363 FastTrack *fastTrack = &state->mFastTracks[j];
4364
4365 // Determine whether the track is currently in underrun condition,
4366 // and whether it had a recent underrun.
4367 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4368 FastTrackUnderruns underruns = ftDump->mUnderruns;
4369 uint32_t recentFull = (underruns.mBitFields.mFull -
4370 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4371 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4372 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4373 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4374 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4375 uint32_t recentUnderruns = recentPartial + recentEmpty;
4376 track->mObservedUnderruns = underruns;
4377 // don't count underruns that occur while stopping or pausing
4378 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004379 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004380 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4381 recentUnderruns > 0) {
4382 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004383 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004384 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004385 // Immediately account for FastTrack underruns.
4386 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004387
4388 // This is similar to the state machine for normal tracks,
4389 // with a few modifications for fast tracks.
4390 bool isActive = true;
4391 switch (track->mState) {
4392 case TrackBase::STOPPING_1:
4393 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004394 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004395 track->mState = TrackBase::STOPPING_2;
4396 }
4397 break;
4398 case TrackBase::PAUSING:
4399 // ramp down is not yet implemented
4400 track->setPaused();
4401 break;
4402 case TrackBase::RESUMING:
4403 // ramp up is not yet implemented
4404 track->mState = TrackBase::ACTIVE;
4405 break;
4406 case TrackBase::ACTIVE:
4407 if (recentFull > 0 || recentPartial > 0) {
4408 // track has provided at least some frames recently: reset retry count
4409 track->mRetryCount = kMaxTrackRetries;
4410 }
4411 if (recentUnderruns == 0) {
4412 // no recent underruns: stay active
4413 break;
4414 }
4415 // there has recently been an underrun of some kind
4416 if (track->sharedBuffer() == 0) {
4417 // were any of the recent underruns "empty" (no frames available)?
4418 if (recentEmpty == 0) {
4419 // no, then ignore the partial underruns as they are allowed indefinitely
4420 break;
4421 }
4422 // there has recently been an "empty" underrun: decrement the retry counter
4423 if (--(track->mRetryCount) > 0) {
4424 break;
4425 }
4426 // indicate to client process that the track was disabled because of underrun;
4427 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004428 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004429 // remove from active list, but state remains ACTIVE [confusing but true]
4430 isActive = false;
4431 break;
4432 }
4433 // fall through
4434 case TrackBase::STOPPING_2:
4435 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004436 case TrackBase::STOPPED:
4437 case TrackBase::FLUSHED: // flush() while active
4438 // Check for presentation complete if track is inactive
4439 // We have consumed all the buffers of this track.
4440 // This would be incomplete if we auto-paused on underrun
4441 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004442 uint32_t latency = 0;
4443 status_t result = mOutput->stream->getLatency(&latency);
4444 ALOGE_IF(result != OK,
4445 "Error when retrieving output stream latency: %d", result);
4446 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004447 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004448 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4449 // track stays in active list until presentation is complete
4450 break;
4451 }
4452 }
4453 if (track->isStopping_2()) {
4454 track->mState = TrackBase::STOPPED;
4455 }
4456 if (track->isStopped()) {
4457 // Can't reset directly, as fast mixer is still polling this track
4458 // track->reset();
4459 // So instead mark this track as needing to be reset after push with ack
4460 resetMask |= 1 << i;
4461 }
4462 isActive = false;
4463 break;
4464 case TrackBase::IDLE:
4465 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004466 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004467 }
4468
4469 if (isActive) {
4470 // was it previously inactive?
4471 if (!(state->mTrackMask & (1 << j))) {
4472 ExtendedAudioBufferProvider *eabp = track;
4473 VolumeProvider *vp = track;
4474 fastTrack->mBufferProvider = eabp;
4475 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004476 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004477 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004478 fastTrack->mGeneration++;
4479 state->mTrackMask |= 1 << j;
4480 didModify = true;
4481 // no acknowledgement required for newly active tracks
4482 }
Kevin Rocard12381092018-04-11 09:19:59 -07004483 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004484 // cache the combined master volume and stream type volume for fast mixer; this
4485 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004486 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004487 proxy->framesReleased()).first;
4488 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004489 * mStreamTypes[track->streamType()].volume
4490 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004491 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004492 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4493 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4494 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4495 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004496 ++fastTracks;
4497 } else {
4498 // was it previously active?
4499 if (state->mTrackMask & (1 << j)) {
4500 fastTrack->mBufferProvider = NULL;
4501 fastTrack->mGeneration++;
4502 state->mTrackMask &= ~(1 << j);
4503 didModify = true;
4504 // If any fast tracks were removed, we must wait for acknowledgement
4505 // because we're about to decrement the last sp<> on those tracks.
4506 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4507 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004508 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4509 // AudioTrack may start (which may not be with a start() but with a write()
4510 // after underrun) and immediately paused or released. In that case the
4511 // FastTrack state hasn't had time to update.
4512 // TODO Remove the ALOGW when this theory is confirmed.
4513 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004514 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4515 j, track->mState, state->mTrackMask, recentUnderruns,
4516 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004517 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004518 }
4519 tracksToRemove->add(track);
4520 // Avoids a misleading display in dumpsys
4521 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4522 }
4523 continue;
4524 }
4525
4526 { // local variable scope to avoid goto warning
4527
4528 audio_track_cblk_t* cblk = track->cblk();
4529
4530 // The first time a track is added we wait
4531 // for all its buffers to be filled before processing it
4532 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004533
4534 // if an active track doesn't exist in the AudioMixer, create it.
4535 if (!mAudioMixer->exists(name)) {
4536 status_t status = mAudioMixer->create(
4537 name,
4538 track->mChannelMask,
4539 track->mFormat,
4540 track->mSessionId);
4541 if (status != OK) {
4542 ALOGW("%s: cannot create track name"
4543 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4544 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4545 tracksToRemove->add(track);
4546 track->invalidate(); // consider it dead.
4547 continue;
4548 }
4549 }
4550
Eric Laurent81784c32012-11-19 14:55:58 -08004551 // make sure that we have enough frames to mix one full buffer.
4552 // enforce this condition only once to enable draining the buffer in case the client
4553 // app does not call stop() and relies on underrun to stop:
4554 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4555 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004556 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004557 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004558 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004559
4560 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004561 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004562 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4563 // add frames already consumed but not yet released by the resampler
4564 // because mAudioTrackServerProxy->framesReady() will include these frames
4565 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4566
Eric Laurent81784c32012-11-19 14:55:58 -08004567 uint32_t minFrames = 1;
4568 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4569 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004570 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004571 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004572
4573 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004574 if (ATRACE_ENABLED()) {
4575 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004576 std::string traceName("nRdy");
4577 traceName += std::to_string(track->name());
4578 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004579 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004580 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004581 !track->isPaused() && !track->isTerminated())
4582 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004583 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004584
4585 mixedTracks++;
4586
Andy Hung69aed5f2014-02-25 17:24:40 -08004587 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4588 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004589 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004590 if (track->mainBuffer() != mSinkBuffer &&
4591 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004592 if (mEffectBufferEnabled) {
4593 mEffectBufferValid = true; // Later can set directly.
4594 }
Eric Laurent81784c32012-11-19 14:55:58 -08004595 chain = getEffectChain_l(track->sessionId());
4596 // Delegate volume control to effect in track effect chain if needed
4597 if (chain != 0) {
4598 tracksWithEffect++;
4599 } else {
4600 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4601 "session %d",
4602 name, track->sessionId());
4603 }
4604 }
4605
4606
4607 int param = AudioMixer::VOLUME;
4608 if (track->mFillingUpStatus == Track::FS_FILLED) {
4609 // no ramp for the first volume setting
4610 track->mFillingUpStatus = Track::FS_ACTIVE;
4611 if (track->mState == TrackBase::RESUMING) {
4612 track->mState = TrackBase::ACTIVE;
4613 param = AudioMixer::RAMP_VOLUME;
4614 }
4615 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004616 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004617 // FIXME should not make a decision based on mServer
4618 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004619 // If the track is stopped before the first frame was mixed,
4620 // do not apply ramp
4621 param = AudioMixer::RAMP_VOLUME;
4622 }
4623
4624 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004625 uint32_t vl, vr; // in U8.24 integer format
4626 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004627 // read original volumes with volume control
4628 float typeVolume = mStreamTypes[track->streamType()].volume;
4629 float v = masterVolume * typeVolume;
4630
Glenn Kastene4756fe2012-11-29 13:38:14 -08004631 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004632 vl = vr = 0;
4633 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004634 if (track->isPausing()) {
4635 track->setPaused();
4636 }
4637 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004638 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004639 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004640 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4641 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004642 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004643 if (vlf > GAIN_FLOAT_UNITY) {
4644 ALOGV("Track left volume out of range: %.3g", vlf);
4645 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004646 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004647 if (vrf > GAIN_FLOAT_UNITY) {
4648 ALOGV("Track right volume out of range: %.3g", vrf);
4649 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004650 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004651 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004652 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004653 // now apply the master volume and stream type volume and shaper volume
4654 vlf *= v * vh;
4655 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004656 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004657 // then derive vl and vr as U8.24 versions for the effect chain
4658 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4659 vl = (uint32_t) (scaleto8_24 * vlf);
4660 vr = (uint32_t) (scaleto8_24 * vrf);
4661 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004662 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004663 // send level comes from shared memory and so may be corrupt
4664 if (sendLevel > MAX_GAIN_INT) {
4665 ALOGV("Track send level out of range: %04X", sendLevel);
4666 sendLevel = MAX_GAIN_INT;
4667 }
Andy Hung6be49402014-05-30 10:42:03 -07004668 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4669 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004670 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004671
Kevin Rocard12381092018-04-11 09:19:59 -07004672 track->setFinalVolume((vrf + vlf) / 2.f);
4673
Eric Laurent81784c32012-11-19 14:55:58 -08004674 // Delegate volume control to effect in track effect chain if needed
4675 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4676 // Do not ramp volume if volume is controlled by effect
4677 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004678 // Update remaining floating point volume levels
4679 vlf = (float)vl / (1 << 24);
4680 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004681 track->mHasVolumeController = true;
4682 } else {
4683 // force no volume ramp when volume controller was just disabled or removed
4684 // from effect chain to avoid volume spike
4685 if (track->mHasVolumeController) {
4686 param = AudioMixer::VOLUME;
4687 }
4688 track->mHasVolumeController = false;
4689 }
4690
Eric Laurent7c29ec92017-09-20 17:54:22 -07004691 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4692 // still applied by the mixer.
4693 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4694 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4695 if (v != mLeftVolFloat) {
4696 status_t result = mOutput->stream->setVolume(v, v);
4697 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4698 if (result == OK) {
4699 mLeftVolFloat = v;
4700 }
4701 }
4702 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4703 // remove stream volume contribution from software volume.
4704 if (v != 0.0f && mLeftVolFloat == v) {
4705 vlf = min(1.0f, vlf / v);
4706 vrf = min(1.0f, vrf / v);
4707 vaf = min(1.0f, vaf / v);
4708 }
4709 }
Eric Laurent81784c32012-11-19 14:55:58 -08004710 // XXX: these things DON'T need to be done each time
4711 mAudioMixer->setBufferProvider(name, track);
4712 mAudioMixer->enable(name);
4713
Andy Hung6be49402014-05-30 10:42:03 -07004714 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4715 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4716 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004717 mAudioMixer->setParameter(
4718 name,
4719 AudioMixer::TRACK,
4720 AudioMixer::FORMAT, (void *)track->format());
4721 mAudioMixer->setParameter(
4722 name,
4723 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004724 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004725 mAudioMixer->setParameter(
4726 name,
4727 AudioMixer::TRACK,
4728 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004729 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004730 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004731 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004732 if (reqSampleRate == 0) {
4733 reqSampleRate = mSampleRate;
4734 } else if (reqSampleRate > maxSampleRate) {
4735 reqSampleRate = maxSampleRate;
4736 }
Eric Laurent81784c32012-11-19 14:55:58 -08004737 mAudioMixer->setParameter(
4738 name,
4739 AudioMixer::RESAMPLE,
4740 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004741 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004742
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004743 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004744 mAudioMixer->setParameter(
4745 name,
4746 AudioMixer::TIMESTRETCH,
4747 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004748 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004749
Andy Hung69aed5f2014-02-25 17:24:40 -08004750 /*
4751 * Select the appropriate output buffer for the track.
4752 *
Andy Hung98ef9782014-03-04 14:46:50 -08004753 * Tracks with effects go into their own effects chain buffer
4754 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004755 *
4756 * Other tracks can use mMixerBuffer for higher precision
4757 * channel accumulation. If this buffer is enabled
4758 * (mMixerBufferEnabled true), then selected tracks will accumulate
4759 * into it.
4760 *
4761 */
4762 if (mMixerBufferEnabled
4763 && (track->mainBuffer() == mSinkBuffer
4764 || track->mainBuffer() == mMixerBuffer)) {
4765 mAudioMixer->setParameter(
4766 name,
4767 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004768 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004769 mAudioMixer->setParameter(
4770 name,
4771 AudioMixer::TRACK,
4772 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4773 // TODO: override track->mainBuffer()?
4774 mMixerBufferValid = true;
4775 } else {
4776 mAudioMixer->setParameter(
4777 name,
4778 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004779 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004780 mAudioMixer->setParameter(
4781 name,
4782 AudioMixer::TRACK,
4783 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4784 }
Eric Laurent81784c32012-11-19 14:55:58 -08004785 mAudioMixer->setParameter(
4786 name,
4787 AudioMixer::TRACK,
4788 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4789
4790 // reset retry count
4791 track->mRetryCount = kMaxTrackRetries;
4792
4793 // If one track is ready, set the mixer ready if:
4794 // - the mixer was not ready during previous round OR
4795 // - no other track is not ready
4796 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4797 mixerStatus != MIXER_TRACKS_ENABLED) {
4798 mixerStatus = MIXER_TRACKS_READY;
4799 }
4800 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004801 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004802 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004803 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4804 track, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004805 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004806 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004807 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004808
Eric Laurent81784c32012-11-19 14:55:58 -08004809 // clear effect chain input buffer if an active track underruns to avoid sending
4810 // previous audio buffer again to effects
4811 chain = getEffectChain_l(track->sessionId());
4812 if (chain != 0) {
4813 chain->clearInputBuffer();
4814 }
4815
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004816 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004817 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4818 track->isStopped() || track->isPaused()) {
4819 // We have consumed all the buffers of this track.
4820 // Remove it from the list of active tracks.
4821 // TODO: use actual buffer filling status instead of latency when available from
4822 // audio HAL
4823 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004824 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004825 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4826 if (track->isStopped()) {
4827 track->reset();
4828 }
4829 tracksToRemove->add(track);
4830 }
4831 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004832 // No buffers for this track. Give it a few chances to
4833 // fill a buffer, then remove it from active list.
4834 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004835 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004836 tracksToRemove->add(track);
4837 // indicate to client process that the track was disabled because of underrun;
4838 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004839 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004840 // If one track is not ready, mark the mixer also not ready if:
4841 // - the mixer was ready during previous round OR
4842 // - no other track is ready
4843 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4844 mixerStatus != MIXER_TRACKS_READY) {
4845 mixerStatus = MIXER_TRACKS_ENABLED;
4846 }
4847 }
4848 mAudioMixer->disable(name);
4849 }
4850
4851 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004852
4853 }
4854
4855 // Push the new FastMixer state if necessary
4856 bool pauseAudioWatchdog = false;
4857 if (didModify) {
4858 state->mFastTracksGen++;
4859 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4860 if (kUseFastMixer == FastMixer_Dynamic &&
4861 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4862 state->mCommand = FastMixerState::COLD_IDLE;
4863 state->mColdFutexAddr = &mFastMixerFutex;
4864 state->mColdGen++;
4865 mFastMixerFutex = 0;
4866 if (kUseFastMixer == FastMixer_Dynamic) {
4867 mNormalSink = mOutputSink;
4868 }
4869 // If we go into cold idle, need to wait for acknowledgement
4870 // so that fast mixer stops doing I/O.
4871 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4872 pauseAudioWatchdog = true;
4873 }
Eric Laurent81784c32012-11-19 14:55:58 -08004874 }
4875 if (sq != NULL) {
4876 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004877 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4878 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4879 // when bringing the output sink into standby.)
4880 //
4881 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4882 //
4883 // This occurs with BT suspend when we idle the FastMixer with
4884 // active tracks, which may be added or removed.
4885 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004886 }
4887#ifdef AUDIO_WATCHDOG
4888 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4889 mAudioWatchdog->pause();
4890 }
4891#endif
4892
4893 // Now perform the deferred reset on fast tracks that have stopped
4894 while (resetMask != 0) {
4895 size_t i = __builtin_ctz(resetMask);
4896 ALOG_ASSERT(i < count);
4897 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004898 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004899 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4900 track->reset();
4901 }
4902
Andy Hung80d03d22018-04-10 10:32:11 -07004903 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4904 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4905 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4906 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4907 // See also the implementation of destroyTrack_l().
4908 for (const auto &track : *tracksToRemove) {
4909 const int name = track->name();
4910 if (mAudioMixer->exists(name)) { // Normal tracks here, fast tracks in FastMixer.
4911 mAudioMixer->setBufferProvider(name, nullptr /* bufferProvider */);
4912 }
4913 }
4914
Eric Laurent81784c32012-11-19 14:55:58 -08004915 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004916 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004917
Eric Laurent97d547d2014-09-02 14:45:53 -07004918 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4919 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004920 }
4921
4922 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004923 // as long as there are effects we should clear the effects buffer, to avoid
4924 // passing a non-clean buffer to the effect chain
4925 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004926 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004927 // sink or mix buffer must be cleared if all tracks are connected to an
4928 // effect chain as in this case the mixer will not write to the sink or mix buffer
4929 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004930 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4931 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004932 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004933 if (mMixerBufferValid) {
4934 memset(mMixerBuffer, 0, mMixerBufferSize);
4935 // TODO: In testing, mSinkBuffer below need not be cleared because
4936 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4937 // after mixing.
4938 //
4939 // To enforce this guarantee:
4940 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4941 // (mixedTracks == 0 && fastTracks > 0))
4942 // must imply MIXER_TRACKS_READY.
4943 // Later, we may clear buffers regardless, and skip much of this logic.
4944 }
Andy Hung98ef9782014-03-04 14:46:50 -08004945 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004946 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004947 }
4948
4949 // if any fast tracks, then status is ready
4950 mMixerStatusIgnoringFastTracks = mixerStatus;
4951 if (fastTracks > 0) {
4952 mixerStatus = MIXER_TRACKS_READY;
4953 }
4954 return mixerStatus;
4955}
4956
Eric Laurentad7dd962016-09-22 12:38:37 -07004957// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004958uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004959{
4960 uint32_t trackCount = 0;
4961 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004962 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004963 trackCount++;
4964 }
4965 }
4966 return trackCount;
4967}
4968
Andy Hung1bc088a2018-02-09 15:57:31 -08004969// isTrackAllowed_l() must be called with ThreadBase::mLock held
4970bool AudioFlinger::MixerThread::isTrackAllowed_l(
4971 audio_channel_mask_t channelMask, audio_format_t format,
4972 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004973{
Andy Hung1bc088a2018-02-09 15:57:31 -08004974 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4975 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004976 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004977 // Check validity as we don't call AudioMixer::create() here.
4978 if (!AudioMixer::isValidFormat(format)) {
4979 ALOGW("%s: invalid format: %#x", __func__, format);
4980 return false;
4981 }
4982 if (!AudioMixer::isValidChannelMask(channelMask)) {
4983 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4984 return false;
4985 }
4986 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004987}
4988
Eric Laurent10351942014-05-08 18:49:52 -07004989// checkForNewParameter_l() must be called with ThreadBase::mLock held
4990bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4991 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004992{
Eric Laurent81784c32012-11-19 14:55:58 -08004993 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004994 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004995
Eric Laurent10351942014-05-08 18:49:52 -07004996 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004997
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004998 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004999
Eric Laurent10351942014-05-08 18:49:52 -07005000 AudioParameter param = AudioParameter(keyValuePair);
5001 int value;
5002 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5003 reconfig = true;
5004 }
5005 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005006 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005007 status = BAD_VALUE;
5008 } else {
5009 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005010 reconfig = true;
5011 }
Eric Laurent10351942014-05-08 18:49:52 -07005012 }
5013 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005014 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005015 status = BAD_VALUE;
5016 } else {
5017 // no need to save value, since it's constant
5018 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005019 }
Eric Laurent10351942014-05-08 18:49:52 -07005020 }
5021 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5022 // do not accept frame count changes if tracks are open as the track buffer
5023 // size depends on frame count and correct behavior would not be guaranteed
5024 // if frame count is changed after track creation
5025 if (!mTracks.isEmpty()) {
5026 status = INVALID_OPERATION;
5027 } else {
5028 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005029 }
Eric Laurent10351942014-05-08 18:49:52 -07005030 }
5031 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005032#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005033 // when changing the audio output device, call addBatteryData to notify
5034 // the change
5035 if (mOutDevice != value) {
5036 uint32_t params = 0;
5037 // check whether speaker is on
5038 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5039 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005040 }
Eric Laurent10351942014-05-08 18:49:52 -07005041
5042 audio_devices_t deviceWithoutSpeaker
5043 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5044 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005045 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005046 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5047 }
5048
5049 if (params != 0) {
5050 addBatteryData(params);
5051 }
5052 }
Eric Laurent81784c32012-11-19 14:55:58 -08005053#endif
5054
Eric Laurent10351942014-05-08 18:49:52 -07005055 // forward device change to effects that have requested to be
5056 // aware of attached audio device.
5057 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005058 a2dpDeviceChanged =
5059 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005060 mOutDevice = value;
5061 for (size_t i = 0; i < mEffectChains.size(); i++) {
5062 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005063 }
5064 }
Eric Laurent10351942014-05-08 18:49:52 -07005065 }
Eric Laurent81784c32012-11-19 14:55:58 -08005066
Eric Laurent10351942014-05-08 18:49:52 -07005067 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005068 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005069 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005070 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005071 mStandby = true;
5072 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005073 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005074 }
Eric Laurent10351942014-05-08 18:49:52 -07005075 if (status == NO_ERROR && reconfig) {
5076 readOutputParameters_l();
5077 delete mAudioMixer;
5078 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005079 for (const auto &track : mTracks) {
5080 const int name = track->name();
5081 status_t status = mAudioMixer->create(
5082 name,
5083 track->mChannelMask,
5084 track->mFormat,
5085 track->mSessionId);
5086 ALOGW_IF(status != NO_ERROR,
5087 "%s: cannot create track name"
5088 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
5089 __func__,
5090 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005091 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005092 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005093 }
Eric Laurent81784c32012-11-19 14:55:58 -08005094 }
5095
Eric Laurent42537be2016-01-08 17:16:42 -08005096 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005097}
5098
5099
5100void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5101{
Eric Laurent81784c32012-11-19 14:55:58 -08005102 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005103 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005104 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005105 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005106 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005107 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005108 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005109 } else {
5110 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005111 }
Eric Laurent81784c32012-11-19 14:55:58 -08005112
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005113 if (hasFastMixer()) {
5114 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5115
5116 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5117 // while we are dumping it. It may be inconsistent, but it won't mutate!
5118 // This is a large object so we place it on the heap.
5119 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan7b651152018-07-13 10:17:19 -07005120 const std::unique_ptr<FastMixerDumpState> copy(new FastMixerDumpState(mFastMixerDumpState));
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005121 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005122
5123#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005124 // Similar for state queue
5125 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5126 observerCopy.dump(fd);
5127 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5128 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005129#endif
5130
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005131#ifdef AUDIO_WATCHDOG
5132 if (mAudioWatchdog != 0) {
5133 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5134 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5135 wdCopy.dump(fd);
5136 }
5137#endif
5138
5139 } else {
5140 dprintf(fd, " No FastMixer\n");
5141 }
Eric Laurent81784c32012-11-19 14:55:58 -08005142}
5143
Eric Tan7b651152018-07-13 10:17:19 -07005144std::string AudioFlinger::MixerThread::getJsonString() const
5145{
5146 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5147 // while we are dumping it. It may be inconsistent, but it won't mutate!
5148 // This is a large object so we place it on the heap.
5149 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5150 return std::unique_ptr<FastMixerDumpState>(new FastMixerDumpState(mFastMixerDumpState))
5151 ->getJsonString();
5152}
5153
Eric Laurent81784c32012-11-19 14:55:58 -08005154uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5155{
5156 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5157}
5158
5159uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5160{
5161 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5162}
5163
5164void AudioFlinger::MixerThread::cacheParameters_l()
5165{
5166 PlaybackThread::cacheParameters_l();
5167
5168 // FIXME: Relaxed timing because of a certain device that can't meet latency
5169 // Should be reduced to 2x after the vendor fixes the driver issue
5170 // increase threshold again due to low power audio mode. The way this warning
5171 // threshold is calculated and its usefulness should be reconsidered anyway.
5172 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5173}
5174
5175// ----------------------------------------------------------------------------
5176
5177AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005178 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5179 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005180{
5181}
5182
Eric Laurentbfb1b832013-01-07 09:53:42 -08005183AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5184 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005185 ThreadBase::type_t type, bool systemReady)
5186 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005187 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005188{
5189}
5190
Eric Laurent81784c32012-11-19 14:55:58 -08005191AudioFlinger::DirectOutputThread::~DirectOutputThread()
5192{
5193}
5194
Eric Laurent5850c4c2016-11-10 13:04:31 -08005195void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005196{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005197 float left, right;
5198
5199 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5200 left = right = 0;
5201 } else {
5202 float typeVolume = mStreamTypes[track->streamType()].volume;
5203 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005204 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005205
Andy Hung10cbff12017-02-21 17:30:14 -08005206 // Get volumeshaper scaling
5207 std::pair<float /* volume */, bool /* active */>
5208 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005209 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005210 v *= vh.first;
5211 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005212
Glenn Kastenc56f3422014-03-21 17:53:17 -07005213 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5214 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5215 if (left > GAIN_FLOAT_UNITY) {
5216 left = GAIN_FLOAT_UNITY;
5217 }
5218 left *= v;
5219 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5220 if (right > GAIN_FLOAT_UNITY) {
5221 right = GAIN_FLOAT_UNITY;
5222 }
5223 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005224 }
5225
5226 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005227 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005228 if (left != mLeftVolFloat || right != mRightVolFloat) {
5229 mLeftVolFloat = left;
5230 mRightVolFloat = right;
5231
5232 // Convert volumes from float to 8.24
5233 uint32_t vl = (uint32_t)(left * (1 << 24));
5234 uint32_t vr = (uint32_t)(right * (1 << 24));
5235
5236 // Delegate volume control to effect in track effect chain if needed
5237 // only one effect chain can be present on DirectOutputThread, so if
5238 // there is one, the track is connected to it
5239 if (!mEffectChains.isEmpty()) {
5240 mEffectChains[0]->setVolume_l(&vl, &vr);
5241 left = (float)vl / (1 << 24);
5242 right = (float)vr / (1 << 24);
5243 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005244 status_t result = mOutput->stream->setVolume(left, right);
5245 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005246 }
5247 }
5248}
5249
Phil Burk43b4dcc2015-06-09 16:53:44 -07005250void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5251{
5252 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005253 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005254
Eric Laurent0f0631e2015-07-06 18:01:25 -07005255 if (previousTrack != 0 && latestTrack != 0) {
5256 if (mType == DIRECT) {
5257 if (previousTrack.get() != latestTrack.get()) {
5258 mFlushPending = true;
5259 }
5260 } else /* mType == OFFLOAD */ {
5261 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5262 mFlushPending = true;
5263 }
5264 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005265 }
5266 PlaybackThread::onAddNewTrack_l();
5267}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005268
Eric Laurent81784c32012-11-19 14:55:58 -08005269AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5270 Vector< sp<Track> > *tracksToRemove
5271)
5272{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005273 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005274 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005275 bool doHwPause = false;
5276 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005277
5278 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005279 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005280 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005281 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005282 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005283 continue;
5284 }
5285
Eric Laurent5850c4c2016-11-10 13:04:31 -08005286 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005287#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005288 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005289#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005290 // Only consider last track started for volume and mixer state control.
5291 // In theory an older track could underrun and restart after the new one starts
5292 // but as we only care about the transition phase between two tracks on a
5293 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005294 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005295 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005296
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005297 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005298 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005299 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005300 doHwPause = true;
5301 mHwPaused = true;
5302 }
5303 tracksToRemove->add(track);
5304 } else if (track->isFlushPending()) {
5305 track->flushAck();
5306 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005307 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005308 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005309 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005310 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005311 if (last) {
5312 mLeftVolFloat = mRightVolFloat = -1.0;
5313 if (mHwPaused) {
5314 doHwResume = true;
5315 mHwPaused = false;
5316 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005317 }
5318 }
5319
Eric Laurent81784c32012-11-19 14:55:58 -08005320 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005321 // for all its buffers to be filled before processing it.
5322 // Allow draining the buffer in case the client
5323 // app does not call stop() and relies on underrun to stop:
5324 // hence the test on (track->mRetryCount > 1).
5325 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005326 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005327 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005328 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005329 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005330 minFrames = mNormalFrameCount;
5331 } else {
5332 minFrames = 1;
5333 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005334
Eric Laurentab5cdba2014-06-09 17:22:27 -07005335 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5336 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005337 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005338 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005339
5340 if (track->mFillingUpStatus == Track::FS_FILLED) {
5341 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005342 if (last) {
5343 // make sure processVolume_l() will apply new volume even if 0
5344 mLeftVolFloat = mRightVolFloat = -1.0;
5345 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005346 if (!mHwSupportsPause) {
5347 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005348 }
5349 }
5350
5351 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005352 processVolume_l(track, last);
5353 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005354 sp<Track> previousTrack = mPreviousTrack.promote();
5355 if (previousTrack != 0) {
5356 if (track != previousTrack.get()) {
5357 // Flush any data still being written from last track
5358 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005359 // Invalidate previous track to force a seek when resuming.
5360 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005361 }
5362 }
5363 mPreviousTrack = track;
5364
Eric Laurentd595b7c2013-04-03 17:27:56 -07005365 // reset retry count
5366 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005367 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005368 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005369 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005370 doHwResume = true;
5371 mHwPaused = false;
5372 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005373 }
Eric Laurent81784c32012-11-19 14:55:58 -08005374 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005375 // clear effect chain input buffer if the last active track started underruns
5376 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005377 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005378 mEffectChains[0]->clearInputBuffer();
5379 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005380 if (track->isStopping_1()) {
5381 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005382 if (last && mHwPaused) {
5383 doHwResume = true;
5384 mHwPaused = false;
5385 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005386 }
5387 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5388 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005389 // We have consumed all the buffers of this track.
5390 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005391 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005392 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005393 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5394 } else {
5395 audioHALFrames = 0;
5396 }
5397
Andy Hung818e7a32016-02-16 18:08:07 -08005398 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005399 if (mStandby || !last ||
5400 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005401 if (track->isStopping_2()) {
5402 track->mState = TrackBase::STOPPED;
5403 }
Eric Laurent81784c32012-11-19 14:55:58 -08005404 if (track->isStopped()) {
5405 track->reset();
5406 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005407 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005408 }
5409 } else {
5410 // No buffers for this track. Give it a few chances to
5411 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005412 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005413 if (--(track->mRetryCount) <= 0) {
5414 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005415 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005416 // indicate to client process that the track was disabled because of underrun;
5417 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005418 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005419 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005420 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5421 "minFrames = %u, mFormat = %#x",
5422 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005423 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005424 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005425 doHwPause = true;
5426 mHwPaused = true;
5427 }
Eric Laurent81784c32012-11-19 14:55:58 -08005428 }
5429 }
5430 }
5431 }
5432
Eric Laurentd1f69b02014-12-15 14:33:13 -08005433 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005434 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005435 for (size_t i = 0; i < mTracks.size(); i++) {
5436 if (mTracks[i]->isFlushPending()) {
5437 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005438 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005439 }
5440 }
5441 }
5442
5443 // make sure the pause/flush/resume sequence is executed in the right order.
5444 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5445 // before flush and then resume HW. This can happen in case of pause/flush/resume
5446 // if resume is received before pause is executed.
5447 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005448 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005449 status_t result = mOutput->stream->pause();
5450 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005451 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005452 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005453 flushHw_l();
5454 }
5455 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005456 status_t result = mOutput->stream->resume();
5457 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005458 }
Eric Laurent81784c32012-11-19 14:55:58 -08005459 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005460 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005461
5462 return mixerStatus;
5463}
5464
5465void AudioFlinger::DirectOutputThread::threadLoop_mix()
5466{
Eric Laurent81784c32012-11-19 14:55:58 -08005467 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005468 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005469 // output audio to hardware
5470 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005471 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005472 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005473 status_t status = mActiveTrack->getNextBuffer(&buffer);
5474 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005475 // no need to pad with 0 for compressed audio
5476 if (audio_has_proportional_frames(mFormat)) {
5477 memset(curBuf, 0, frameCount * mFrameSize);
5478 }
Eric Laurent81784c32012-11-19 14:55:58 -08005479 break;
5480 }
5481 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5482 frameCount -= buffer.frameCount;
5483 curBuf += buffer.frameCount * mFrameSize;
5484 mActiveTrack->releaseBuffer(&buffer);
5485 }
Andy Hung2098f272014-02-27 14:00:06 -08005486 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005487 mSleepTimeUs = 0;
5488 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005489 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005490}
5491
5492void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5493{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005494 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005495 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005496 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005497 return;
5498 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005499 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005500 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005501 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005502 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005503 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005504 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005505 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005506 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005507 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005508 }
5509}
5510
Eric Laurentd1f69b02014-12-15 14:33:13 -08005511void AudioFlinger::DirectOutputThread::threadLoop_exit()
5512{
5513 {
5514 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005515 for (size_t i = 0; i < mTracks.size(); i++) {
5516 if (mTracks[i]->isFlushPending()) {
5517 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005518 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005519 }
5520 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005521 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005522 flushHw_l();
5523 }
5524 }
5525 PlaybackThread::threadLoop_exit();
5526}
5527
5528// must be called with thread mutex locked
5529bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5530{
5531 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005532 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005533
vivek mehta9cd7ad12016-03-17 00:18:29 -07005534 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5535 return !mStandby;
5536 }
5537
Eric Laurentd1f69b02014-12-15 14:33:13 -08005538 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5539 // after a timeout and we will enter standby then.
5540 if (mTracks.size() > 0) {
5541 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005542 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5543 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005544 }
5545
Eric Laurent5cff4032015-05-26 13:49:58 -07005546 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005547}
5548
Eric Laurent10351942014-05-08 18:49:52 -07005549// checkForNewParameter_l() must be called with ThreadBase::mLock held
5550bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5551 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005552{
5553 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005554 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005555
Eric Laurent10351942014-05-08 18:49:52 -07005556 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005557
Eric Laurent10351942014-05-08 18:49:52 -07005558 AudioParameter param = AudioParameter(keyValuePair);
5559 int value;
5560 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5561 // forward device change to effects that have requested to be
5562 // aware of attached audio device.
5563 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005564 a2dpDeviceChanged =
5565 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005566 mOutDevice = value;
5567 for (size_t i = 0; i < mEffectChains.size(); i++) {
5568 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005569 }
5570 }
Eric Laurent81784c32012-11-19 14:55:58 -08005571 }
Eric Laurent10351942014-05-08 18:49:52 -07005572 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5573 // do not accept frame count changes if tracks are open as the track buffer
5574 // size depends on frame count and correct behavior would not be garantied
5575 // if frame count is changed after track creation
5576 if (!mTracks.isEmpty()) {
5577 status = INVALID_OPERATION;
5578 } else {
5579 reconfig = true;
5580 }
5581 }
5582 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005583 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005584 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005585 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005586 mStandby = true;
5587 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005588 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005589 }
5590 if (status == NO_ERROR && reconfig) {
5591 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005592 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005593 }
5594 }
5595
Eric Laurent42537be2016-01-08 17:16:42 -08005596 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005597}
5598
5599uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5600{
5601 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005602 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005603 time = PlaybackThread::activeSleepTimeUs();
5604 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005605 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005606 }
5607 return time;
5608}
5609
5610uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5611{
5612 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005613 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005614 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5615 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005616 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005617 }
5618 return time;
5619}
5620
5621uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5622{
5623 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005624 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005625 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5626 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005627 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005628 }
5629 return time;
5630}
5631
5632void AudioFlinger::DirectOutputThread::cacheParameters_l()
5633{
5634 PlaybackThread::cacheParameters_l();
5635
5636 // use shorter standby delay as on normal output to release
5637 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005638 // no delay on outputs with HW A/V sync
5639 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005640 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005641 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005642 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005643 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005644 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005645 }
Eric Laurent81784c32012-11-19 14:55:58 -08005646}
5647
Eric Laurente659ef42014-09-29 13:06:46 -07005648void AudioFlinger::DirectOutputThread::flushHw_l()
5649{
Phil Burk062e67a2015-02-11 13:40:50 -08005650 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005651 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005652 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005653 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005654}
5655
Andy Hung10cbff12017-02-21 17:30:14 -08005656int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5657 // If a VolumeShaper is active, we must wake up periodically to update volume.
5658 const int64_t NS_PER_MS = 1000000;
5659 return mVolumeShaperActive ?
5660 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5661}
5662
Eric Laurent81784c32012-11-19 14:55:58 -08005663// ----------------------------------------------------------------------------
5664
Eric Laurentbfb1b832013-01-07 09:53:42 -08005665AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005666 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005667 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005668 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005669 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005670 mDrainSequence(0),
5671 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005672{
5673}
5674
5675AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5676{
5677}
5678
5679void AudioFlinger::AsyncCallbackThread::onFirstRef()
5680{
5681 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5682}
5683
5684bool AudioFlinger::AsyncCallbackThread::threadLoop()
5685{
5686 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005687 uint32_t writeAckSequence;
5688 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005689 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005690
5691 {
5692 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005693 while (!((mWriteAckSequence & 1) ||
5694 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005695 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005696 exitPending())) {
5697 mWaitWorkCV.wait(mLock);
5698 }
5699
Eric Laurentbfb1b832013-01-07 09:53:42 -08005700 if (exitPending()) {
5701 break;
5702 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005703 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5704 mWriteAckSequence, mDrainSequence);
5705 writeAckSequence = mWriteAckSequence;
5706 mWriteAckSequence &= ~1;
5707 drainSequence = mDrainSequence;
5708 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005709 asyncError = mAsyncError;
5710 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005711 }
5712 {
Eric Laurent4de95592013-09-26 15:28:21 -07005713 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5714 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005715 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005716 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005717 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005718 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005719 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005720 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005721 if (asyncError) {
5722 playbackThread->onAsyncError();
5723 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005724 }
5725 }
5726 }
5727 return false;
5728}
5729
5730void AudioFlinger::AsyncCallbackThread::exit()
5731{
5732 ALOGV("AsyncCallbackThread::exit");
5733 Mutex::Autolock _l(mLock);
5734 requestExit();
5735 mWaitWorkCV.broadcast();
5736}
5737
Eric Laurent3b4529e2013-09-05 18:09:19 -07005738void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005739{
5740 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005741 // bit 0 is cleared
5742 mWriteAckSequence = sequence << 1;
5743}
5744
5745void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5746{
5747 Mutex::Autolock _l(mLock);
5748 // ignore unexpected callbacks
5749 if (mWriteAckSequence & 2) {
5750 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005751 mWaitWorkCV.signal();
5752 }
5753}
5754
Eric Laurent3b4529e2013-09-05 18:09:19 -07005755void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005756{
5757 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005758 // bit 0 is cleared
5759 mDrainSequence = sequence << 1;
5760}
5761
5762void AudioFlinger::AsyncCallbackThread::resetDraining()
5763{
5764 Mutex::Autolock _l(mLock);
5765 // ignore unexpected callbacks
5766 if (mDrainSequence & 2) {
5767 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005768 mWaitWorkCV.signal();
5769 }
5770}
5771
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005772void AudioFlinger::AsyncCallbackThread::setAsyncError()
5773{
5774 Mutex::Autolock _l(mLock);
5775 mAsyncError = true;
5776 mWaitWorkCV.signal();
5777}
5778
Eric Laurentbfb1b832013-01-07 09:53:42 -08005779
5780// ----------------------------------------------------------------------------
5781AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005782 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5783 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005784 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5785 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005786{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005787 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005788 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005789 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005790}
5791
Eric Laurentbfb1b832013-01-07 09:53:42 -08005792void AudioFlinger::OffloadThread::threadLoop_exit()
5793{
5794 if (mFlushPending || mHwPaused) {
5795 // If a flush is pending or track was paused, just discard buffered data
5796 flushHw_l();
5797 } else {
5798 mMixerStatus = MIXER_DRAIN_ALL;
5799 threadLoop_drain();
5800 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005801 if (mUseAsyncWrite) {
5802 ALOG_ASSERT(mCallbackThread != 0);
5803 mCallbackThread->exit();
5804 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005805 PlaybackThread::threadLoop_exit();
5806}
5807
5808AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5809 Vector< sp<Track> > *tracksToRemove
5810)
5811{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005812 size_t count = mActiveTracks.size();
5813
5814 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005815 bool doHwPause = false;
5816 bool doHwResume = false;
5817
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005818 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005819
Eric Laurentbfb1b832013-01-07 09:53:42 -08005820 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005821 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005822 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005823#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005824 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005825#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005826 // Only consider last track started for volume and mixer state control.
5827 // In theory an older track could underrun and restart after the new one starts
5828 // but as we only care about the transition phase between two tracks on a
5829 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005830 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005831 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005832
Haynes Mathew George7844f672014-01-15 12:32:55 -08005833 if (track->isInvalid()) {
5834 ALOGW("An invalidated track shouldn't be in active list");
5835 tracksToRemove->add(track);
5836 continue;
5837 }
5838
5839 if (track->mState == TrackBase::IDLE) {
5840 ALOGW("An idle track shouldn't be in active list");
5841 continue;
5842 }
5843
Eric Laurentbfb1b832013-01-07 09:53:42 -08005844 if (track->isPausing()) {
5845 track->setPaused();
5846 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005847 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005848 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005849 mHwPaused = true;
5850 }
5851 // If we were part way through writing the mixbuffer to
5852 // the HAL we must save this until we resume
5853 // BUG - this will be wrong if a different track is made active,
5854 // in that case we want to discard the pending data in the
5855 // mixbuffer and tell the client to present it again when the
5856 // track is resumed
5857 mPausedWriteLength = mCurrentWriteLength;
5858 mPausedBytesRemaining = mBytesRemaining;
5859 mBytesRemaining = 0; // stop writing
5860 }
5861 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005862 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005863 if (track->isStopping_1()) {
5864 track->mRetryCount = kMaxTrackStopRetriesOffload;
5865 } else {
5866 track->mRetryCount = kMaxTrackRetriesOffload;
5867 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005868 track->flushAck();
5869 if (last) {
5870 mFlushPending = true;
5871 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005872 } else if (track->isResumePending()){
5873 track->resumeAck();
5874 if (last) {
5875 if (mPausedBytesRemaining) {
5876 // Need to continue write that was interrupted
5877 mCurrentWriteLength = mPausedWriteLength;
5878 mBytesRemaining = mPausedBytesRemaining;
5879 mPausedBytesRemaining = 0;
5880 }
5881 if (mHwPaused) {
5882 doHwResume = true;
5883 mHwPaused = false;
5884 // threadLoop_mix() will handle the case that we need to
5885 // resume an interrupted write
5886 }
5887 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005888 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005889
Eric Laurent3df841a2016-07-15 15:15:40 -07005890 mLeftVolFloat = mRightVolFloat = -1.0;
5891
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005892 // Do not handle new data in this iteration even if track->framesReady()
5893 mixerStatus = MIXER_TRACKS_ENABLED;
5894 }
5895 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005896 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005897 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005898 if (track->mFillingUpStatus == Track::FS_FILLED) {
5899 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005900 if (last) {
5901 // make sure processVolume_l() will apply new volume even if 0
5902 mLeftVolFloat = mRightVolFloat = -1.0;
5903 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005904 }
5905
5906 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005907 sp<Track> previousTrack = mPreviousTrack.promote();
5908 if (previousTrack != 0) {
5909 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005910 // Flush any data still being written from last track
5911 mBytesRemaining = 0;
5912 if (mPausedBytesRemaining) {
5913 // Last track was paused so we also need to flush saved
5914 // mixbuffer state and invalidate track so that it will
5915 // re-submit that unwritten data when it is next resumed
5916 mPausedBytesRemaining = 0;
5917 // Invalidate is a bit drastic - would be more efficient
5918 // to have a flag to tell client that some of the
5919 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005920 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005921 }
5922 // flush data already sent to the DSP if changing audio session as audio
5923 // comes from a different source. Also invalidate previous track to force a
5924 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005925 if (previousTrack->sessionId() != track->sessionId()) {
5926 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005927 }
5928 }
5929 }
5930 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005931 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005932 if (track->isStopping_1()) {
5933 track->mRetryCount = kMaxTrackStopRetriesOffload;
5934 } else {
5935 track->mRetryCount = kMaxTrackRetriesOffload;
5936 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005937 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005938 mixerStatus = MIXER_TRACKS_READY;
5939 }
5940 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005941 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005942 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005943 if (--(track->mRetryCount) <= 0) {
5944 // Hardware buffer can hold a large amount of audio so we must
5945 // wait for all current track's data to drain before we say
5946 // that the track is stopped.
5947 if (mBytesRemaining == 0) {
5948 // Only start draining when all data in mixbuffer
5949 // has been written
5950 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5951 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5952 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5953 if (last && !mStandby) {
5954 // do not modify drain sequence if we are already draining. This happens
5955 // when resuming from pause after drain.
5956 if ((mDrainSequence & 1) == 0) {
5957 mSleepTimeUs = 0;
5958 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5959 mixerStatus = MIXER_DRAIN_TRACK;
5960 mDrainSequence += 2;
5961 }
5962 if (mHwPaused) {
5963 // It is possible to move from PAUSED to STOPPING_1 without
5964 // a resume so we must ensure hardware is running
5965 doHwResume = true;
5966 mHwPaused = false;
5967 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005968 }
5969 }
Eric Laurente93cc032016-05-05 10:15:10 -07005970 } else if (last) {
5971 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5972 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005973 }
5974 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005975 // Drain has completed or we are in standby, signal presentation complete
5976 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005977 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005978 uint32_t latency = 0;
5979 status_t result = mOutput->stream->getLatency(&latency);
5980 ALOGE_IF(result != OK,
5981 "Error when retrieving output stream latency: %d", result);
5982 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005983 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005984 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005985 track->presentationComplete(framesWritten, audioHALFrames);
5986 track->reset();
5987 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07005988 // DIRECT and OFFLOADED stop resets frame counts.
5989 if (!mUseAsyncWrite) {
5990 // If we don't get explicit drain notification we must
5991 // register discontinuity regardless of whether this is
5992 // the previous (!last) or the upcoming (last) track
5993 // to avoid skipping the discontinuity.
5994 mTimestampVerifier.discontinuity();
5995 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005996 }
5997 } else {
5998 // No buffers for this track. Give it a few chances to
5999 // fill a buffer, then remove it from active list.
6000 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006001 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006002 uint64_t position = 0;
6003 struct timespec unused;
6004 // The running check restarts the retry counter at least once.
6005 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6006 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6007 running = true;
6008 mOffloadUnderrunPosition = position;
6009 }
6010 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006011 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6012 (long long)position, (long long)mOffloadUnderrunPosition);
6013 }
6014 if (running) { // still running, give us more time.
6015 track->mRetryCount = kMaxTrackRetriesOffload;
6016 } else {
6017 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
6018 track->name());
6019 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006020 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006021 // it will then automatically call start() when data is available
6022 track->disable();
6023 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006024 } else if (last){
6025 mixerStatus = MIXER_TRACKS_ENABLED;
6026 }
6027 }
6028 }
6029 // compute volume for this track
6030 processVolume_l(track, last);
6031 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006032
Eric Laurentea0fade2013-10-04 16:23:48 -07006033 // make sure the pause/flush/resume sequence is executed in the right order.
6034 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6035 // before flush and then resume HW. This can happen in case of pause/flush/resume
6036 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006037 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006038 status_t result = mOutput->stream->pause();
6039 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006040 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006041 if (mFlushPending) {
6042 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006043 }
Eric Laurentfd477972013-10-25 18:10:40 -07006044 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006045 status_t result = mOutput->stream->resume();
6046 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006047 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006048
Eric Laurentbfb1b832013-01-07 09:53:42 -08006049 // remove all the tracks that need to be...
6050 removeTracks_l(*tracksToRemove);
6051
6052 return mixerStatus;
6053}
6054
Eric Laurentbfb1b832013-01-07 09:53:42 -08006055// must be called with thread mutex locked
6056bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6057{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006058 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6059 mWriteAckSequence, mDrainSequence);
6060 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006061 return true;
6062 }
6063 return false;
6064}
6065
Eric Laurentbfb1b832013-01-07 09:53:42 -08006066bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6067{
6068 Mutex::Autolock _l(mLock);
6069 return waitingAsyncCallback_l();
6070}
6071
6072void AudioFlinger::OffloadThread::flushHw_l()
6073{
Eric Laurente659ef42014-09-29 13:06:46 -07006074 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006075 // Flush anything still waiting in the mixbuffer
6076 mCurrentWriteLength = 0;
6077 mBytesRemaining = 0;
6078 mPausedWriteLength = 0;
6079 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006080 // reset bytes written count to reflect that DSP buffers are empty after flush.
6081 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006082 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006083
Eric Laurentbfb1b832013-01-07 09:53:42 -08006084 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006085 // discard any pending drain or write ack by incrementing sequence
6086 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6087 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006088 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006089 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6090 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006091 }
6092}
6093
Haynes Mathew George05317d22016-05-03 16:34:26 -07006094void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6095{
6096 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006097 if (PlaybackThread::invalidateTracks_l(streamType)) {
6098 mFlushPending = true;
6099 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006100}
6101
Eric Laurentbfb1b832013-01-07 09:53:42 -08006102// ----------------------------------------------------------------------------
6103
Eric Laurent81784c32012-11-19 14:55:58 -08006104AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006105 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006106 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006107 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006108 mWaitTimeMs(UINT_MAX)
6109{
6110 addOutputTrack(mainThread);
6111}
6112
6113AudioFlinger::DuplicatingThread::~DuplicatingThread()
6114{
6115 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6116 mOutputTracks[i]->destroy();
6117 }
6118}
6119
6120void AudioFlinger::DuplicatingThread::threadLoop_mix()
6121{
6122 // mix buffers...
6123 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006124 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006125 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006126 if (mMixerBufferValid) {
6127 memset(mMixerBuffer, 0, mMixerBufferSize);
6128 } else {
6129 memset(mSinkBuffer, 0, mSinkBufferSize);
6130 }
Eric Laurent81784c32012-11-19 14:55:58 -08006131 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006132 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006133 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006134 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006135 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006136}
6137
6138void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6139{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006140 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006141 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006142 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006143 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006144 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006145 }
6146 } else if (mBytesWritten != 0) {
6147 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6148 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006149 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006150 } else {
6151 // flush remaining overflow buffers in output tracks
6152 writeFrames = 0;
6153 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006154 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006155 }
6156}
6157
Eric Laurentbfb1b832013-01-07 09:53:42 -08006158ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006159{
6160 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006161 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6162
6163 // Consider the first OutputTrack for timestamp and frame counting.
6164
6165 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6166 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6167 // we always claim success.
6168 if (i == 0) {
6169 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6170 ALOGD_IF(correction != 0 && writeFrames != 0,
6171 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6172 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6173 mFramesWritten -= correction;
6174 }
6175
6176 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006177 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006178 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006179 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006180}
6181
6182void AudioFlinger::DuplicatingThread::threadLoop_standby()
6183{
6184 // DuplicatingThread implements standby by stopping all tracks
6185 for (size_t i = 0; i < outputTracks.size(); i++) {
6186 outputTracks[i]->stop();
6187 }
6188}
6189
Andy Hung1bc088a2018-02-09 15:57:31 -08006190void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6191{
6192 MixerThread::dumpInternals(fd, args);
6193
6194 std::stringstream ss;
6195 const size_t numTracks = mOutputTracks.size();
6196 ss << " " << numTracks << " OutputTracks";
6197 if (numTracks > 0) {
6198 ss << ":";
6199 for (const auto &track : mOutputTracks) {
6200 const sp<ThreadBase> thread = track->thread().promote();
6201 ss << " (" << track->name() << " : ";
6202 if (thread.get() != nullptr) {
6203 ss << thread.get() << ", " << thread->id();
6204 } else {
6205 ss << "null";
6206 }
6207 ss << ")";
6208 }
6209 }
6210 ss << "\n";
6211 std::string result = ss.str();
6212 write(fd, result.c_str(), result.size());
6213}
6214
Eric Laurent81784c32012-11-19 14:55:58 -08006215void AudioFlinger::DuplicatingThread::saveOutputTracks()
6216{
6217 outputTracks = mOutputTracks;
6218}
6219
6220void AudioFlinger::DuplicatingThread::clearOutputTracks()
6221{
6222 outputTracks.clear();
6223}
6224
6225void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6226{
6227 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006228 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6229 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6230 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6231 const size_t frameCount =
6232 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6233 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6234 // from different OutputTracks and their associated MixerThreads (e.g. one may
6235 // nearly empty and the other may be dropping data).
6236
6237 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006238 this,
6239 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006240 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006241 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006242 frameCount,
6243 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006244 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6245 if (status != NO_ERROR) {
6246 ALOGE("addOutputTrack() initCheck failed %d", status);
6247 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006248 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006249 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6250 mOutputTracks.add(outputTrack);
6251 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6252 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006253}
6254
6255void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6256{
6257 Mutex::Autolock _l(mLock);
6258 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6259 if (mOutputTracks[i]->thread() == thread) {
6260 mOutputTracks[i]->destroy();
6261 mOutputTracks.removeAt(i);
6262 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006263 if (thread->getOutput() == mOutput) {
6264 mOutput = NULL;
6265 }
Eric Laurent81784c32012-11-19 14:55:58 -08006266 return;
6267 }
6268 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006269 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006270}
6271
6272// caller must hold mLock
6273void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6274{
6275 mWaitTimeMs = UINT_MAX;
6276 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6277 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6278 if (strong != 0) {
6279 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6280 if (waitTimeMs < mWaitTimeMs) {
6281 mWaitTimeMs = waitTimeMs;
6282 }
6283 }
6284 }
6285}
6286
6287
6288bool AudioFlinger::DuplicatingThread::outputsReady(
6289 const SortedVector< sp<OutputTrack> > &outputTracks)
6290{
6291 for (size_t i = 0; i < outputTracks.size(); i++) {
6292 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6293 if (thread == 0) {
6294 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6295 outputTracks[i].get());
6296 return false;
6297 }
6298 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6299 // see note at standby() declaration
6300 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6301 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6302 thread.get());
6303 return false;
6304 }
6305 }
6306 return true;
6307}
6308
Kevin Rocard12381092018-04-11 09:19:59 -07006309void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6310 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006311{
Kevin Rocard12381092018-04-11 09:19:59 -07006312 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6313 outputTrack->setMetadatas(metadata.tracks);
6314 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006315}
6316
Eric Laurent81784c32012-11-19 14:55:58 -08006317uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6318{
6319 return (mWaitTimeMs * 1000) / 2;
6320}
6321
6322void AudioFlinger::DuplicatingThread::cacheParameters_l()
6323{
6324 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6325 updateWaitTime_l();
6326
6327 MixerThread::cacheParameters_l();
6328}
6329
Eric Laurent6acd1d42017-01-04 14:23:29 -08006330
Eric Laurent81784c32012-11-19 14:55:58 -08006331// ----------------------------------------------------------------------------
6332// Record
6333// ----------------------------------------------------------------------------
6334
6335AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6336 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006337 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006338 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006339 audio_devices_t inDevice,
6340 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006341 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006342 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006343 mInput(input),
6344 mActiveTracks(&this->mLocalLog),
6345 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006346 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006347 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006348 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6349 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006350 // mFastCapture below
6351 , mFastCaptureFutex(0)
6352 // mInputSource
6353 // mPipeSink
6354 // mPipeSource
6355 , mPipeFramesP2(0)
6356 // mPipeMemory
6357 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006358 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006359 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006360{
Glenn Kastend7dca052015-03-05 16:05:54 -08006361 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6362 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006363
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006364 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006365
6366 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006367 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006368 size_t numCounterOffers = 0;
6369 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006370#if !LOG_NDEBUG
6371 ssize_t index =
6372#else
6373 (void)
6374#endif
6375 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006376 ALOG_ASSERT(index == 0);
6377
6378 // initialize fast capture depending on configuration
6379 bool initFastCapture;
6380 switch (kUseFastCapture) {
6381 case FastCapture_Never:
6382 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006383 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006384 break;
6385 case FastCapture_Always:
6386 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006387 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006388 break;
6389 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006390 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006391 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6392 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6393 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006394 break;
6395 // case FastCapture_Dynamic:
6396 }
6397
6398 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006399 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006400 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006401 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6402 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006403 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006404 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006405 const sp<MemoryDealer> roHeap(readOnlyHeap());
6406 sp<IMemory> pipeMemory;
6407 if ((roHeap == 0) ||
6408 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006409 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6410 ALOGE("not enough memory for pipe buffer size=%zu; "
6411 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6412 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6413 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006414 goto failed;
6415 }
6416 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6417 memset(pipeBuffer, 0, pipeSize);
6418 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6419 const NBAIO_Format offers[1] = {format};
6420 size_t numCounterOffers = 0;
6421 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6422 ALOG_ASSERT(index == 0);
6423 mPipeSink = pipe;
6424 PipeReader *pipeReader = new PipeReader(*pipe);
6425 numCounterOffers = 0;
6426 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6427 ALOG_ASSERT(index == 0);
6428 mPipeSource = pipeReader;
6429 mPipeFramesP2 = pipeFramesP2;
6430 mPipeMemory = pipeMemory;
6431
6432 // create fast capture
6433 mFastCapture = new FastCapture();
6434 FastCaptureStateQueue *sq = mFastCapture->sq();
6435#ifdef STATE_QUEUE_DUMP
6436 // FIXME
6437#endif
6438 FastCaptureState *state = sq->begin();
6439 state->mCblk = NULL;
6440 state->mInputSource = mInputSource.get();
6441 state->mInputSourceGen++;
6442 state->mPipeSink = pipe;
6443 state->mPipeSinkGen++;
6444 state->mFrameCount = mFrameCount;
6445 state->mCommand = FastCaptureState::COLD_IDLE;
6446 // already done in constructor initialization list
6447 //mFastCaptureFutex = 0;
6448 state->mColdFutexAddr = &mFastCaptureFutex;
6449 state->mColdGen++;
6450 state->mDumpState = &mFastCaptureDumpState;
6451#ifdef TEE_SINK
6452 // FIXME
6453#endif
6454 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6455 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6456 sq->end();
6457 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6458
6459 // start the fast capture
6460 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6461 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006462 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006463 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006464#ifdef AUDIO_WATCHDOG
6465 // FIXME
6466#endif
6467
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006468 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006469 }
Andy Hung8946a282018-04-19 20:04:56 -07006470#ifdef TEE_SINK
6471 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6472 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6473#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006474failed: ;
6475
6476 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006477}
6478
Eric Laurent81784c32012-11-19 14:55:58 -08006479AudioFlinger::RecordThread::~RecordThread()
6480{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006481 if (mFastCapture != 0) {
6482 FastCaptureStateQueue *sq = mFastCapture->sq();
6483 FastCaptureState *state = sq->begin();
6484 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6485 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6486 if (old == -1) {
6487 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6488 }
6489 }
6490 state->mCommand = FastCaptureState::EXIT;
6491 sq->end();
6492 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6493 mFastCapture->join();
6494 mFastCapture.clear();
6495 }
6496 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006497 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006498 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006499}
6500
6501void AudioFlinger::RecordThread::onFirstRef()
6502{
Glenn Kastend7dca052015-03-05 16:05:54 -08006503 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006504}
6505
Eric Laurent555530a2017-02-07 18:17:24 -08006506void AudioFlinger::RecordThread::preExit()
6507{
6508 ALOGV(" preExit()");
6509 Mutex::Autolock _l(mLock);
6510 for (size_t i = 0; i < mTracks.size(); i++) {
6511 sp<RecordTrack> track = mTracks[i];
6512 track->invalidate();
6513 }
6514 mActiveTracks.clear();
6515 mStartStopCond.broadcast();
6516}
6517
Eric Laurent81784c32012-11-19 14:55:58 -08006518bool AudioFlinger::RecordThread::threadLoop()
6519{
Eric Laurent81784c32012-11-19 14:55:58 -08006520 nsecs_t lastWarning = 0;
6521
6522 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006523
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006524reacquire_wakelock:
6525 sp<RecordTrack> activeTrack;
6526 {
6527 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006528 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006529 }
6530
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006531 // used to request a deferred sleep, to be executed later while mutex is unlocked
6532 uint32_t sleepUs = 0;
6533
6534 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006535 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006536 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006537
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006538 // activeTracks accumulates a copy of a subset of mActiveTracks
6539 Vector< sp<RecordTrack> > activeTracks;
6540
Glenn Kasten735f45f2014-08-18 15:51:59 -07006541 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006542 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006543
Glenn Kasten735f45f2014-08-18 15:51:59 -07006544 // reference to a fast track which is about to be removed
6545 sp<RecordTrack> fastTrackToRemove;
6546
Eric Laurent81784c32012-11-19 14:55:58 -08006547 { // scope for mLock
6548 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006549
Eric Laurent021cf962014-05-13 10:18:14 -07006550 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006551
Eric Laurent000a4192014-01-29 15:17:32 -08006552 // check exitPending here because checkForNewParameters_l() and
6553 // checkForNewParameters_l() can temporarily release mLock
6554 if (exitPending()) {
6555 break;
6556 }
6557
Eric Laurent5c25d562016-07-13 17:17:45 -07006558 // sleep with mutex unlocked
6559 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006560 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006561 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6562 ATRACE_END();
6563 sleepUs = 0;
6564 continue;
6565 }
6566
Glenn Kasten2b806402013-11-20 16:37:38 -08006567 // if no active track(s), then standby and release wakelock
6568 size_t size = mActiveTracks.size();
6569 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006570 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006571 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006572 releaseWakeLock_l();
6573 ALOGV("RecordThread: loop stopping");
6574 // go to sleep
6575 mWaitWorkCV.wait(mLock);
6576 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006577 goto reacquire_wakelock;
6578 }
6579
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006580 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006581 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006582 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006583
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006584 activeTrack = mActiveTracks[i];
6585 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006586 if (activeTrack->isFastTrack()) {
6587 ALOG_ASSERT(fastTrackToRemove == 0);
6588 fastTrackToRemove = activeTrack;
6589 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006590 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006591 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006592 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006593 continue;
6594 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006595
6596 TrackBase::track_state activeTrackState = activeTrack->mState;
6597 switch (activeTrackState) {
6598
6599 case TrackBase::PAUSING:
6600 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006601 doBroadcast = true;
6602 size--;
6603 continue;
6604
6605 case TrackBase::STARTING_1:
6606 sleepUs = 10000;
6607 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006608 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006609 continue;
6610
6611 case TrackBase::STARTING_2:
6612 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006613 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006614 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006615 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006616 break;
6617
6618 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006619 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006620 break;
6621
6622 case TrackBase::IDLE:
6623 i++;
6624 continue;
6625
6626 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006627 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006628 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006629
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006630 activeTracks.add(activeTrack);
6631 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006632
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006633 if (activeTrack->isFastTrack()) {
6634 ALOG_ASSERT(!mFastTrackAvail);
6635 ALOG_ASSERT(fastTrack == 0);
6636 fastTrack = activeTrack;
6637 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006638 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006639
Andy Hungdae27702016-10-31 14:01:16 -07006640 mActiveTracks.updatePowerState(this);
6641
Kevin Rocard069c2712018-03-29 19:09:14 -07006642 updateMetadata_l();
6643
Eric Laurent5c25d562016-07-13 17:17:45 -07006644 if (allStopped) {
6645 standbyIfNotAlreadyInStandby();
6646 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006647 if (doBroadcast) {
6648 mStartStopCond.broadcast();
6649 }
6650
6651 // sleep if there are no active tracks to process
6652 if (activeTracks.size() == 0) {
6653 if (sleepUs == 0) {
6654 sleepUs = kRecordThreadSleepUs;
6655 }
6656 continue;
6657 }
6658 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006659
Eric Laurent81784c32012-11-19 14:55:58 -08006660 lockEffectChains_l(effectChains);
6661 }
6662
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006663 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006664
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006665 size_t size = effectChains.size();
6666 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006667 // thread mutex is not locked, but effect chain is locked
6668 effectChains[i]->process_l();
6669 }
6670
Glenn Kasten735f45f2014-08-18 15:51:59 -07006671 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006672 if (mFastCapture != 0) {
6673 FastCaptureStateQueue *sq = mFastCapture->sq();
6674 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006675 bool didModify = false;
6676 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006677 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6678 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6679 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6680 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6681 if (old == -1) {
6682 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6683 }
6684 }
6685 state->mCommand = FastCaptureState::READ_WRITE;
6686#if 0 // FIXME
6687 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006688 FastThreadDumpState::kSamplingNforLowRamDevice :
6689 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006690#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006691 didModify = true;
6692 }
6693 audio_track_cblk_t *cblkOld = state->mCblk;
6694 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6695 if (cblkNew != cblkOld) {
6696 state->mCblk = cblkNew;
6697 // block until acked if removing a fast track
6698 if (cblkOld != NULL) {
6699 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6700 }
6701 didModify = true;
6702 }
6703 sq->end(didModify);
6704 if (didModify) {
6705 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006706#if 0
6707 if (kUseFastCapture == FastCapture_Dynamic) {
6708 mNormalSource = mPipeSource;
6709 }
6710#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006711 }
6712 }
6713
Glenn Kasten735f45f2014-08-18 15:51:59 -07006714 // now run the fast track destructor with thread mutex unlocked
6715 fastTrackToRemove.clear();
6716
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006717 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6718 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6719 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6720 // If destination is non-contiguous, first read past the nominal end of buffer, then
6721 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006722
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006723 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006724 ssize_t framesRead;
6725
6726 // If an NBAIO source is present, use it to read the normal capture's data
6727 if (mPipeSource != 0) {
6728 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006729 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006730
6731 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6732 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6733 // we immediately retry the read() to get data and prevent another overflow.
6734 for (int retries = 0; retries <= 2; ++retries) {
6735 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6736 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6737 framesToRead);
6738 if (framesRead != OVERRUN) break;
6739 }
6740
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006741 const ssize_t availableToRead = mPipeSource->availableToRead();
6742 if (availableToRead >= 0) {
6743 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6744 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6745 "more frames to read than fifo size, %zd > %zu",
6746 availableToRead, mPipeFramesP2);
6747 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6748 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6749 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6750 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006751 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6752 }
6753 if (framesRead < 0) {
6754 status_t status = (status_t) framesRead;
6755 switch (status) {
6756 case OVERRUN:
6757 ALOGW("overrun on read from pipe");
6758 framesRead = 0;
6759 break;
6760 case NEGOTIATE:
6761 ALOGE("re-negotiation is needed");
6762 framesRead = -1; // Will cause an attempt to recover.
6763 break;
6764 default:
6765 ALOGE("unknown error %d on read from pipe", status);
6766 break;
6767 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006768 }
6769 // otherwise use the HAL / AudioStreamIn directly
6770 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006771 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006772 size_t bytesRead;
6773 status_t result = mInput->stream->read(
6774 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006775 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006776 if (result < 0) {
6777 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006778 } else {
6779 framesRead = bytesRead / mFrameSize;
6780 }
6781 }
6782
Andy Hung3f0c9022016-01-15 17:49:46 -08006783 // Update server timestamp with server stats
6784 // systemTime() is optional if the hardware supports timestamps.
6785 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6786 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6787
6788 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006789 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006790 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006791 if (mStandby) {
6792 mTimestampVerifier.discontinuity();
6793 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006794 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6795 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6796 // Note: In general record buffers should tend to be empty in
6797 // a properly running pipeline.
6798 //
6799 // Also, it is not advantageous to call get_presentation_position during the read
6800 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006801
6802 mTimestampVerifier.add(mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
6803 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
6804 mSampleRate);
6805 } else {
6806 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08006807 }
6808 }
6809 // Use this to track timestamp information
6810 // ALOGD("%s", mTimestamp.toString().c_str());
6811
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006812 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006813 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006814 // Force input into standby so that it tries to recover at next read attempt
6815 inputStandBy();
6816 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006817 }
6818 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006819 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006820 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006821 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006822
Andy Hung8946a282018-04-19 20:04:56 -07006823#ifdef TEE_SINK
6824 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6825#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006826 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006827 {
6828 size_t part1 = mRsmpInFramesP2 - rear;
6829 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006830 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006831 (framesRead - part1) * mFrameSize);
6832 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006833 }
6834 rear = mRsmpInRear += framesRead;
6835
6836 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006837
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006838 // loop over each active track
6839 for (size_t i = 0; i < size; i++) {
6840 activeTrack = activeTracks[i];
6841
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006842 // skip fast tracks, as those are handled directly by FastCapture
6843 if (activeTrack->isFastTrack()) {
6844 continue;
6845 }
6846
Andy Hung73c02e42015-03-29 01:13:58 -07006847 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006848 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6849
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006850 enum {
6851 OVERRUN_UNKNOWN,
6852 OVERRUN_TRUE,
6853 OVERRUN_FALSE
6854 } overrun = OVERRUN_UNKNOWN;
6855
6856 // loop over getNextBuffer to handle circular sink
6857 for (;;) {
6858
6859 activeTrack->mSink.frameCount = ~0;
6860 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6861 size_t framesOut = activeTrack->mSink.frameCount;
6862 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6863
Andy Hung73c02e42015-03-29 01:13:58 -07006864 // check available frames and handle overrun conditions
6865 // if the record track isn't draining fast enough.
6866 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006867 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006868 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6869 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006870 overrun = OVERRUN_TRUE;
6871 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006872 if (framesOut == 0 || framesIn == 0) {
6873 break;
6874 }
6875
Andy Hung6770c6f2015-04-07 13:43:36 -07006876 // Don't allow framesOut to be larger than what is possible with resampling
6877 // from framesIn.
6878 // This isn't strictly necessary but helps limit buffer resizing in
6879 // RecordBufferConverter. TODO: remove when no longer needed.
6880 framesOut = min(framesOut,
6881 destinationFramesPossible(
6882 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006883
6884 if (activeTrack->isDirect()) {
6885 // No RecordBufferConverter used for compressed formats. Pass
6886 // straight from RecordThread buffer to RecordTrack buffer.
6887 AudioBufferProvider::Buffer buffer;
6888 buffer.frameCount = framesOut;
6889 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
6890 if (status == OK && buffer.frameCount != 0) {
6891 ALOGV_IF(buffer.frameCount != framesOut,
6892 "%s() read less than expected (%zu vs %zu)",
6893 __func__, buffer.frameCount, framesOut);
6894 framesOut = buffer.frameCount;
6895 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount);
6896 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
6897 } else {
6898 framesOut = 0;
6899 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
6900 __func__, status, buffer.frameCount);
6901 }
6902 } else {
6903 // process frames from the RecordThread buffer provider to the RecordTrack
6904 // buffer
6905 framesOut = activeTrack->mRecordBufferConverter->convert(
6906 activeTrack->mSink.raw,
6907 activeTrack->mResamplerBufferProvider,
6908 framesOut);
6909 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006910
6911 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6912 overrun = OVERRUN_FALSE;
6913 }
6914
6915 if (activeTrack->mFramesToDrop == 0) {
6916 if (framesOut > 0) {
6917 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006918 // Sanitize before releasing if the track has no access to the source data
6919 // An idle UID receives silence from non virtual devices until active
6920 if (activeTrack->isSilenced()) {
6921 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6922 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006923 activeTrack->releaseBuffer(&activeTrack->mSink);
6924 }
6925 } else {
6926 // FIXME could do a partial drop of framesOut
6927 if (activeTrack->mFramesToDrop > 0) {
6928 activeTrack->mFramesToDrop -= framesOut;
6929 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006930 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006931 }
6932 } else {
6933 activeTrack->mFramesToDrop += framesOut;
6934 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6935 activeTrack->mSyncStartEvent->isCancelled()) {
6936 ALOGW("Synced record %s, session %d, trigger session %d",
6937 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6938 activeTrack->sessionId(),
6939 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006940 activeTrack->mSyncStartEvent->triggerSession() :
6941 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006942 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006943 }
6944 }
6945 }
6946
6947 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006948 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006949 }
6950 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006951
6952 switch (overrun) {
6953 case OVERRUN_TRUE:
6954 // client isn't retrieving buffers fast enough
6955 if (!activeTrack->setOverflow()) {
6956 nsecs_t now = systemTime();
6957 // FIXME should lastWarning per track?
6958 if ((now - lastWarning) > kWarningThrottleNs) {
6959 ALOGW("RecordThread: buffer overflow");
6960 lastWarning = now;
6961 }
6962 }
6963 break;
6964 case OVERRUN_FALSE:
6965 activeTrack->clearOverflow();
6966 break;
6967 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006968 break;
6969 }
6970
Andy Hung3f0c9022016-01-15 17:49:46 -08006971 // update frame information and push timestamp out
6972 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006973 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006974 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6975 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006976 }
6977
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006978unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006979 // enable changes in effect chain
6980 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006981 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006982 }
6983
Glenn Kasten93e471f2013-08-19 08:40:07 -07006984 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006985
6986 {
6987 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006988 for (size_t i = 0; i < mTracks.size(); i++) {
6989 sp<RecordTrack> track = mTracks[i];
6990 track->invalidate();
6991 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006992 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006993 mStartStopCond.broadcast();
6994 }
6995
6996 releaseWakeLock();
6997
6998 ALOGV("RecordThread %p exiting", this);
6999 return false;
7000}
7001
Glenn Kasten93e471f2013-08-19 08:40:07 -07007002void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007003{
7004 if (!mStandby) {
7005 inputStandBy();
7006 mStandby = true;
7007 }
7008}
7009
7010void AudioFlinger::RecordThread::inputStandBy()
7011{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007012 // Idle the fast capture if it's currently running
7013 if (mFastCapture != 0) {
7014 FastCaptureStateQueue *sq = mFastCapture->sq();
7015 FastCaptureState *state = sq->begin();
7016 if (!(state->mCommand & FastCaptureState::IDLE)) {
7017 state->mCommand = FastCaptureState::COLD_IDLE;
7018 state->mColdFutexAddr = &mFastCaptureFutex;
7019 state->mColdGen++;
7020 mFastCaptureFutex = 0;
7021 sq->end();
7022 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7023 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7024#if 0
7025 if (kUseFastCapture == FastCapture_Dynamic) {
7026 // FIXME
7027 }
7028#endif
7029#ifdef AUDIO_WATCHDOG
7030 // FIXME
7031#endif
7032 } else {
7033 sq->end(false /*didModify*/);
7034 }
7035 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007036 status_t result = mInput->stream->standby();
7037 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007038
7039 // If going into standby, flush the pipe source.
7040 if (mPipeSource.get() != nullptr) {
7041 const ssize_t flushed = mPipeSource->flush();
7042 if (flushed > 0) {
7043 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7044 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7045 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7046 }
7047 }
Eric Laurent81784c32012-11-19 14:55:58 -08007048}
7049
Glenn Kasten05997e22014-03-13 15:08:33 -07007050// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007051sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007052 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007053 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007054 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007055 audio_format_t format,
7056 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007057 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007058 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007059 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007060 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007061 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007062 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007063 status_t *status,
7064 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007065{
Glenn Kasten74935e42013-12-19 08:56:45 -08007066 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007067 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007068 sp<RecordTrack> track;
7069 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007070 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007071 audio_input_flags_t requestedFlags = *flags;
7072 uint32_t sampleRate;
7073
7074 lStatus = initCheck();
7075 if (lStatus != NO_ERROR) {
7076 ALOGE("createRecordTrack_l() audio driver not initialized");
7077 goto Exit;
7078 }
7079
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007080 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7081 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7082 lStatus = BAD_VALUE;
7083 goto Exit;
7084 }
7085
Eric Laurentf14db3c2017-12-08 14:20:36 -08007086 if (*pSampleRate == 0) {
7087 *pSampleRate = mSampleRate;
7088 }
7089 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007090
7091 // special case for FAST flag considered OK if fast capture is present
7092 if (hasFastCapture()) {
7093 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7094 }
7095
Eric Laurentf14db3c2017-12-08 14:20:36 -08007096 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007097 if ((*flags & inputFlags) != *flags) {
7098 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7099 " input flags (%08x)",
7100 *flags, inputFlags);
7101 *flags = (audio_input_flags_t)(*flags & inputFlags);
7102 }
Eric Laurent81784c32012-11-19 14:55:58 -08007103
Glenn Kasten90e58b12013-07-31 16:16:02 -07007104 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007105 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007106 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007107 // we formerly checked for a callback handler (non-0 tid),
7108 // but that is no longer required for TRANSFER_OBTAIN mode
7109 //
Glenn Kasten74105912014-07-03 12:28:53 -07007110 // frame count is not specified, or is exactly the pipe depth
7111 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007112 // PCM data
7113 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007114 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007115 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007116 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007117 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007118 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007119 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007120 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007121 hasFastCapture() &&
7122 // there are sufficient fast track slots available
7123 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007124 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007125 // check compatibility with audio effects.
7126 Mutex::Autolock _l(mLock);
7127 // Do not accept FAST flag if the session has software effects
7128 sp<EffectChain> chain = getEffectChain_l(sessionId);
7129 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007130 audio_input_flags_t old = *flags;
7131 chain->checkInputFlagCompatibility(flags);
7132 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007133 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7134 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007135 }
7136 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007137 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007138 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7139 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007140 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007141 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7142 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007143 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007144 this, frameCount, mFrameCount, mPipeFramesP2,
7145 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007146 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007147 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007148 }
7149 }
7150
Eric Laurentf14db3c2017-12-08 14:20:36 -08007151 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7152 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7153 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7154 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7155 lStatus = BAD_TYPE;
7156 goto Exit;
7157 }
7158
Glenn Kasten74105912014-07-03 12:28:53 -07007159 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007160 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007161 // fast track: frame count is exactly the pipe depth
7162 frameCount = mPipeFramesP2;
7163 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007164 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007165 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007166 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7167 // or 20 ms if there is a fast capture
7168 // TODO This could be a roundupRatio inline, and const
7169 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7170 * sampleRate + mSampleRate - 1) / mSampleRate;
7171 // minimum number of notification periods is at least kMinNotifications,
7172 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7173 static const size_t kMinNotifications = 3;
7174 static const uint32_t kMinMs = 30;
7175 // TODO This could be a roundupRatio inline
7176 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7177 // TODO This could be a roundupRatio inline
7178 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7179 maxNotificationFrames;
7180 const size_t minFrameCount = maxNotificationFrames *
7181 max(kMinNotifications, minNotificationsByMs);
7182 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007183 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7184 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007185 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007186 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007187 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007188 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007189
7190 { // scope for mLock
7191 Mutex::Autolock _l(mLock);
7192
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007193 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007194 format, channelMask, frameCount,
7195 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007196 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007197
Glenn Kasten03003332013-08-06 15:40:54 -07007198 lStatus = track->initCheck();
7199 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007200 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007201 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007202 goto Exit;
7203 }
7204 mTracks.add(track);
7205
Eric Laurent05067782016-06-01 18:27:28 -07007206 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007207 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7208 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7209 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007210 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007211 }
Eric Laurent81784c32012-11-19 14:55:58 -08007212 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007213
Eric Laurent81784c32012-11-19 14:55:58 -08007214 lStatus = NO_ERROR;
7215
7216Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007217 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007218 return track;
7219}
7220
7221status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7222 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007223 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007224{
7225 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7226 sp<ThreadBase> strongMe = this;
7227 status_t status = NO_ERROR;
7228
7229 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007230 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007231 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007232 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007233 triggerSession,
7234 recordTrack->sessionId(),
7235 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007236 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007237 // Sync event can be cancelled by the trigger session if the track is not in a
7238 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007239 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007240 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007241 } else {
7242 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007243 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007244 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007245 }
7246 }
7247
7248 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007249 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007250 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007251 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7252 if (recordTrack->mState == TrackBase::PAUSING) {
7253 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007254 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007255 } else {
7256 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007257 }
7258 return status;
7259 }
7260
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007261 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7262 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7263 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007264 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007265 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007266 status_t status = NO_ERROR;
7267 if (recordTrack->isExternalTrack()) {
7268 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007269 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007270 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007271 mLock.lock();
7272 // FIXME should verify that recordTrack is still in mActiveTracks
7273 if (status != NO_ERROR) {
7274 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007275 recordTrack->clearSyncStartEvent();
7276 ALOGV("RecordThread::start error %d", status);
7277 return status;
7278 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007279 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007280 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007281 // Catch up with current buffer indices if thread is already running.
7282 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7283 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7284 // see previously buffered data before it called start(), but with greater risk of overrun.
7285
Andy Hung73c02e42015-03-29 01:13:58 -07007286 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007287 if (!recordTrack->isDirect()) {
7288 // clear any converter state as new data will be discontinuous
7289 recordTrack->mRecordBufferConverter->reset();
7290 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007291 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007292 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007293 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007294 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007295 ALOGV("Record failed to start");
7296 status = BAD_VALUE;
7297 goto startError;
7298 }
Eric Laurent81784c32012-11-19 14:55:58 -08007299 return status;
7300 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007301
Eric Laurent81784c32012-11-19 14:55:58 -08007302startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007303 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007304 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007305 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007306 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007307 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007308 return status;
7309}
7310
Eric Laurent81784c32012-11-19 14:55:58 -08007311void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7312{
7313 sp<SyncEvent> strongEvent = event.promote();
7314
7315 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007316 sp<RefBase> ptr = strongEvent->cookie().promote();
7317 if (ptr != 0) {
7318 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7319 recordTrack->handleSyncStartEvent(strongEvent);
7320 }
Eric Laurent81784c32012-11-19 14:55:58 -08007321 }
7322}
7323
Glenn Kastena8356f62013-07-25 14:37:52 -07007324bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007325 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007326 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007327 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007328 return false;
7329 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007330 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007331 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007332 // signal thread to stop
7333 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007334 // do not wait for mStartStopCond if exiting
7335 if (exitPending()) {
7336 return true;
7337 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007338 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007339 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007340 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007341 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007342 ALOGV("Record stopped OK");
7343 return true;
7344 }
7345 return false;
7346}
7347
Glenn Kasten0f11b512014-01-31 16:18:54 -08007348bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007349{
7350 return false;
7351}
7352
Glenn Kasten0f11b512014-01-31 16:18:54 -08007353status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007354{
7355#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7356 if (!isValidSyncEvent(event)) {
7357 return BAD_VALUE;
7358 }
7359
Glenn Kastend848eb42016-03-08 13:42:11 -08007360 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007361 status_t ret = NAME_NOT_FOUND;
7362
7363 Mutex::Autolock _l(mLock);
7364
7365 for (size_t i = 0; i < mTracks.size(); i++) {
7366 sp<RecordTrack> track = mTracks[i];
7367 if (eventSession == track->sessionId()) {
7368 (void) track->setSyncEvent(event);
7369 ret = NO_ERROR;
7370 }
7371 }
7372 return ret;
7373#else
7374 return BAD_VALUE;
7375#endif
7376}
7377
jiabin653cc0a2018-01-17 17:54:10 -08007378status_t AudioFlinger::RecordThread::getActiveMicrophones(
7379 std::vector<media::MicrophoneInfo>* activeMicrophones)
7380{
7381 ALOGV("RecordThread::getActiveMicrophones");
7382 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007383 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7384 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007385}
7386
Kevin Rocard069c2712018-03-29 19:09:14 -07007387void AudioFlinger::RecordThread::updateMetadata_l()
7388{
7389 if (mInput == nullptr || mInput->stream == nullptr ||
7390 !mActiveTracks.readAndClearHasChanged()) {
7391 return;
7392 }
7393 StreamInHalInterface::SinkMetadata metadata;
7394 for (const sp<RecordTrack> &track : mActiveTracks) {
7395 // No track is invalid as this is called after prepareTrack_l in the same critical section
7396 metadata.tracks.push_back({
7397 .source = track->attributes().source,
7398 .gain = 1, // capture tracks do not have volumes
7399 });
7400 }
7401 mInput->stream->updateSinkMetadata(metadata);
7402}
7403
Eric Laurent81784c32012-11-19 14:55:58 -08007404// destroyTrack_l() must be called with ThreadBase::mLock held
7405void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7406{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007407 track->terminate();
7408 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007409 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007410 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007411 removeTrack_l(track);
7412 }
7413}
7414
7415void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7416{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007417 String8 result;
7418 track->appendDump(result, false /* active */);
7419 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7420
Eric Laurent81784c32012-11-19 14:55:58 -08007421 mTracks.remove(track);
7422 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007423 if (track->isFastTrack()) {
7424 ALOG_ASSERT(!mFastTrackAvail);
7425 mFastTrackAvail = true;
7426 }
Eric Laurent81784c32012-11-19 14:55:58 -08007427}
7428
7429void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7430{
7431 dumpInternals(fd, args);
7432 dumpTracks(fd, args);
7433 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007434 dprintf(fd, " Local log:\n");
7435 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007436}
7437
7438void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7439{
Glenn Kasten44182c22015-03-05 17:12:23 -08007440 dumpBase(fd, args);
7441
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007442 AudioStreamIn *input = mInput;
7443 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7444 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7445 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007446 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007447 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007448 }
Andy Hungbfa64962017-06-12 14:43:19 -07007449
7450 if (input != nullptr) {
7451 dprintf(fd, " Hal stream dump:\n");
7452 (void)input->stream->dump(fd);
7453 }
7454
Andy Hung20bd30b2018-06-01 15:39:35 -07007455 const double latencyMs = - mTimestamp.getOutputServerLatencyMs(mSampleRate);
7456 if (latencyMs != 0.) {
7457 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7458 } else {
7459 dprintf(fd, " NormalRecord latency ms: unavail\n");
7460 }
7461
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007462 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007463 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007464
Glenn Kasten2f90c512015-12-02 11:40:09 -08007465 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7466 // while we are dumping it. It may be inconsistent, but it won't mutate!
7467 // This is a large object so we place it on the heap.
7468 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan7b651152018-07-13 10:17:19 -07007469 std::unique_ptr<FastCaptureDumpState> copy(new FastCaptureDumpState(mFastCaptureDumpState));
Glenn Kasten2f90c512015-12-02 11:40:09 -08007470 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007471}
7472
Glenn Kasten0f11b512014-01-31 16:18:54 -08007473void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007474{
Eric Laurent81784c32012-11-19 14:55:58 -08007475 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007476 size_t numtracks = mTracks.size();
7477 size_t numactive = mActiveTracks.size();
7478 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007479 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007480 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007481 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007482 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007483 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007484 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007485 for (size_t i = 0; i < numtracks ; ++i) {
7486 sp<RecordTrack> track = mTracks[i];
7487 if (track != 0) {
7488 bool active = mActiveTracks.indexOf(track) >= 0;
7489 if (active) {
7490 numactiveseen++;
7491 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007492 result.append(prefix);
7493 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007494 }
Eric Laurent81784c32012-11-19 14:55:58 -08007495 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007496 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007497 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007498 }
7499
Marco Nelissenb2208842014-02-07 14:00:50 -08007500 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007501 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007502 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007503 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007504 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007505 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007506 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007507 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007508 result.append(prefix);
7509 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007510 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007511 }
Eric Laurent81784c32012-11-19 14:55:58 -08007512
7513 }
7514 write(fd, result.string(), result.size());
7515}
7516
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007517void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7518{
7519 Mutex::Autolock _l(mLock);
7520 for (size_t i = 0; i < mTracks.size() ; i++) {
7521 sp<RecordTrack> track = mTracks[i];
7522 if (track != 0 && track->uid() == uid) {
7523 track->setSilenced(silenced);
7524 }
7525 }
7526}
Andy Hung73c02e42015-03-29 01:13:58 -07007527
7528void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7529{
7530 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7531 RecordThread *recordThread = (RecordThread *) threadBase.get();
7532 mRsmpInFront = recordThread->mRsmpInRear;
7533 mRsmpInUnrel = 0;
7534}
7535
7536void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7537 size_t *framesAvailable, bool *hasOverrun)
7538{
7539 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7540 RecordThread *recordThread = (RecordThread *) threadBase.get();
7541 const int32_t rear = recordThread->mRsmpInRear;
7542 const int32_t front = mRsmpInFront;
7543 const ssize_t filled = rear - front;
7544
7545 size_t framesIn;
7546 bool overrun = false;
7547 if (filled < 0) {
7548 // should not happen, but treat like a massive overrun and re-sync
7549 framesIn = 0;
7550 mRsmpInFront = rear;
7551 overrun = true;
7552 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7553 framesIn = (size_t) filled;
7554 } else {
7555 // client is not keeping up with server, but give it latest data
7556 framesIn = recordThread->mRsmpInFrames;
7557 mRsmpInFront = /* front = */ rear - framesIn;
7558 overrun = true;
7559 }
7560 if (framesAvailable != NULL) {
7561 *framesAvailable = framesIn;
7562 }
7563 if (hasOverrun != NULL) {
7564 *hasOverrun = overrun;
7565 }
7566}
7567
Eric Laurent81784c32012-11-19 14:55:58 -08007568// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007569status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007570 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007571{
Andy Hung73c02e42015-03-29 01:13:58 -07007572 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007573 if (threadBase == 0) {
7574 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007575 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007576 return NOT_ENOUGH_DATA;
7577 }
7578 RecordThread *recordThread = (RecordThread *) threadBase.get();
7579 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007580 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007581 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007582 // FIXME should not be P2 (don't want to increase latency)
7583 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007584 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007585 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007586 front &= recordThread->mRsmpInFramesP2 - 1;
7587 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007588 if (part1 > (size_t) filled) {
7589 part1 = filled;
7590 }
7591 size_t ask = buffer->frameCount;
7592 ALOG_ASSERT(ask > 0);
7593 if (part1 > ask) {
7594 part1 = ask;
7595 }
7596 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007597 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007598 buffer->raw = NULL;
7599 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007600 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007601 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007602 }
7603
Andy Hung57446612015-04-19 23:56:46 -07007604 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007605 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007606 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007607 return NO_ERROR;
7608}
7609
7610// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007611void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7612 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007613{
Glenn Kasten85948432013-08-19 12:09:05 -07007614 size_t stepCount = buffer->frameCount;
7615 if (stepCount == 0) {
7616 return;
7617 }
Andy Hung73c02e42015-03-29 01:13:58 -07007618 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7619 mRsmpInUnrel -= stepCount;
7620 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007621 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007622 buffer->frameCount = 0;
7623}
7624
Eric Laurentd8365c52017-07-16 15:27:05 -07007625void AudioFlinger::RecordThread::checkBtNrec()
7626{
7627 Mutex::Autolock _l(mLock);
7628 checkBtNrec_l();
7629}
7630
7631void AudioFlinger::RecordThread::checkBtNrec_l()
7632{
7633 // disable AEC and NS if the device is a BT SCO headset supporting those
7634 // pre processings
7635 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7636 mAudioFlinger->btNrecIsOff();
7637 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7638 for (size_t i = 0; i < mEffectChains.size(); i++) {
7639 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7640 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7641 }
7642 }
7643}
7644
Andy Hung97a893e2015-03-29 01:03:07 -07007645
Eric Laurent10351942014-05-08 18:49:52 -07007646bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7647 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007648{
7649 bool reconfig = false;
7650
Eric Laurent10351942014-05-08 18:49:52 -07007651 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007652
Eric Laurent10351942014-05-08 18:49:52 -07007653 audio_format_t reqFormat = mFormat;
7654 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007655 // 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 -07007656 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7657
7658 AudioParameter param = AudioParameter(keyValuePair);
7659 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007660
7661 // scope for AutoPark extends to end of method
7662 AutoPark<FastCapture> park(mFastCapture);
7663
Eric Laurent10351942014-05-08 18:49:52 -07007664 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7665 // channel count change can be requested. Do we mandate the first client defines the
7666 // HAL sampling rate and channel count or do we allow changes on the fly?
7667 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7668 samplingRate = value;
7669 reconfig = true;
7670 }
7671 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007672 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007673 status = BAD_VALUE;
7674 } else {
7675 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007676 reconfig = true;
7677 }
Eric Laurent10351942014-05-08 18:49:52 -07007678 }
7679 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7680 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007681 if (!audio_is_input_channel(mask) ||
7682 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007683 status = BAD_VALUE;
7684 } else {
7685 channelMask = mask;
7686 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007687 }
Eric Laurent10351942014-05-08 18:49:52 -07007688 }
7689 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7690 // do not accept frame count changes if tracks are open as the track buffer
7691 // size depends on frame count and correct behavior would not be guaranteed
7692 // if frame count is changed after track creation
7693 if (mActiveTracks.size() > 0) {
7694 status = INVALID_OPERATION;
7695 } else {
7696 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007697 }
Eric Laurent10351942014-05-08 18:49:52 -07007698 }
7699 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7700 // forward device change to effects that have requested to be
7701 // aware of attached audio device.
7702 for (size_t i = 0; i < mEffectChains.size(); i++) {
7703 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007704 }
Eric Laurent81784c32012-11-19 14:55:58 -08007705
Eric Laurent10351942014-05-08 18:49:52 -07007706 // store input device and output device but do not forward output device to audio HAL.
7707 // Note that status is ignored by the caller for output device
7708 // (see AudioFlinger::setParameters()
7709 if (audio_is_output_devices(value)) {
7710 mOutDevice = value;
7711 status = BAD_VALUE;
7712 } else {
7713 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007714 if (value != AUDIO_DEVICE_NONE) {
7715 mPrevInDevice = value;
7716 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007717 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007718 }
Eric Laurent10351942014-05-08 18:49:52 -07007719 }
7720 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7721 mAudioSource != (audio_source_t)value) {
7722 // forward device change to effects that have requested to be
7723 // aware of attached audio device.
7724 for (size_t i = 0; i < mEffectChains.size(); i++) {
7725 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007726 }
Eric Laurent10351942014-05-08 18:49:52 -07007727 mAudioSource = (audio_source_t)value;
7728 }
Glenn Kastene198c362013-08-13 09:13:36 -07007729
Eric Laurent10351942014-05-08 18:49:52 -07007730 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007731 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007732 if (status == INVALID_OPERATION) {
7733 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007734 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007735 }
7736 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007737 if (status == BAD_VALUE) {
7738 uint32_t sRate;
7739 audio_channel_mask_t channelMask;
7740 audio_format_t format;
7741 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7742 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7743 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7744 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7745 status = NO_ERROR;
7746 }
Eric Laurent81784c32012-11-19 14:55:58 -08007747 }
Eric Laurent10351942014-05-08 18:49:52 -07007748 if (status == NO_ERROR) {
7749 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007750 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007751 }
7752 }
Eric Laurent81784c32012-11-19 14:55:58 -08007753 }
Eric Laurent10351942014-05-08 18:49:52 -07007754
Eric Laurent81784c32012-11-19 14:55:58 -08007755 return reconfig;
7756}
7757
7758String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7759{
Eric Laurent81784c32012-11-19 14:55:58 -08007760 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007761 if (initCheck() == NO_ERROR) {
7762 String8 out_s8;
7763 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7764 return out_s8;
7765 }
Eric Laurent81784c32012-11-19 14:55:58 -08007766 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007767 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007768}
7769
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007770void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007771 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7772
7773 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007774
7775 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007776 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007777 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007778 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007779 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007780 desc->mChannelMask = mChannelMask;
7781 desc->mSamplingRate = mSampleRate;
7782 desc->mFormat = mFormat;
7783 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007784 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007785 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007786 break;
7787
Eric Laurent73e26b62015-04-27 16:55:58 -07007788 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007789 default:
7790 break;
7791 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007792 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007793}
7794
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007795void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007796{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007797 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7798 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07007799 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007800 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
7801 if (audio_is_linear_pcm(mFormat)) {
7802 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
7803 mChannelCount, FCC_8);
7804 } else {
7805 // Can have more that FCC_8 channels in encoded streams.
7806 ALOGI("HAL format %#x is not linear pcm", mFormat);
7807 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007808 result = mInput->stream->getFrameSize(&mFrameSize);
7809 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7810 result = mInput->stream->getBufferSize(&mBufferSize);
7811 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007812 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007813 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7814 "mBufferSize=%lld, mFrameCount=%lld",
7815 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7816 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007817 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007818 // 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 -07007819 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007820 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007821 // A larger value should allow more old data to be read after a track calls start(),
7822 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007823 //
7824 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007825 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007826 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007827 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007828 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007829
7830 // TODO optimize audio capture buffer sizes ...
7831 // Here we calculate the size of the sliding buffer used as a source
7832 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7833 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7834 // be better to have it derived from the pipe depth in the long term.
7835 // The current value is higher than necessary. However it should not add to latency.
7836
Glenn Kasten85948432013-08-19 12:09:05 -07007837 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007838 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7839 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007840 // if posix_memalign fails, will segv here.
7841 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007842
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007843 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7844 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007845}
7846
Glenn Kasten5f972c02014-01-13 09:59:31 -08007847uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007848{
7849 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007850 uint32_t result;
7851 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7852 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007853 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007854 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007855}
7856
Eric Laurent4c415062016-06-17 16:14:16 -07007857// hasAudioSession_l() must be called with ThreadBase::mLock held
7858uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007859{
Eric Laurent81784c32012-11-19 14:55:58 -08007860 uint32_t result = 0;
7861 if (getEffectChain_l(sessionId) != 0) {
7862 result = EFFECT_SESSION;
7863 }
7864
7865 for (size_t i = 0; i < mTracks.size(); ++i) {
7866 if (sessionId == mTracks[i]->sessionId()) {
7867 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007868 if (mTracks[i]->isFastTrack()) {
7869 result |= FAST_SESSION;
7870 }
Eric Laurent81784c32012-11-19 14:55:58 -08007871 break;
7872 }
7873 }
7874
7875 return result;
7876}
7877
Glenn Kastend848eb42016-03-08 13:42:11 -08007878KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007879{
Glenn Kastend848eb42016-03-08 13:42:11 -08007880 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007881 Mutex::Autolock _l(mLock);
7882 for (size_t j = 0; j < mTracks.size(); ++j) {
7883 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007884 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007885 if (ids.indexOfKey(sessionId) < 0) {
7886 ids.add(sessionId, true);
7887 }
7888 }
7889 return ids;
7890}
7891
7892AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7893{
7894 Mutex::Autolock _l(mLock);
7895 AudioStreamIn *input = mInput;
7896 mInput = NULL;
7897 return input;
7898}
7899
7900// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007901sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007902{
7903 if (mInput == NULL) {
7904 return NULL;
7905 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007906 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007907}
7908
7909status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7910{
7911 // only one chain per input thread
7912 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007913 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007914 return INVALID_OPERATION;
7915 }
7916 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007917 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007918 chain->setInBuffer(NULL);
7919 chain->setOutBuffer(NULL);
7920
7921 checkSuspendOnAddEffectChain_l(chain);
7922
Eric Laurent1b928682014-10-02 19:41:47 -07007923 // make sure enabled pre processing effects state is communicated to the HAL as we
7924 // just moved them to a new input stream.
7925 chain->syncHalEffectsState();
7926
Eric Laurent81784c32012-11-19 14:55:58 -08007927 mEffectChains.add(chain);
7928
7929 return NO_ERROR;
7930}
7931
7932size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7933{
7934 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7935 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007936 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007937 chain.get(), mEffectChains.size(), this);
7938 if (mEffectChains.size() == 1) {
7939 mEffectChains.removeAt(0);
7940 }
7941 return 0;
7942}
7943
Eric Laurent1c333e22014-05-20 10:48:17 -07007944status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7945 audio_patch_handle_t *handle)
7946{
7947 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007948
7949 // store new device and send to effects
7950 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007951 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007952 for (size_t i = 0; i < mEffectChains.size(); i++) {
7953 mEffectChains[i]->setDevice_l(mInDevice);
7954 }
7955
Eric Laurentd8365c52017-07-16 15:27:05 -07007956 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007957
7958 // store new source and send to effects
7959 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7960 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007961 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007962 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007963 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007964 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007965
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007966 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007967 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7968 status = hwDevice->createAudioPatch(patch->num_sources,
7969 patch->sources,
7970 patch->num_sinks,
7971 patch->sinks,
7972 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007973 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007974 char *address;
7975 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7976 address = audio_device_address_to_parameter(
7977 patch->sources[0].ext.device.type,
7978 patch->sources[0].ext.device.address);
7979 } else {
7980 address = (char *)calloc(1, 1);
7981 }
7982 AudioParameter param = AudioParameter(String8(address));
7983 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007984 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007985 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007986 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007987 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007988 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007989 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007990 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007991
Eric Laurente8726fe2015-06-26 09:39:24 -07007992 if (mInDevice != mPrevInDevice) {
7993 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7994 mPrevInDevice = mInDevice;
7995 }
Eric Laurent296fb132015-05-01 11:38:42 -07007996
Eric Laurent1c333e22014-05-20 10:48:17 -07007997 return status;
7998}
7999
8000status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8001{
8002 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008003
8004 mInDevice = AUDIO_DEVICE_NONE;
8005
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008006 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008007 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8008 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008009 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008010 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008011 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008012 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008013 }
8014 return status;
8015}
8016
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008017void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008018{
8019 Mutex::Autolock _l(mLock);
8020 mTracks.add(record);
8021}
8022
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008023void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008024{
8025 Mutex::Autolock _l(mLock);
8026 destroyTrack_l(record);
8027}
8028
Mikhail Naganovdc769682018-05-04 15:34:08 -07008029void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008030{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008031 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008032 config->role = AUDIO_PORT_ROLE_SINK;
8033 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8034 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008035 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8036 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8037 config->flags.input = mInput->flags;
8038 }
Eric Laurent83b88082014-06-20 18:31:16 -07008039}
Eric Laurent1c333e22014-05-20 10:48:17 -07008040
Eric Laurent6acd1d42017-01-04 14:23:29 -08008041// ----------------------------------------------------------------------------
8042// Mmap
8043// ----------------------------------------------------------------------------
8044
8045AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8046 : mThread(thread)
8047{
Phil Burk9fabbf82017-08-03 12:02:00 -07008048 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008049}
8050
8051AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8052{
Phil Burk9fabbf82017-08-03 12:02:00 -07008053 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008054}
8055
8056status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8057 struct audio_mmap_buffer_info *info)
8058{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008059 return mThread->createMmapBuffer(minSizeFrames, info);
8060}
8061
8062status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8063{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008064 return mThread->getMmapPosition(position);
8065}
8066
Eric Laurenta54f1282017-07-01 19:39:32 -07008067status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008068 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008069
8070{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008071 return mThread->start(client, handle);
8072}
8073
8074status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8075{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008076 return mThread->stop(handle);
8077}
8078
Eric Laurent18b57012017-02-13 16:23:52 -08008079status_t AudioFlinger::MmapThreadHandle::standby()
8080{
Eric Laurent18b57012017-02-13 16:23:52 -08008081 return mThread->standby();
8082}
8083
Eric Laurent6acd1d42017-01-04 14:23:29 -08008084
8085AudioFlinger::MmapThread::MmapThread(
8086 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8087 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8088 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8089 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008090 mSessionId(AUDIO_SESSION_NONE),
8091 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008092 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008093 mActiveTracks(&this->mLocalLog),
8094 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8095 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008096{
Eric Laurent18b57012017-02-13 16:23:52 -08008097 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008098 readHalParameters_l();
8099}
8100
8101AudioFlinger::MmapThread::~MmapThread()
8102{
Eric Laurent18b57012017-02-13 16:23:52 -08008103 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008104}
8105
8106void AudioFlinger::MmapThread::onFirstRef()
8107{
8108 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8109}
8110
8111void AudioFlinger::MmapThread::disconnect()
8112{
Eric Laurent331679c2018-04-16 17:03:16 -07008113 ActiveTracks<MmapTrack> activeTracks;
8114 {
8115 Mutex::Autolock _l(mLock);
8116 for (const sp<MmapTrack> &t : mActiveTracks) {
8117 activeTracks.add(t);
8118 }
8119 }
8120 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008121 stop(t->portId());
8122 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008123 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008124 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008125 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008126 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008127 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008128 }
8129}
8130
8131
8132void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8133 audio_stream_type_t streamType __unused,
8134 audio_session_t sessionId,
8135 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008136 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008137 audio_port_handle_t portId)
8138{
8139 mAttr = *attr;
8140 mSessionId = sessionId;
8141 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008142 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008143 mPortId = portId;
8144}
8145
8146status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8147 struct audio_mmap_buffer_info *info)
8148{
8149 if (mHalStream == 0) {
8150 return NO_INIT;
8151 }
Eric Laurent18b57012017-02-13 16:23:52 -08008152 mStandby = true;
8153 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008154 return mHalStream->createMmapBuffer(minSizeFrames, info);
8155}
8156
8157status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8158{
8159 if (mHalStream == 0) {
8160 return NO_INIT;
8161 }
8162 return mHalStream->getMmapPosition(position);
8163}
8164
Eric Laurent331679c2018-04-16 17:03:16 -07008165status_t AudioFlinger::MmapThread::exitStandby()
8166{
8167 status_t ret = mHalStream->start();
8168 if (ret != NO_ERROR) {
8169 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8170 return ret;
8171 }
8172 mStandby = false;
8173 return NO_ERROR;
8174}
8175
Eric Laurenta54f1282017-07-01 19:39:32 -07008176status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008177 audio_port_handle_t *handle)
8178{
Eric Laurenta54f1282017-07-01 19:39:32 -07008179 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8180 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008181 if (mHalStream == 0) {
8182 return NO_INIT;
8183 }
8184
8185 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008186
Eric Laurenta54f1282017-07-01 19:39:32 -07008187 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008188 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008189 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008190 }
8191
8192 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8193
8194 audio_io_handle_t io = mId;
8195 if (isOutput()) {
8196 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8197 config.sample_rate = mSampleRate;
8198 config.channel_mask = mChannelMask;
8199 config.format = mFormat;
8200 audio_stream_type_t stream = streamType();
8201 audio_output_flags_t flags =
8202 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008203 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008204 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8205 mSessionId,
8206 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008207 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008208 client.clientUid,
8209 &config,
8210 flags,
8211 &deviceId,
8212 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008213 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008214 audio_config_base_t config;
8215 config.sample_rate = mSampleRate;
8216 config.channel_mask = mChannelMask;
8217 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008218 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008219 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8220 mSessionId,
8221 client.clientPid,
8222 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008223 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008224 &config,
8225 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8226 &deviceId,
8227 &portId);
8228 }
8229 // APM should not chose a different input or output stream for the same set of attributes
8230 // and audo configuration
8231 if (ret != NO_ERROR || io != mId) {
8232 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8233 __FUNCTION__, ret, io, mId);
8234 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008235 }
8236
Eric Laurent331679c2018-04-16 17:03:16 -07008237 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008238 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008239 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008240 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008241 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008242 }
8243
Eric Laurent331679c2018-04-16 17:03:16 -07008244 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008245 // abort if start is rejected by audio policy manager
8246 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008247 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008248 if (mActiveTracks.size() != 0) {
Eric Laurent331679c2018-04-16 17:03:16 -07008249 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008250 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008251 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008252 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008253 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008254 }
Eric Laurent331679c2018-04-16 17:03:16 -07008255 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008256 } else {
8257 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008258 }
8259 return PERMISSION_DENIED;
8260 }
8261
Eric Laurent67f97292018-04-20 18:05:41 -07008262 if (isOutput()) {
8263 // force volume update when a new track is added
8264 mHalVolFloat = -1.0f;
8265 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008266 for (const sp<MmapTrack> &track : mActiveTracks) {
8267 if (track->isSilenced_l() && track->uid() != client.clientUid)
8268 track->invalidate();
8269 }
8270 }
8271
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008272 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8273 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008274 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008275
Eric Laurent331679c2018-04-16 17:03:16 -07008276 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008277 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008278 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008279 if (chain != 0) {
8280 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8281 chain->incTrackCnt();
8282 chain->incActiveTrackCnt();
8283 }
8284
8285 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008286 broadcast_l();
8287
Eric Laurenta54f1282017-07-01 19:39:32 -07008288 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008289
8290 return NO_ERROR;
8291}
8292
8293status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8294{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008295 ALOGV("%s handle %d", __FUNCTION__, handle);
8296
8297 if (mHalStream == 0) {
8298 return NO_INIT;
8299 }
8300
Eric Laurenta54f1282017-07-01 19:39:32 -07008301 if (handle == mPortId) {
8302 mHalStream->stop();
8303 return NO_ERROR;
8304 }
8305
Eric Laurent331679c2018-04-16 17:03:16 -07008306 Mutex::Autolock _l(mLock);
8307
Eric Laurent6acd1d42017-01-04 14:23:29 -08008308 sp<MmapTrack> track;
8309 for (const sp<MmapTrack> &t : mActiveTracks) {
8310 if (handle == t->portId()) {
8311 track = t;
8312 break;
8313 }
8314 }
8315 if (track == 0) {
8316 return BAD_VALUE;
8317 }
8318
8319 mActiveTracks.remove(track);
8320
Eric Laurent331679c2018-04-16 17:03:16 -07008321 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008322 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008323 AudioSystem::stopOutput(track->portId());
8324 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008325 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008326 AudioSystem::stopInput(track->portId());
8327 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008328 }
Eric Laurent331679c2018-04-16 17:03:16 -07008329 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008330
8331 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8332 if (chain != 0) {
8333 chain->decActiveTrackCnt();
8334 chain->decTrackCnt();
8335 }
8336
8337 broadcast_l();
8338
Eric Laurent6acd1d42017-01-04 14:23:29 -08008339 return NO_ERROR;
8340}
8341
Eric Laurent18b57012017-02-13 16:23:52 -08008342status_t AudioFlinger::MmapThread::standby()
8343{
8344 ALOGV("%s", __FUNCTION__);
8345
8346 if (mHalStream == 0) {
8347 return NO_INIT;
8348 }
8349 if (mActiveTracks.size() != 0) {
8350 return INVALID_OPERATION;
8351 }
8352 mHalStream->standby();
8353 mStandby = true;
8354 releaseWakeLock();
8355 return NO_ERROR;
8356}
8357
Eric Laurent6acd1d42017-01-04 14:23:29 -08008358
8359void AudioFlinger::MmapThread::readHalParameters_l()
8360{
8361 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8362 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8363 mFormat = mHALFormat;
8364 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8365 result = mHalStream->getFrameSize(&mFrameSize);
8366 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8367 result = mHalStream->getBufferSize(&mBufferSize);
8368 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8369 mFrameCount = mBufferSize / mFrameSize;
8370}
8371
8372bool AudioFlinger::MmapThread::threadLoop()
8373{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008374 checkSilentMode_l();
8375
8376 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8377
8378 while (!exitPending())
8379 {
8380 Mutex::Autolock _l(mLock);
8381 Vector< sp<EffectChain> > effectChains;
8382
8383 if (mSignalPending) {
8384 // A signal was raised while we were unlocked
8385 mSignalPending = false;
8386 } else {
8387 if (mConfigEvents.isEmpty()) {
8388 // we're about to wait, flush the binder command buffer
8389 IPCThreadState::self()->flushCommands();
8390
8391 if (exitPending()) {
8392 break;
8393 }
8394
Eric Laurent6acd1d42017-01-04 14:23:29 -08008395 // wait until we have something to do...
8396 ALOGV("%s going to sleep", myName.string());
8397 mWaitWorkCV.wait(mLock);
8398 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008399
8400 checkSilentMode_l();
8401
8402 continue;
8403 }
8404 }
8405
8406 processConfigEvents_l();
8407
8408 processVolume_l();
8409
8410 checkInvalidTracks_l();
8411
8412 mActiveTracks.updatePowerState(this);
8413
Kevin Rocard069c2712018-03-29 19:09:14 -07008414 updateMetadata_l();
8415
Eric Laurent6acd1d42017-01-04 14:23:29 -08008416 lockEffectChains_l(effectChains);
8417 for (size_t i = 0; i < effectChains.size(); i ++) {
8418 effectChains[i]->process_l();
8419 }
8420 // enable changes in effect chain
8421 unlockEffectChains(effectChains);
8422 // Effect chains will be actually deleted here if they were removed from
8423 // mEffectChains list during mixing or effects processing
8424 }
8425
8426 threadLoop_exit();
8427
8428 if (!mStandby) {
8429 threadLoop_standby();
8430 mStandby = true;
8431 }
8432
Eric Laurent6acd1d42017-01-04 14:23:29 -08008433 ALOGV("Thread %p type %d exiting", this, mType);
8434 return false;
8435}
8436
8437// checkForNewParameter_l() must be called with ThreadBase::mLock held
8438bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8439 status_t& status)
8440{
8441 AudioParameter param = AudioParameter(keyValuePair);
8442 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008443 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008444 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008445 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008446 // forward device change to effects that have requested to be
8447 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008448 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008449 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008450 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008451 }
8452 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008453 if (audio_is_output_devices(device)) {
8454 mOutDevice = device;
8455 if (!isOutput()) {
8456 sendToHal = false;
8457 }
8458 } else {
8459 mInDevice = device;
8460 if (device != AUDIO_DEVICE_NONE) {
8461 mPrevInDevice = value;
8462 }
8463 // TODO: implement and call checkBtNrec_l();
8464 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008465 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008466 if (sendToHal) {
8467 status = mHalStream->setParameters(keyValuePair);
8468 } else {
8469 status = NO_ERROR;
8470 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008471
8472 return false;
8473}
8474
8475String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8476{
8477 Mutex::Autolock _l(mLock);
8478 String8 out_s8;
8479 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8480 return out_s8;
8481 }
8482 return String8();
8483}
8484
8485void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8486 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8487
8488 desc->mIoHandle = mId;
8489
8490 switch (event) {
8491 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008492 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008493 case AUDIO_INPUT_CONFIG_CHANGED:
8494 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008495 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008496 case AUDIO_OUTPUT_CONFIG_CHANGED:
8497 desc->mPatch = mPatch;
8498 desc->mChannelMask = mChannelMask;
8499 desc->mSamplingRate = mSampleRate;
8500 desc->mFormat = mFormat;
8501 desc->mFrameCount = mFrameCount;
8502 desc->mFrameCountHAL = mFrameCount;
8503 desc->mLatency = 0;
8504 break;
8505
8506 case AUDIO_INPUT_CLOSED:
8507 case AUDIO_OUTPUT_CLOSED:
8508 default:
8509 break;
8510 }
8511 mAudioFlinger->ioConfigChanged(event, desc, pid);
8512}
8513
8514status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8515 audio_patch_handle_t *handle)
8516{
8517 status_t status = NO_ERROR;
8518
8519 // store new device and send to effects
8520 audio_devices_t type = AUDIO_DEVICE_NONE;
8521 audio_port_handle_t deviceId;
8522 if (isOutput()) {
8523 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8524 type |= patch->sinks[i].ext.device.type;
8525 }
8526 deviceId = patch->sinks[0].id;
8527 } else {
8528 type = patch->sources[0].ext.device.type;
8529 deviceId = patch->sources[0].id;
8530 }
8531
8532 for (size_t i = 0; i < mEffectChains.size(); i++) {
8533 mEffectChains[i]->setDevice_l(type);
8534 }
8535
8536 if (isOutput()) {
8537 mOutDevice = type;
8538 } else {
8539 mInDevice = type;
8540 // store new source and send to effects
8541 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8542 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8543 for (size_t i = 0; i < mEffectChains.size(); i++) {
8544 mEffectChains[i]->setAudioSource_l(mAudioSource);
8545 }
8546 }
8547 }
8548
8549 if (mAudioHwDev->supportsAudioPatches()) {
8550 status = mHalDevice->createAudioPatch(patch->num_sources,
8551 patch->sources,
8552 patch->num_sinks,
8553 patch->sinks,
8554 handle);
8555 } else {
8556 char *address;
8557 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8558 //FIXME: we only support address on first sink with HAL version < 3.0
8559 address = audio_device_address_to_parameter(
8560 patch->sinks[0].ext.device.type,
8561 patch->sinks[0].ext.device.address);
8562 } else {
8563 address = (char *)calloc(1, 1);
8564 }
8565 AudioParameter param = AudioParameter(String8(address));
8566 free(address);
8567 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8568 if (!isOutput()) {
8569 param.addInt(String8(AudioParameter::keyInputSource),
8570 (int)patch->sinks[0].ext.mix.usecase.source);
8571 }
8572 status = mHalStream->setParameters(param.toString());
8573 *handle = AUDIO_PATCH_HANDLE_NONE;
8574 }
8575
8576 if (isOutput() && mPrevOutDevice != mOutDevice) {
8577 mPrevOutDevice = type;
8578 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008579 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008580 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008581 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008582 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008583 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008584 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008585 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008586 }
8587 if (!isOutput() && mPrevInDevice != mInDevice) {
8588 mPrevInDevice = type;
8589 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008590 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008591 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008592 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008593 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008594 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008595 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008596 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008597 }
8598 return status;
8599}
8600
8601status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8602{
8603 status_t status = NO_ERROR;
8604
8605 mInDevice = AUDIO_DEVICE_NONE;
8606
8607 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8608 supportsAudioPatches : false;
8609
8610 if (supportsAudioPatches) {
8611 status = mHalDevice->releaseAudioPatch(handle);
8612 } else {
8613 AudioParameter param;
8614 param.addInt(String8(AudioParameter::keyRouting), 0);
8615 status = mHalStream->setParameters(param.toString());
8616 }
8617 return status;
8618}
8619
Mikhail Naganovdc769682018-05-04 15:34:08 -07008620void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008621{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008622 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008623 if (isOutput()) {
8624 config->role = AUDIO_PORT_ROLE_SOURCE;
8625 config->ext.mix.hw_module = mAudioHwDev->handle();
8626 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8627 } else {
8628 config->role = AUDIO_PORT_ROLE_SINK;
8629 config->ext.mix.hw_module = mAudioHwDev->handle();
8630 config->ext.mix.usecase.source = mAudioSource;
8631 }
8632}
8633
8634status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8635{
8636 audio_session_t session = chain->sessionId();
8637
8638 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8639 // Attach all tracks with same session ID to this chain.
8640 // indicate all active tracks in the chain
8641 for (const sp<MmapTrack> &track : mActiveTracks) {
8642 if (session == track->sessionId()) {
8643 chain->incTrackCnt();
8644 chain->incActiveTrackCnt();
8645 }
8646 }
8647
8648 chain->setThread(this);
8649 chain->setInBuffer(nullptr);
8650 chain->setOutBuffer(nullptr);
8651 chain->syncHalEffectsState();
8652
8653 mEffectChains.add(chain);
8654 checkSuspendOnAddEffectChain_l(chain);
8655 return NO_ERROR;
8656}
8657
8658size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8659{
8660 audio_session_t session = chain->sessionId();
8661
8662 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8663
8664 for (size_t i = 0; i < mEffectChains.size(); i++) {
8665 if (chain == mEffectChains[i]) {
8666 mEffectChains.removeAt(i);
8667 // detach all active tracks from the chain
8668 // detach all tracks with same session ID from this chain
8669 for (const sp<MmapTrack> &track : mActiveTracks) {
8670 if (session == track->sessionId()) {
8671 chain->decActiveTrackCnt();
8672 chain->decTrackCnt();
8673 }
8674 }
8675 break;
8676 }
8677 }
8678 return mEffectChains.size();
8679}
8680
8681// hasAudioSession_l() must be called with ThreadBase::mLock held
8682uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8683{
8684 uint32_t result = 0;
8685 if (getEffectChain_l(sessionId) != 0) {
8686 result = EFFECT_SESSION;
8687 }
8688
8689 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8690 sp<MmapTrack> track = mActiveTracks[i];
8691 if (sessionId == track->sessionId()) {
8692 result |= TRACK_SESSION;
8693 if (track->isFastTrack()) {
8694 result |= FAST_SESSION;
8695 }
8696 break;
8697 }
8698 }
8699
8700 return result;
8701}
8702
8703void AudioFlinger::MmapThread::threadLoop_standby()
8704{
8705 mHalStream->standby();
8706}
8707
8708void AudioFlinger::MmapThread::threadLoop_exit()
8709{
Phil Burk7dce7282017-09-27 13:51:41 -07008710 // Do not call callback->onTearDown() because it is redundant for thread exit
8711 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008712}
8713
8714status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8715{
8716 return BAD_VALUE;
8717}
8718
8719bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8720{
8721 return false;
8722}
8723
8724status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8725 const effect_descriptor_t *desc, audio_session_t sessionId)
8726{
8727 // No global effect sessions on mmap threads
8728 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8729 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8730 desc->name, mThreadName);
8731 return BAD_VALUE;
8732 }
8733
8734 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8735 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8736 desc->name);
8737 return BAD_VALUE;
8738 }
8739 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008740 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8741 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008742 return BAD_VALUE;
8743 }
8744
8745 // Only allow effects without processing load or latency
8746 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8747 return BAD_VALUE;
8748 }
8749
8750 return NO_ERROR;
8751
8752}
8753
8754void AudioFlinger::MmapThread::checkInvalidTracks_l()
8755{
8756 for (const sp<MmapTrack> &track : mActiveTracks) {
8757 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008758 sp<MmapStreamCallback> callback = mCallback.promote();
8759 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008760 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008761 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008762 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008763 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8764 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8765 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008766 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008767 }
8768 }
8769}
8770
8771void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8772{
8773 dumpInternals(fd, args);
8774 dumpTracks(fd, args);
8775 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008776 dprintf(fd, " Local log:\n");
8777 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008778}
8779
8780void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8781{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008782 dumpBase(fd, args);
8783
8784 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8785 mAttr.content_type, mAttr.usage, mAttr.source);
8786 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8787 if (mActiveTracks.size() == 0) {
8788 dprintf(fd, " No active clients\n");
8789 }
8790}
8791
8792void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8793{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008794 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008795 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008796 dprintf(fd, " %zu Tracks\n", numtracks);
8797 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008798 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008799 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008800 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008801 for (size_t i = 0; i < numtracks ; ++i) {
8802 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008803 result.append(prefix);
8804 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008805 }
8806 } else {
8807 dprintf(fd, "\n");
8808 }
8809 write(fd, result.string(), result.size());
8810}
8811
8812AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8813 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8814 AudioHwDevice *hwDev, AudioStreamOut *output,
8815 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8816 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8817 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008818 mStreamVolume(1.0),
8819 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008820 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008821{
8822 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8823 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8824 mMasterVolume = audioFlinger->masterVolume_l();
8825 mMasterMute = audioFlinger->masterMute_l();
8826 if (mAudioHwDev) {
8827 if (mAudioHwDev->canSetMasterVolume()) {
8828 mMasterVolume = 1.0;
8829 }
8830
8831 if (mAudioHwDev->canSetMasterMute()) {
8832 mMasterMute = false;
8833 }
8834 }
8835}
8836
8837void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8838 audio_stream_type_t streamType,
8839 audio_session_t sessionId,
8840 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008841 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008842 audio_port_handle_t portId)
8843{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008844 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008845 mStreamType = streamType;
8846}
8847
8848AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8849{
8850 Mutex::Autolock _l(mLock);
8851 AudioStreamOut *output = mOutput;
8852 mOutput = NULL;
8853 return output;
8854}
8855
8856void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8857{
8858 Mutex::Autolock _l(mLock);
8859 // Don't apply master volume in SW if our HAL can do it for us.
8860 if (mAudioHwDev &&
8861 mAudioHwDev->canSetMasterVolume()) {
8862 mMasterVolume = 1.0;
8863 } else {
8864 mMasterVolume = value;
8865 }
8866}
8867
8868void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8869{
8870 Mutex::Autolock _l(mLock);
8871 // Don't apply master mute in SW if our HAL can do it for us.
8872 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8873 mMasterMute = false;
8874 } else {
8875 mMasterMute = muted;
8876 }
8877}
8878
8879void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8880{
8881 Mutex::Autolock _l(mLock);
8882 if (stream == mStreamType) {
8883 mStreamVolume = value;
8884 broadcast_l();
8885 }
8886}
8887
8888float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8889{
8890 Mutex::Autolock _l(mLock);
8891 if (stream == mStreamType) {
8892 return mStreamVolume;
8893 }
8894 return 0.0f;
8895}
8896
8897void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8898{
8899 Mutex::Autolock _l(mLock);
8900 if (stream == mStreamType) {
8901 mStreamMute= muted;
8902 broadcast_l();
8903 }
8904}
8905
8906void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8907{
8908 Mutex::Autolock _l(mLock);
8909 if (streamType == mStreamType) {
8910 for (const sp<MmapTrack> &track : mActiveTracks) {
8911 track->invalidate();
8912 }
8913 broadcast_l();
8914 }
8915}
8916
8917void AudioFlinger::MmapPlaybackThread::processVolume_l()
8918{
8919 float volume;
8920
8921 if (mMasterMute || mStreamMute) {
8922 volume = 0;
8923 } else {
8924 volume = mMasterVolume * mStreamVolume;
8925 }
8926
8927 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008928
8929 // Convert volumes from float to 8.24
8930 uint32_t vol = (uint32_t)(volume * (1 << 24));
8931
8932 // Delegate volume control to effect in track effect chain if needed
8933 // only one effect chain can be present on DirectOutputThread, so if
8934 // there is one, the track is connected to it
8935 if (!mEffectChains.isEmpty()) {
8936 mEffectChains[0]->setVolume_l(&vol, &vol);
8937 volume = (float)vol / (1 << 24);
8938 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008939 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008940 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8941 mHalVolFloat = volume; // HW volume control worked, so update value.
8942 mNoCallbackWarningCount = 0;
8943 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008944 sp<MmapStreamCallback> callback = mCallback.promote();
8945 if (callback != 0) {
8946 int channelCount;
8947 if (isOutput()) {
8948 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8949 } else {
8950 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8951 }
8952 Vector<float> values;
8953 for (int i = 0; i < channelCount; i++) {
8954 values.add(volume);
8955 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07008956 mHalVolFloat = volume; // SW volume control worked, so update value.
8957 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07008958 mLock.unlock();
8959 callback->onVolumeChanged(mChannelMask, values);
8960 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008961 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008962 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8963 ALOGW("Could not set MMAP stream volume: no volume callback!");
8964 mNoCallbackWarningCount++;
8965 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008966 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008967 }
8968 }
8969}
8970
Kevin Rocard069c2712018-03-29 19:09:14 -07008971void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
8972{
8973 if (mOutput == nullptr || mOutput->stream == nullptr ||
8974 !mActiveTracks.readAndClearHasChanged()) {
8975 return;
8976 }
8977 StreamOutHalInterface::SourceMetadata metadata;
8978 for (const sp<MmapTrack> &track : mActiveTracks) {
8979 // No track is invalid as this is called after prepareTrack_l in the same critical section
8980 metadata.tracks.push_back({
8981 .usage = track->attributes().usage,
8982 .content_type = track->attributes().content_type,
8983 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
8984 });
8985 }
8986 mOutput->stream->updateSourceMetadata(metadata);
8987}
8988
Eric Laurent6acd1d42017-01-04 14:23:29 -08008989void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8990{
8991 if (!mMasterMute) {
8992 char value[PROPERTY_VALUE_MAX];
8993 if (property_get("ro.audio.silent", value, "0") > 0) {
8994 char *endptr;
8995 unsigned long ul = strtoul(value, &endptr, 0);
8996 if (*endptr == '\0' && ul != 0) {
8997 ALOGD("Silence is golden");
8998 // The setprop command will not allow a property to be changed after
8999 // the first time it is set, so we don't have to worry about un-muting.
9000 setMasterMute_l(true);
9001 }
9002 }
9003 }
9004}
9005
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009006void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9007{
9008 MmapThread::toAudioPortConfig(config);
9009 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9010 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9011 config->flags.output = mOutput->flags;
9012 }
9013}
9014
Eric Laurent6acd1d42017-01-04 14:23:29 -08009015void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9016{
9017 MmapThread::dumpInternals(fd, args);
9018
Glenn Kastend3bb6452016-12-05 18:14:37 -08009019 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9020 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009021 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9022}
9023
9024AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9025 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9026 AudioHwDevice *hwDev, AudioStreamIn *input,
9027 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9028 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9029 mInput(input)
9030{
9031 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9032 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9033}
9034
Eric Laurent331679c2018-04-16 17:03:16 -07009035status_t AudioFlinger::MmapCaptureThread::exitStandby()
9036{
9037 mInput->stream->setGain(1.0f);
9038 return MmapThread::exitStandby();
9039}
9040
Eric Laurent6acd1d42017-01-04 14:23:29 -08009041AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9042{
9043 Mutex::Autolock _l(mLock);
9044 AudioStreamIn *input = mInput;
9045 mInput = NULL;
9046 return input;
9047}
Kevin Rocard069c2712018-03-29 19:09:14 -07009048
Eric Laurent331679c2018-04-16 17:03:16 -07009049
9050void AudioFlinger::MmapCaptureThread::processVolume_l()
9051{
9052 bool changed = false;
9053 bool silenced = false;
9054
9055 sp<MmapStreamCallback> callback = mCallback.promote();
9056 if (callback == 0) {
9057 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9058 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9059 mNoCallbackWarningCount++;
9060 }
9061 }
9062
9063 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9064 // track is silenced and unmute otherwise
9065 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9066 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9067 changed = true;
9068 silenced = mActiveTracks[i]->isSilenced_l();
9069 }
9070 }
9071
9072 if (changed) {
9073 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9074 }
9075}
9076
Kevin Rocard069c2712018-03-29 19:09:14 -07009077void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9078{
9079 if (mInput == nullptr || mInput->stream == nullptr ||
9080 !mActiveTracks.readAndClearHasChanged()) {
9081 return;
9082 }
9083 StreamInHalInterface::SinkMetadata metadata;
9084 for (const sp<MmapTrack> &track : mActiveTracks) {
9085 // No track is invalid as this is called after prepareTrack_l in the same critical section
9086 metadata.tracks.push_back({
9087 .source = track->attributes().source,
9088 .gain = 1, // capture tracks do not have volumes
9089 });
9090 }
9091 mInput->stream->updateSinkMetadata(metadata);
9092}
9093
Eric Laurent331679c2018-04-16 17:03:16 -07009094void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9095{
9096 Mutex::Autolock _l(mLock);
9097 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9098 if (mActiveTracks[i]->uid() == uid) {
9099 mActiveTracks[i]->setSilenced_l(silenced);
9100 broadcast_l();
9101 }
9102 }
9103}
9104
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009105void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9106{
9107 MmapThread::toAudioPortConfig(config);
9108 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9109 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9110 config->flags.input = mInput->flags;
9111 }
9112}
9113
Glenn Kasten63238ef2015-03-02 15:50:29 -08009114} // namespace android