blob: 58fb83ad409e79ac8e74eaca61f2a254a5969b49 [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>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080032#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070033#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080035#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036
37#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070038#include <private/android_filesystem_config.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080039#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070043#include <system/audio_effects/effect_ns.h>
44#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046
47// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070048#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <media/nbaio/AudioStreamOutSink.h>
50#include <media/nbaio/MonoPipe.h>
51#include <media/nbaio/MonoPipeReader.h>
52#include <media/nbaio/Pipe.h>
53#include <media/nbaio/PipeReader.h>
54#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080055#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57#include <powermanager/PowerManager.h>
58
Kevin Rocard7588ff42018-01-08 11:11:30 -080059#include <media/audiohal/EffectsFactoryHalInterface.h>
60
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070063#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070065#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080066
Eric Laurent81784c32012-11-19 14:55:58 -080067#ifdef ADD_BATTERY_DATA
68#include <media/IMediaPlayerService.h>
69#include <media/IMediaDeathNotifier.h>
70#endif
71
Eric Laurent81784c32012-11-19 14:55:58 -080072#ifdef DEBUG_CPU_USAGE
73#include <cpustats/CentralTendencyStatistics.h>
74#include <cpustats/ThreadCpuUsage.h>
75#endif
76
Glenn Kastenc05b8d72016-03-24 09:48:17 -070077#include "AutoPark.h"
78
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080079#include <pthread.h>
80#include "TypedLogger.h"
81
Eric Laurent81784c32012-11-19 14:55:58 -080082// ----------------------------------------------------------------------------
83
84// Note: the following macro is used for extremely verbose logging message. In
85// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
86// 0; but one side effect of this is to turn all LOGV's as well. Some messages
87// are so verbose that we want to suppress them even when we have ALOG_ASSERT
88// turned on. Do not uncomment the #def below unless you really know what you
89// are doing and want to see all of the extremely verbose messages.
90//#define VERY_VERY_VERBOSE_LOGGING
91#ifdef VERY_VERY_VERBOSE_LOGGING
92#define ALOGVV ALOGV
93#else
94#define ALOGVV(a...) do { } while(0)
95#endif
96
Andy Hung6770c6f2015-04-07 13:43:36 -070097// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070098#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070099template <typename T>
100static inline T min(const T& a, const T& b)
101{
102 return a < b ? a : b;
103}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700104
Eric Laurent81784c32012-11-19 14:55:58 -0800105namespace android {
106
107// retry counts for buffer fill timeout
108// 50 * ~20msecs = 1 second
109static const int8_t kMaxTrackRetries = 50;
110static const int8_t kMaxTrackStartupRetries = 50;
111// allow less retry attempts on direct output thread.
112// direct outputs can be a scarce resource in audio hardware and should
113// be released as quickly as possible.
114static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700115
Eric Laurent51716182016-02-29 18:00:56 -0800116
Eric Laurent81784c32012-11-19 14:55:58 -0800117
118// don't warn about blocked writes or record buffer overflows more often than this
119static const nsecs_t kWarningThrottleNs = seconds(5);
120
121// RecordThread loop sleep time upon application overrun or audio HAL read error
122static const int kRecordThreadSleepUs = 5000;
123
Eric Laurent10351942014-05-08 18:49:52 -0700124// maximum time to wait in sendConfigEvent_l() for a status to be received
125static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800126
127// minimum sleep time for the mixer thread loop when tracks are active but in underrun
128static const uint32_t kMinThreadSleepTimeUs = 5000;
129// maximum divider applied to the active sleep time in the mixer thread loop
130static const uint32_t kMaxThreadSleepTimeShift = 2;
131
Andy Hung09a50072014-02-27 14:30:47 -0800132// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700133// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800134static const uint32_t kMinNormalSinkBufferSizeMs = 20;
135// maximum normal sink buffer size
136static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800137
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700138// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
139// FIXME This should be based on experimentally observed scheduling jitter
140static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
141
Eric Laurent972a1732013-09-04 09:42:59 -0700142// Offloaded output thread standby delay: allows track transition without going to standby
143static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
144
Eric Laurent51716182016-02-29 18:00:56 -0800145// Direct output thread minimum sleep time in idle or active(underrun) state
146static const nsecs_t kDirectMinSleepTimeUs = 10000;
147
Glenn Kasten1b291842016-07-18 14:55:21 -0700148// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
149// balance between power consumption and latency, and allows threads to be scheduled reliably
150// by the CFS scheduler.
151// FIXME Express other hardcoded references to 20ms with references to this constant and move
152// it appropriately.
153#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800154
Eric Laurent81784c32012-11-19 14:55:58 -0800155// Whether to use fast mixer
156static const enum {
157 FastMixer_Never, // never initialize or use: for debugging only
158 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
159 // normal mixer multiplier is 1
160 FastMixer_Static, // initialize if needed, then use all the time if initialized,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
163 // multiplier is calculated based on min & max normal mixer buffer size
164 // FIXME for FastMixer_Dynamic:
165 // Supporting this option will require fixing HALs that can't handle large writes.
166 // For example, one HAL implementation returns an error from a large write,
167 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
168 // We could either fix the HAL implementations, or provide a wrapper that breaks
169 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
170} kUseFastMixer = FastMixer_Static;
171
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700172// Whether to use fast capture
173static const enum {
174 FastCapture_Never, // never initialize or use: for debugging only
175 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
176 FastCapture_Static, // initialize if needed, then use all the time if initialized
177} kUseFastCapture = FastCapture_Static;
178
Eric Laurent81784c32012-11-19 14:55:58 -0800179// Priorities for requestPriority
180static const int kPriorityAudioApp = 2;
181static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700182static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800183
Glenn Kastenea38ee72016-04-18 11:08:01 -0700184// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
185// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
186// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700187
188// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800189static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800190
Glenn Kasten03490092014-05-27 12:30:54 -0700191// The minimum and maximum allowed values
192static const int kFastTrackMultiplierMin = 1;
193static const int kFastTrackMultiplierMax = 2;
194
195// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
196static int sFastTrackMultiplier = kFastTrackMultiplier;
197
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700198// See Thread::readOnlyHeap().
199// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
200// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
201// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten691b02a2017-10-03 10:12:20 -0700202static const size_t kRecordThreadReadOnlyHeapSize = 0x4000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700203
Eric Laurent81784c32012-11-19 14:55:58 -0800204// ----------------------------------------------------------------------------
205
Glenn Kasten03490092014-05-27 12:30:54 -0700206static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
207
208static void sFastTrackMultiplierInit()
209{
210 char value[PROPERTY_VALUE_MAX];
211 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
212 char *endptr;
213 unsigned long ul = strtoul(value, &endptr, 0);
214 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
215 sFastTrackMultiplier = (int) ul;
216 }
217 }
218}
219
220// ----------------------------------------------------------------------------
221
Eric Laurent81784c32012-11-19 14:55:58 -0800222#ifdef ADD_BATTERY_DATA
223// To collect the amplifier usage
224static void addBatteryData(uint32_t params) {
225 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
226 if (service == NULL) {
227 // it already logged
228 return;
229 }
230
231 service->addBatteryData(params);
232}
233#endif
234
Andy Hung3f0c9022016-01-15 17:49:46 -0800235// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
236struct {
237 // call when you acquire a partial wakelock
238 void acquire(const sp<IBinder> &wakeLockToken) {
239 pthread_mutex_lock(&mLock);
240 if (wakeLockToken.get() == nullptr) {
241 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
242 } else {
243 if (mCount == 0) {
244 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
245 }
246 ++mCount;
247 }
248 pthread_mutex_unlock(&mLock);
249 }
250
251 // call when you release a partial wakelock.
252 void release(const sp<IBinder> &wakeLockToken) {
253 if (wakeLockToken.get() == nullptr) {
254 return;
255 }
256 pthread_mutex_lock(&mLock);
257 if (--mCount < 0) {
258 ALOGE("negative wakelock count");
259 mCount = 0;
260 }
261 pthread_mutex_unlock(&mLock);
262 }
263
264 // retrieves the boottime timebase offset from monotonic.
265 int64_t getBoottimeOffset() {
266 pthread_mutex_lock(&mLock);
267 int64_t boottimeOffset = mBoottimeOffset;
268 pthread_mutex_unlock(&mLock);
269 return boottimeOffset;
270 }
271
272 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
273 // and the selected timebase.
274 // Currently only TIMEBASE_BOOTTIME is allowed.
275 //
276 // This only needs to be called upon acquiring the first partial wakelock
277 // after all other partial wakelocks are released.
278 //
279 // We do an empirical measurement of the offset rather than parsing
280 // /proc/timer_list since the latter is not a formal kernel ABI.
281 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
282 int clockbase;
283 switch (timebase) {
284 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
285 clockbase = SYSTEM_TIME_BOOTTIME;
286 break;
287 default:
288 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
289 break;
290 }
291 // try three times to get the clock offset, choose the one
292 // with the minimum gap in measurements.
293 const int tries = 3;
294 nsecs_t bestGap, measured;
295 for (int i = 0; i < tries; ++i) {
296 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t tbase = systemTime(clockbase);
298 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
299 const nsecs_t gap = tmono2 - tmono;
300 if (i == 0 || gap < bestGap) {
301 bestGap = gap;
302 measured = tbase - ((tmono + tmono2) >> 1);
303 }
304 }
305
306 // to avoid micro-adjusting, we don't change the timebase
307 // unless it is significantly different.
308 //
309 // Assumption: It probably takes more than toleranceNs to
310 // suspend and resume the device.
311 static int64_t toleranceNs = 10000; // 10 us
312 if (llabs(*offset - measured) > toleranceNs) {
313 ALOGV("Adjusting timebase offset old: %lld new: %lld",
314 (long long)*offset, (long long)measured);
315 *offset = measured;
316 }
317 }
318
319 pthread_mutex_t mLock;
320 int32_t mCount;
321 int64_t mBoottimeOffset;
322} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800323
324// ----------------------------------------------------------------------------
325// CPU Stats
326// ----------------------------------------------------------------------------
327
328class CpuStats {
329public:
330 CpuStats();
331 void sample(const String8 &title);
332#ifdef DEBUG_CPU_USAGE
333private:
334 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
335 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
336
337 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
338
339 int mCpuNum; // thread's current CPU number
340 int mCpukHz; // frequency of thread's current CPU in kHz
341#endif
342};
343
344CpuStats::CpuStats()
345#ifdef DEBUG_CPU_USAGE
346 : mCpuNum(-1), mCpukHz(-1)
347#endif
348{
349}
350
Glenn Kasten0f11b512014-01-31 16:18:54 -0800351void CpuStats::sample(const String8 &title
352#ifndef DEBUG_CPU_USAGE
353 __unused
354#endif
355 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800356#ifdef DEBUG_CPU_USAGE
357 // get current thread's delta CPU time in wall clock ns
358 double wcNs;
359 bool valid = mCpuUsage.sampleAndEnable(wcNs);
360
361 // record sample for wall clock statistics
362 if (valid) {
363 mWcStats.sample(wcNs);
364 }
365
366 // get the current CPU number
367 int cpuNum = sched_getcpu();
368
369 // get the current CPU frequency in kHz
370 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
371
372 // check if either CPU number or frequency changed
373 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
374 mCpuNum = cpuNum;
375 mCpukHz = cpukHz;
376 // ignore sample for purposes of cycles
377 valid = false;
378 }
379
380 // if no change in CPU number or frequency, then record sample for cycle statistics
381 if (valid && mCpukHz > 0) {
382 double cycles = wcNs * cpukHz * 0.000001;
383 mHzStats.sample(cycles);
384 }
385
386 unsigned n = mWcStats.n();
387 // mCpuUsage.elapsed() is expensive, so don't call it every loop
388 if ((n & 127) == 1) {
389 long long elapsed = mCpuUsage.elapsed();
390 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
391 double perLoop = elapsed / (double) n;
392 double perLoop100 = perLoop * 0.01;
393 double perLoop1k = perLoop * 0.001;
394 double mean = mWcStats.mean();
395 double stddev = mWcStats.stddev();
396 double minimum = mWcStats.minimum();
397 double maximum = mWcStats.maximum();
398 double meanCycles = mHzStats.mean();
399 double stddevCycles = mHzStats.stddev();
400 double minCycles = mHzStats.minimum();
401 double maxCycles = mHzStats.maximum();
402 mCpuUsage.resetElapsed();
403 mWcStats.reset();
404 mHzStats.reset();
405 ALOGD("CPU usage for %s over past %.1f secs\n"
406 " (%u mixer loops at %.1f mean ms per loop):\n"
407 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
408 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
409 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
410 title.string(),
411 elapsed * .000000001, n, perLoop * .000001,
412 mean * .001,
413 stddev * .001,
414 minimum * .001,
415 maximum * .001,
416 mean / perLoop100,
417 stddev / perLoop100,
418 minimum / perLoop100,
419 maximum / perLoop100,
420 meanCycles / perLoop1k,
421 stddevCycles / perLoop1k,
422 minCycles / perLoop1k,
423 maxCycles / perLoop1k);
424
425 }
426 }
427#endif
428};
429
430// ----------------------------------------------------------------------------
431// ThreadBase
432// ----------------------------------------------------------------------------
433
Glenn Kasten97b7b752014-09-28 13:04:24 -0700434// static
435const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
436{
437 switch (type) {
438 case MIXER:
439 return "MIXER";
440 case DIRECT:
441 return "DIRECT";
442 case DUPLICATING:
443 return "DUPLICATING";
444 case RECORD:
445 return "RECORD";
446 case OFFLOAD:
447 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800448 case MMAP:
449 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700450 default:
451 return "unknown";
452 }
453}
454
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700461 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800462 }
463 return result;
464}
465
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800467{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700468 std::string result;
469 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800470 return result;
471}
472
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700474{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700475 std::string result;
476 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700477 return result;
478}
479
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800480const char *sourceToString(audio_source_t source)
481{
482 switch (source) {
483 case AUDIO_SOURCE_DEFAULT: return "default";
484 case AUDIO_SOURCE_MIC: return "mic";
485 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
486 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
487 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
488 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
489 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
490 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
491 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800492 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800493 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
494 case AUDIO_SOURCE_HOTWORD: return "hotword";
495 default: return "unknown";
496 }
497}
498
Eric Laurent81784c32012-11-19 14:55:58 -0800499AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700500 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800501 : Thread(false /*canCallJava*/),
502 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700503 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700504 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800505 // are set by PlaybackThread::readOutputParameters_l() or
506 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700507 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800508 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700509 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
510 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800511 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700512 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800513 mSystemReady(systemReady),
514 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800515{
Eric Laurent296fb132015-05-01 11:38:42 -0700516 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800517}
518
519AudioFlinger::ThreadBase::~ThreadBase()
520{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700521 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700522 mConfigEvents.clear();
523
Eric Laurent81784c32012-11-19 14:55:58 -0800524 // do not lock the mutex in destructor
525 releaseWakeLock_l();
526 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800527 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800528 binder->unlinkToDeath(mDeathRecipient);
529 }
530}
531
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700532status_t AudioFlinger::ThreadBase::readyToRun()
533{
534 status_t status = initCheck();
535 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800536 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700537 } else {
538 ALOGE("No working audio driver found.");
539 }
540 return status;
541}
542
Eric Laurent81784c32012-11-19 14:55:58 -0800543void AudioFlinger::ThreadBase::exit()
544{
545 ALOGV("ThreadBase::exit");
546 // do any cleanup required for exit to succeed
547 preExit();
548 {
549 // This lock prevents the following race in thread (uniprocessor for illustration):
550 // if (!exitPending()) {
551 // // context switch from here to exit()
552 // // exit() calls requestExit(), what exitPending() observes
553 // // exit() calls signal(), which is dropped since no waiters
554 // // context switch back from exit() to here
555 // mWaitWorkCV.wait(...);
556 // // now thread is hung
557 // }
558 AutoMutex lock(mLock);
559 requestExit();
560 mWaitWorkCV.broadcast();
561 }
562 // When Thread::requestExitAndWait is made virtual and this method is renamed to
563 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
564 requestExitAndWait();
565}
566
567status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
568{
Eric Laurent81784c32012-11-19 14:55:58 -0800569 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
570 Mutex::Autolock _l(mLock);
571
Eric Laurent10351942014-05-08 18:49:52 -0700572 return sendSetParameterConfigEvent_l(keyValuePairs);
573}
574
575// sendConfigEvent_l() must be called with ThreadBase::mLock held
576// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
577status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
578{
579 status_t status = NO_ERROR;
580
Eric Laurent72e3f392015-05-20 14:43:50 -0700581 if (event->mRequiresSystemReady && !mSystemReady) {
582 event->mWaitStatus = false;
583 mPendingConfigEvents.add(event);
584 return status;
585 }
Eric Laurent10351942014-05-08 18:49:52 -0700586 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700587 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800588 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700589 mLock.unlock();
590 {
591 Mutex::Autolock _l(event->mLock);
592 while (event->mWaitStatus) {
593 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
594 event->mStatus = TIMED_OUT;
595 event->mWaitStatus = false;
596 }
597 }
598 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800599 }
Eric Laurent10351942014-05-08 18:49:52 -0700600 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800601 return status;
602}
603
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700604void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800605{
606 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700607 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800608}
609
610// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800612{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700613 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700614 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800615}
616
Mikhail Naganov83f04272017-02-07 10:45:09 -0800617void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700618{
619 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800620 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700621}
622
Eric Laurent81784c32012-11-19 14:55:58 -0800623// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800624void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
625 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800626{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800627 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700628 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800629}
630
Eric Laurent10351942014-05-08 18:49:52 -0700631// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
632status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800633{
Andy Hung2ddee192015-12-18 17:34:44 -0800634 sp<ConfigEvent> configEvent;
635 AudioParameter param(keyValuePair);
636 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700637 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800638 setMasterMono_l(value != 0);
639 if (param.size() == 1) {
640 return NO_ERROR; // should be a solo parameter - we don't pass down
641 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700642 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800643 configEvent = new SetParameterConfigEvent(param.toString());
644 } else {
645 configEvent = new SetParameterConfigEvent(keyValuePair);
646 }
Eric Laurent10351942014-05-08 18:49:52 -0700647 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700648}
649
Eric Laurent1c333e22014-05-20 10:48:17 -0700650status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
651 const struct audio_patch *patch,
652 audio_patch_handle_t *handle)
653{
654 Mutex::Autolock _l(mLock);
655 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
656 status_t status = sendConfigEvent_l(configEvent);
657 if (status == NO_ERROR) {
658 CreateAudioPatchConfigEventData *data =
659 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
660 *handle = data->mHandle;
661 }
662 return status;
663}
664
665status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
666 const audio_patch_handle_t handle)
667{
668 Mutex::Autolock _l(mLock);
669 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
670 return sendConfigEvent_l(configEvent);
671}
672
673
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700674// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700675void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700676{
Eric Laurent10351942014-05-08 18:49:52 -0700677 bool configChanged = false;
678
Eric Laurent81784c32012-11-19 14:55:58 -0800679 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700680 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700681 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800682 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700683 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700684 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700685 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
686 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800687 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700688 true /*asynchronous*/);
689 if (err != 0) {
690 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700691 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700692 }
693 } break;
694 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700695 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700696 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700697 } break;
698 case CFG_EVENT_SET_PARAMETER: {
699 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
700 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
701 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700702 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
703 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700704 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700705 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700706 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700707 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700708 CreateAudioPatchConfigEventData *data =
709 (CreateAudioPatchConfigEventData *)event->mData.get();
710 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700711 const audio_devices_t newDevice = getDevice();
712 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
713 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
714 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700715 } break;
716 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700717 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700718 ReleaseAudioPatchConfigEventData *data =
719 (ReleaseAudioPatchConfigEventData *)event->mData.get();
720 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700721 const audio_devices_t newDevice = getDevice();
722 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
723 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
724 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700725 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700726 default:
Eric Laurent10351942014-05-08 18:49:52 -0700727 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700728 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800729 }
Eric Laurent10351942014-05-08 18:49:52 -0700730 {
731 Mutex::Autolock _l(event->mLock);
732 if (event->mWaitStatus) {
733 event->mWaitStatus = false;
734 event->mCond.signal();
735 }
736 }
737 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
738 }
739
740 if (configChanged) {
741 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800742 }
Eric Laurent81784c32012-11-19 14:55:58 -0800743}
744
Marco Nelissenb2208842014-02-07 14:00:50 -0800745String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
746 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700747 const audio_channel_representation_t representation =
748 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700749
750 switch (representation) {
751 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
752 if (output) {
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
756 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
757 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
758 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
759 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
761 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
763 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
770 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
771 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
772 } else {
773 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
774 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
775 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
776 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
777 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
781 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
782 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
783 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
784 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
785 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
786 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
787 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
788 }
789 const int len = s.length();
790 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700791 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700792 s.unlockBuffer(len - 2); // remove trailing ", "
793 }
794 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800795 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700796 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
797 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
798 return s;
799 default:
800 s.appendFormat("unknown mask, representation:%d bits:%#x",
801 representation, audio_channel_mask_get_bits(mask));
802 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800803 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800804}
805
Glenn Kasten0f11b512014-01-31 16:18:54 -0800806void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800807{
808 const size_t SIZE = 256;
809 char buffer[SIZE];
810 String8 result;
811
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800812 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
813 this, mThreadName, getTid(), type(), threadTypeToString(type()));
814
Eric Laurent81784c32012-11-19 14:55:58 -0800815 bool locked = AudioFlinger::dumpTryLock(mLock);
816 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800817 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800818 }
819
Elliott Hughes87cebad2014-05-22 10:14:43 -0700820 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700822 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700824 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700825 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700826 dprintf(fd, " Channel count: %u\n", mChannelCount);
827 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800828 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700829 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700830 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700831 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800832 size_t numConfig = mConfigEvents.size();
833 if (numConfig) {
834 for (size_t i = 0; i < numConfig; i++) {
835 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800839 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700840 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800841 }
Andy Hung293558a2017-03-21 12:19:20 -0700842 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700843 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
844 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800845 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800846
847 if (locked) {
848 mLock.unlock();
849 }
850}
851
852void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
853{
854 const size_t SIZE = 256;
855 char buffer[SIZE];
856 String8 result;
857
Marco Nelissenb2208842014-02-07 14:00:50 -0800858 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000859 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800860 write(fd, buffer, strlen(buffer));
861
Marco Nelissenb2208842014-02-07 14:00:50 -0800862 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800863 sp<EffectChain> chain = mEffectChains[i];
864 if (chain != 0) {
865 chain->dump(fd, args);
866 }
867 }
868}
869
Andy Hungdae27702016-10-31 14:01:16 -0700870void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800871{
872 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700873 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800874}
875
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100876String16 AudioFlinger::ThreadBase::getWakeLockTag()
877{
878 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800879 case MIXER:
880 return String16("AudioMix");
881 case DIRECT:
882 return String16("AudioDirectOut");
883 case DUPLICATING:
884 return String16("AudioDup");
885 case RECORD:
886 return String16("AudioIn");
887 case OFFLOAD:
888 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800889 case MMAP:
890 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800891 default:
892 ALOG_ASSERT(false);
893 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100894 }
895}
896
Andy Hungdae27702016-10-31 14:01:16 -0700897void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800898{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800899 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800900 if (mPowerManager != 0) {
901 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700902 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
903 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700904 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100905 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700906 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700907 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800908 if (status == NO_ERROR) {
909 mWakeLockToken = binder;
910 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800911 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800912 }
Wei Jia3f273d12015-11-24 09:06:49 -0800913
Andy Hung3f0c9022016-01-15 17:49:46 -0800914 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800915 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
916 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800917}
918
919void AudioFlinger::ThreadBase::releaseWakeLock()
920{
921 Mutex::Autolock _l(mLock);
922 releaseWakeLock_l();
923}
924
925void AudioFlinger::ThreadBase::releaseWakeLock_l()
926{
Andy Hung3f0c9022016-01-15 17:49:46 -0800927 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800929 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800930 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700931 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
932 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800933 }
934 mWakeLockToken.clear();
935 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800936}
937
938void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700939 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800940 // use checkService() to avoid blocking if power service is not up yet
941 sp<IBinder> binder =
942 defaultServiceManager()->checkService(String16("power"));
943 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800944 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800945 } else {
946 mPowerManager = interface_cast<IPowerManager>(binder);
947 binder->linkToDeath(mDeathRecipient);
948 }
949 }
950}
951
Andy Hungd01b0f12016-11-07 16:10:30 -0800952void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800953 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700954
955#if !LOG_NDEBUG
956 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800957 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700958 s << uid << " ";
959 }
960 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
961#endif
962
Andy Hung438e7572015-12-14 15:51:17 -0800963 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
964 if (mSystemReady) {
965 ALOGE("no wake lock to update, but system ready!");
966 } else {
967 ALOGW("no wake lock to update, system not ready yet");
968 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800969 return;
970 }
971 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800972 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
973 status_t status = mPowerManager->updateWakeLockUids(
974 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
975 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800976 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800977 }
978}
979
Eric Laurent81784c32012-11-19 14:55:58 -0800980void AudioFlinger::ThreadBase::clearPowerManager()
981{
982 Mutex::Autolock _l(mLock);
983 releaseWakeLock_l();
984 mPowerManager.clear();
985}
986
Glenn Kasten0f11b512014-01-31 16:18:54 -0800987void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800988{
989 sp<ThreadBase> thread = mThread.promote();
990 if (thread != 0) {
991 thread->clearPowerManager();
992 }
993 ALOGW("power manager service died !!!");
994}
995
Eric Laurent81784c32012-11-19 14:55:58 -0800996void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800997 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800998{
999 sp<EffectChain> chain = getEffectChain_l(sessionId);
1000 if (chain != 0) {
1001 if (type != NULL) {
1002 chain->setEffectSuspended_l(type, suspend);
1003 } else {
1004 chain->setEffectSuspendedAll_l(suspend);
1005 }
1006 }
1007
1008 updateSuspendedSessions_l(type, suspend, sessionId);
1009}
1010
1011void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1012{
1013 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1014 if (index < 0) {
1015 return;
1016 }
1017
1018 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1019 mSuspendedSessions.valueAt(index);
1020
1021 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001022 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001023 for (int j = 0; j < desc->mRefCount; j++) {
1024 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1025 chain->setEffectSuspendedAll_l(true);
1026 } else {
1027 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1028 desc->mType.timeLow);
1029 chain->setEffectSuspended_l(&desc->mType, true);
1030 }
1031 }
1032 }
1033}
1034
1035void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1036 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001037 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001038{
1039 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1040
1041 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1042
1043 if (suspend) {
1044 if (index >= 0) {
1045 sessionEffects = mSuspendedSessions.valueAt(index);
1046 } else {
1047 mSuspendedSessions.add(sessionId, sessionEffects);
1048 }
1049 } else {
1050 if (index < 0) {
1051 return;
1052 }
1053 sessionEffects = mSuspendedSessions.valueAt(index);
1054 }
1055
1056
1057 int key = EffectChain::kKeyForSuspendAll;
1058 if (type != NULL) {
1059 key = type->timeLow;
1060 }
1061 index = sessionEffects.indexOfKey(key);
1062
1063 sp<SuspendedSessionDesc> desc;
1064 if (suspend) {
1065 if (index >= 0) {
1066 desc = sessionEffects.valueAt(index);
1067 } else {
1068 desc = new SuspendedSessionDesc();
1069 if (type != NULL) {
1070 desc->mType = *type;
1071 }
1072 sessionEffects.add(key, desc);
1073 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1074 }
1075 desc->mRefCount++;
1076 } else {
1077 if (index < 0) {
1078 return;
1079 }
1080 desc = sessionEffects.valueAt(index);
1081 if (--desc->mRefCount == 0) {
1082 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1083 sessionEffects.removeItemsAt(index);
1084 if (sessionEffects.isEmpty()) {
1085 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1086 sessionId);
1087 mSuspendedSessions.removeItem(sessionId);
1088 }
1089 }
1090 }
1091 if (!sessionEffects.isEmpty()) {
1092 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1093 }
1094}
1095
1096void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1097 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001098 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001099{
1100 Mutex::Autolock _l(mLock);
1101 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1102}
1103
1104void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1105 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001106 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001107{
1108 if (mType != RECORD) {
1109 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1110 // another session. This gives the priority to well behaved effect control panels
1111 // and applications not using global effects.
1112 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1113 // global effects
1114 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1115 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1116 }
1117 }
1118
1119 sp<EffectChain> chain = getEffectChain_l(sessionId);
1120 if (chain != 0) {
1121 chain->checkSuspendOnEffectEnabled(effect, enabled);
1122 }
1123}
1124
Eric Laurent4c415062016-06-17 16:14:16 -07001125// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1126status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1127 const effect_descriptor_t *desc, audio_session_t sessionId)
1128{
1129 // No global effect sessions on record threads
1130 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1131 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1132 desc->name, mThreadName);
1133 return BAD_VALUE;
1134 }
1135 // only pre processing effects on record thread
1136 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1137 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1138 desc->name, mThreadName);
1139 return BAD_VALUE;
1140 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001141
1142 // always allow effects without processing load or latency
1143 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1144 return NO_ERROR;
1145 }
1146
Eric Laurent4c415062016-06-17 16:14:16 -07001147 audio_input_flags_t flags = mInput->flags;
1148 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1149 if (flags & AUDIO_INPUT_FLAG_RAW) {
1150 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1151 desc->name, mThreadName);
1152 return BAD_VALUE;
1153 }
1154 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1155 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1156 desc->name, mThreadName);
1157 return BAD_VALUE;
1158 }
1159 }
1160 return NO_ERROR;
1161}
1162
1163// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1164status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1165 const effect_descriptor_t *desc, audio_session_t sessionId)
1166{
1167 // no preprocessing on playback threads
1168 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1169 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1170 " thread %s", desc->name, mThreadName);
1171 return BAD_VALUE;
1172 }
1173
Eric Laurent3e4de772017-07-16 16:55:08 -07001174 // always allow effects without processing load or latency
1175 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1176 return NO_ERROR;
1177 }
1178
Eric Laurent4c415062016-06-17 16:14:16 -07001179 switch (mType) {
1180 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001181#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001182 // Reject any effect on mixer multichannel sinks.
1183 // TODO: fix both format and multichannel issues with effects.
1184 if (mChannelCount != FCC_2) {
1185 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1186 " thread %s", desc->name, mChannelCount, mThreadName);
1187 return BAD_VALUE;
1188 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001189#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001190 audio_output_flags_t flags = mOutput->flags;
1191 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1192 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1193 // global effects are applied only to non fast tracks if they are SW
1194 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1195 break;
1196 }
1197 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1198 // only post processing on output stage session
1199 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1200 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1201 " on output stage session", desc->name);
1202 return BAD_VALUE;
1203 }
1204 } else {
1205 // no restriction on effects applied on non fast tracks
1206 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1207 break;
1208 }
1209 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001210
Eric Laurent4c415062016-06-17 16:14:16 -07001211 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1212 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1213 desc->name);
1214 return BAD_VALUE;
1215 }
1216 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1217 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1218 " in fast mode", desc->name);
1219 return BAD_VALUE;
1220 }
1221 }
1222 } break;
1223 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001224 // nothing actionable on offload threads, if the effect:
1225 // - is offloadable: the effect can be created
1226 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1227 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001228 break;
1229 case DIRECT:
1230 // Reject any effect on Direct output threads for now, since the format of
1231 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1232 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1233 desc->name, mThreadName);
1234 return BAD_VALUE;
1235 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001236#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001237 // Reject any effect on mixer multichannel sinks.
1238 // TODO: fix both format and multichannel issues with effects.
1239 if (mChannelCount != FCC_2) {
1240 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1241 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1242 return BAD_VALUE;
1243 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001244#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001245 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1246 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1247 " thread %s", desc->name, mThreadName);
1248 return BAD_VALUE;
1249 }
1250 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1251 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1252 " DUPLICATING thread %s", desc->name, mThreadName);
1253 return BAD_VALUE;
1254 }
1255 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1256 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1257 " DUPLICATING thread %s", desc->name, mThreadName);
1258 return BAD_VALUE;
1259 }
1260 break;
1261 default:
1262 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1263 }
1264
1265 return NO_ERROR;
1266}
1267
Eric Laurent81784c32012-11-19 14:55:58 -08001268// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1269sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1270 const sp<AudioFlinger::Client>& client,
1271 const sp<IEffectClient>& effectClient,
1272 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001273 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001274 effect_descriptor_t *desc,
1275 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001276 status_t *status,
1277 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001278{
1279 sp<EffectModule> effect;
1280 sp<EffectHandle> handle;
1281 status_t lStatus;
1282 sp<EffectChain> chain;
1283 bool chainCreated = false;
1284 bool effectCreated = false;
1285 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001286 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001287
1288 lStatus = initCheck();
1289 if (lStatus != NO_ERROR) {
1290 ALOGW("createEffect_l() Audio driver not initialized.");
1291 goto Exit;
1292 }
1293
Eric Laurent81784c32012-11-19 14:55:58 -08001294 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1295
1296 { // scope for mLock
1297 Mutex::Autolock _l(mLock);
1298
Eric Laurent4c415062016-06-17 16:14:16 -07001299 lStatus = checkEffectCompatibility_l(desc, sessionId);
1300 if (lStatus != NO_ERROR) {
1301 goto Exit;
1302 }
1303
Eric Laurent81784c32012-11-19 14:55:58 -08001304 // check for existing effect chain with the requested audio session
1305 chain = getEffectChain_l(sessionId);
1306 if (chain == 0) {
1307 // create a new chain for this session
1308 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1309 chain = new EffectChain(this, sessionId);
1310 addEffectChain_l(chain);
1311 chain->setStrategy(getStrategyForSession_l(sessionId));
1312 chainCreated = true;
1313 } else {
1314 effect = chain->getEffectFromDesc_l(desc);
1315 }
1316
1317 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1318
1319 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001320 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001321 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001322 lStatus = AudioSystem::registerEffect(
1323 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (lStatus != NO_ERROR) {
1325 goto Exit;
1326 }
1327 effectRegistered = true;
1328 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001329 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001330 if (lStatus != NO_ERROR) {
1331 goto Exit;
1332 }
1333 effectCreated = true;
1334
1335 effect->setDevice(mOutDevice);
1336 effect->setDevice(mInDevice);
1337 effect->setMode(mAudioFlinger->getMode());
1338 effect->setAudioSource(mAudioSource);
1339 }
1340 // create effect handle and connect it to effect module
1341 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001342 lStatus = handle->initCheck();
1343 if (lStatus == OK) {
1344 lStatus = effect->addHandle(handle.get());
1345 }
Eric Laurent81784c32012-11-19 14:55:58 -08001346 if (enabled != NULL) {
1347 *enabled = (int)effect->isEnabled();
1348 }
1349 }
1350
1351Exit:
1352 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1353 Mutex::Autolock _l(mLock);
1354 if (effectCreated) {
1355 chain->removeEffect_l(effect);
1356 }
1357 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001358 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001359 }
1360 if (chainCreated) {
1361 removeEffectChain_l(chain);
1362 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001363 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001364 }
1365
Glenn Kasten9156ef32013-08-06 15:39:08 -07001366 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001367 return handle;
1368}
1369
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001370void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1371 bool unpinIfLast)
1372{
1373 bool remove = false;
1374 sp<EffectModule> effect;
1375 {
1376 Mutex::Autolock _l(mLock);
1377
1378 effect = handle->effect().promote();
1379 if (effect == 0) {
1380 return;
1381 }
1382 // restore suspended effects if the disconnected handle was enabled and the last one.
1383 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1384 if (remove) {
1385 removeEffect_l(effect, true);
1386 }
1387 }
1388 if (remove) {
1389 mAudioFlinger->updateOrphanEffectChains(effect);
1390 AudioSystem::unregisterEffect(effect->id());
1391 if (handle->enabled()) {
1392 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1393 }
1394 }
1395}
1396
Glenn Kastend848eb42016-03-08 13:42:11 -08001397sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1398 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001399{
1400 Mutex::Autolock _l(mLock);
1401 return getEffect_l(sessionId, effectId);
1402}
1403
Glenn Kastend848eb42016-03-08 13:42:11 -08001404sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1405 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001406{
1407 sp<EffectChain> chain = getEffectChain_l(sessionId);
1408 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1409}
1410
1411// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1412// PlaybackThread::mLock held
1413status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1414{
1415 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001416 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001417 sp<EffectChain> chain = getEffectChain_l(sessionId);
1418 bool chainCreated = false;
1419
Eric Laurent5baf2af2013-09-12 17:37:00 -07001420 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001421 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001422 this, effect->desc().name, effect->desc().flags);
1423
Eric Laurent81784c32012-11-19 14:55:58 -08001424 if (chain == 0) {
1425 // create a new chain for this session
1426 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1427 chain = new EffectChain(this, sessionId);
1428 addEffectChain_l(chain);
1429 chain->setStrategy(getStrategyForSession_l(sessionId));
1430 chainCreated = true;
1431 }
1432 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1433
1434 if (chain->getEffectFromId_l(effect->id()) != 0) {
1435 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1436 this, effect->desc().name, chain.get());
1437 return BAD_VALUE;
1438 }
1439
Eric Laurent5baf2af2013-09-12 17:37:00 -07001440 effect->setOffloaded(mType == OFFLOAD, mId);
1441
Eric Laurent81784c32012-11-19 14:55:58 -08001442 status_t status = chain->addEffect_l(effect);
1443 if (status != NO_ERROR) {
1444 if (chainCreated) {
1445 removeEffectChain_l(chain);
1446 }
1447 return status;
1448 }
1449
1450 effect->setDevice(mOutDevice);
1451 effect->setDevice(mInDevice);
1452 effect->setMode(mAudioFlinger->getMode());
1453 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001454
Eric Laurent81784c32012-11-19 14:55:58 -08001455 return NO_ERROR;
1456}
1457
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001458void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001459
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001460 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001461 effect_descriptor_t desc = effect->desc();
1462 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1463 detachAuxEffect_l(effect->id());
1464 }
1465
1466 sp<EffectChain> chain = effect->chain().promote();
1467 if (chain != 0) {
1468 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001469 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001470 removeEffectChain_l(chain);
1471 }
1472 } else {
1473 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1474 }
1475}
1476
1477void AudioFlinger::ThreadBase::lockEffectChains_l(
1478 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1479{
1480 effectChains = mEffectChains;
1481 for (size_t i = 0; i < mEffectChains.size(); i++) {
1482 mEffectChains[i]->lock();
1483 }
1484}
1485
1486void AudioFlinger::ThreadBase::unlockEffectChains(
1487 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1488{
1489 for (size_t i = 0; i < effectChains.size(); i++) {
1490 effectChains[i]->unlock();
1491 }
1492}
1493
Glenn Kastend848eb42016-03-08 13:42:11 -08001494sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001495{
1496 Mutex::Autolock _l(mLock);
1497 return getEffectChain_l(sessionId);
1498}
1499
Glenn Kastend848eb42016-03-08 13:42:11 -08001500sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1501 const
Eric Laurent81784c32012-11-19 14:55:58 -08001502{
1503 size_t size = mEffectChains.size();
1504 for (size_t i = 0; i < size; i++) {
1505 if (mEffectChains[i]->sessionId() == sessionId) {
1506 return mEffectChains[i];
1507 }
1508 }
1509 return 0;
1510}
1511
1512void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1513{
1514 Mutex::Autolock _l(mLock);
1515 size_t size = mEffectChains.size();
1516 for (size_t i = 0; i < size; i++) {
1517 mEffectChains[i]->setMode_l(mode);
1518 }
1519}
1520
Eric Laurent83b88082014-06-20 18:31:16 -07001521void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1522{
1523 config->type = AUDIO_PORT_TYPE_MIX;
1524 config->ext.mix.handle = mId;
1525 config->sample_rate = mSampleRate;
1526 config->format = mFormat;
1527 config->channel_mask = mChannelMask;
1528 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1529 AUDIO_PORT_CONFIG_FORMAT;
1530}
1531
Eric Laurent72e3f392015-05-20 14:43:50 -07001532void AudioFlinger::ThreadBase::systemReady()
1533{
1534 Mutex::Autolock _l(mLock);
1535 if (mSystemReady) {
1536 return;
1537 }
1538 mSystemReady = true;
1539
1540 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1541 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1542 }
1543 mPendingConfigEvents.clear();
1544}
1545
Andy Hungdae27702016-10-31 14:01:16 -07001546template <typename T>
1547ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1548 ssize_t index = mActiveTracks.indexOf(track);
1549 if (index >= 0) {
1550 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1551 return index;
1552 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001553 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001554 mActiveTracksGeneration++;
1555 mLatestActiveTrack = track;
1556 ++mBatteryCounter[track->uid()].second;
1557 return mActiveTracks.add(track);
1558}
1559
1560template <typename T>
1561ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1562 ssize_t index = mActiveTracks.remove(track);
1563 if (index < 0) {
1564 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1565 return index;
1566 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001567 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001568 mActiveTracksGeneration++;
1569 --mBatteryCounter[track->uid()].second;
1570 // mLatestActiveTrack is not cleared even if is the same as track.
1571 return index;
1572}
1573
1574template <typename T>
1575void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1576 for (const sp<T> &track : mActiveTracks) {
1577 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001578 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001579 }
1580 mLastActiveTracksGeneration = mActiveTracksGeneration;
1581 mActiveTracks.clear();
1582 mLatestActiveTrack.clear();
1583 mBatteryCounter.clear();
1584}
1585
1586template <typename T>
1587void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1588 sp<ThreadBase> thread, bool force) {
1589 // Updates ActiveTracks client uids to the thread wakelock.
1590 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1591 thread->updateWakeLockUids_l(getWakeLockUids());
1592 mLastActiveTracksGeneration = mActiveTracksGeneration;
1593 }
1594
1595 // Updates BatteryNotifier uids
1596 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1597 const uid_t uid = it->first;
1598 ssize_t &previous = it->second.first;
1599 ssize_t &current = it->second.second;
1600 if (current > 0) {
1601 if (previous == 0) {
1602 BatteryNotifier::getInstance().noteStartAudio(uid);
1603 }
1604 previous = current;
1605 ++it;
1606 } else if (current == 0) {
1607 if (previous > 0) {
1608 BatteryNotifier::getInstance().noteStopAudio(uid);
1609 }
1610 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1611 } else /* (current < 0) */ {
1612 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1613 }
1614 }
1615}
Eric Laurent83b88082014-06-20 18:31:16 -07001616
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001617template <typename T>
1618void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1619 const char *funcName, const sp<T> &track) const {
1620 if (mLocalLog != nullptr) {
1621 String8 result;
1622 track->appendDump(result, false /* active */);
1623 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1624 }
1625}
1626
Eric Laurent6acd1d42017-01-04 14:23:29 -08001627void AudioFlinger::ThreadBase::broadcast_l()
1628{
1629 // Thread could be blocked waiting for async
1630 // so signal it to handle state changes immediately
1631 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1632 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1633 mSignalPending = true;
1634 mWaitWorkCV.broadcast();
1635}
1636
Eric Laurent81784c32012-11-19 14:55:58 -08001637// ----------------------------------------------------------------------------
1638// Playback
1639// ----------------------------------------------------------------------------
1640
1641AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1642 AudioStreamOut* output,
1643 audio_io_handle_t id,
1644 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001645 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001646 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001647 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001648 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001649 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001650 mMixerBuffer(NULL),
1651 mMixerBufferSize(0),
1652 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1653 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001654 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001655 mEffectBuffer(NULL),
1656 mEffectBufferSize(0),
1657 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1658 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001659 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001660 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001661 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001662 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001663 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001664 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001665 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001666 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001667 mMixerStatus(MIXER_IDLE),
1668 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001669 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001670 mBytesRemaining(0),
1671 mCurrentWriteLength(0),
1672 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001673 mWriteAckSequence(0),
1674 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001675 mScreenState(AudioFlinger::mScreenState),
1676 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001677 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001678 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1679 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001680{
Glenn Kastend7dca052015-03-05 16:05:54 -08001681 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1682 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001683
1684 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1685 // it would be safer to explicitly pass initial masterVolume/masterMute as
1686 // parameter.
1687 //
1688 // If the HAL we are using has support for master volume or master mute,
1689 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1690 // and the mute set to false).
1691 mMasterVolume = audioFlinger->masterVolume_l();
1692 mMasterMute = audioFlinger->masterMute_l();
1693 if (mOutput && mOutput->audioHwDev) {
1694 if (mOutput->audioHwDev->canSetMasterVolume()) {
1695 mMasterVolume = 1.0;
1696 }
1697
1698 if (mOutput->audioHwDev->canSetMasterMute()) {
1699 mMasterMute = false;
1700 }
1701 }
1702
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001703 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001704
Eric Laurent223fd5c2014-11-11 13:43:36 -08001705 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001706 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001707 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001708 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001709 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1710 }
Eric Laurent98e38192018-02-15 18:31:53 -08001711 // Audio patch volume is always max
1712 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1713 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001714}
1715
1716AudioFlinger::PlaybackThread::~PlaybackThread()
1717{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001718 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001719 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001720 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001721 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001722}
1723
1724void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1725{
1726 dumpInternals(fd, args);
1727 dumpTracks(fd, args);
1728 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001729 dprintf(fd, " Local log:\n");
1730 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001731}
1732
Glenn Kasten0f11b512014-01-31 16:18:54 -08001733void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001734{
Eric Laurent81784c32012-11-19 14:55:58 -08001735 String8 result;
1736
Marco Nelissenb2208842014-02-07 14:00:50 -08001737 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001738 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1739 const stream_type_t *st = &mStreamTypes[i];
1740 if (i > 0) {
1741 result.appendFormat(", ");
1742 }
1743 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1744 if (st->mute) {
1745 result.append("M");
1746 }
1747 }
1748 result.append("\n");
1749 write(fd, result.string(), result.length());
1750 result.clear();
1751
Eric Laurent81784c32012-11-19 14:55:58 -08001752 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1753 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001754 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001755 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001756
1757 size_t numtracks = mTracks.size();
1758 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001759 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001760 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001761 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001762 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001763 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001764 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001765 Track::appendDumpHeader(result);
1766 for (size_t i = 0; i < numtracks; ++i) {
1767 sp<Track> track = mTracks[i];
1768 if (track != 0) {
1769 bool active = mActiveTracks.indexOf(track) >= 0;
1770 if (active) {
1771 numactiveseen++;
1772 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001773 result.append(prefix);
1774 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001775 }
1776 }
1777 } else {
1778 result.append("\n");
1779 }
1780 if (numactiveseen != numactive) {
1781 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001782 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001783 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001784 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001785 Track::appendDumpHeader(result);
1786 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001787 sp<Track> track = mActiveTracks[i];
1788 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001789 result.append(prefix);
1790 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001791 }
1792 }
1793 }
1794
1795 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001796}
1797
1798void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1799{
Glenn Kasten44182c22015-03-05 17:12:23 -08001800 dumpBase(fd, args);
1801
Elliott Hughes87cebad2014-05-22 10:14:43 -07001802 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001803 dprintf(fd, " Last write occurred (msecs): %llu\n",
1804 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001805 dprintf(fd, " Total writes: %d\n", mNumWrites);
1806 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1807 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1808 dprintf(fd, " Suspend count: %d\n", mSuspended);
1809 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1810 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1811 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1812 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001813 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001814 AudioStreamOut *output = mOutput;
1815 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001816 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1817 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001818 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1819 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1820 if (mPipeSink.get() != nullptr) {
1821 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1822 }
1823 if (output != nullptr) {
1824 dprintf(fd, " Hal stream dump:\n");
1825 (void)output->stream->dump(fd);
1826 }
Eric Laurent81784c32012-11-19 14:55:58 -08001827}
1828
1829// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001830
1831void AudioFlinger::PlaybackThread::onFirstRef()
1832{
Glenn Kastend7dca052015-03-05 16:05:54 -08001833 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001834}
1835
1836// ThreadBase virtuals
1837void AudioFlinger::PlaybackThread::preExit()
1838{
1839 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001840 // FIXME this is using hard-coded strings but in the future, this functionality will be
1841 // converted to use audio HAL extensions required to support tunneling
1842 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1843 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001844}
1845
1846// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1847sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1848 const sp<AudioFlinger::Client>& client,
1849 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001850 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001851 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001852 audio_format_t format,
1853 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001854 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001855 size_t *pNotificationFrameCount,
1856 uint32_t notificationsPerBuffer,
1857 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001858 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001859 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001860 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001861 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001862 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001863 status_t *status,
1864 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001865{
Glenn Kasten74935e42013-12-19 08:56:45 -08001866 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001867 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001868 sp<Track> track;
1869 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001870 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001871 audio_output_flags_t requestedFlags = *flags;
1872
1873 if (*pSampleRate == 0) {
1874 *pSampleRate = mSampleRate;
1875 }
1876 uint32_t sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001877
1878 // special case for FAST flag considered OK if fast mixer is present
1879 if (hasFastMixer()) {
1880 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1881 }
1882
1883 // Check if requested flags are compatible with output stream flags
1884 if ((*flags & outputFlags) != *flags) {
1885 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1886 *flags, outputFlags);
1887 *flags = (audio_output_flags_t)(*flags & outputFlags);
1888 }
Eric Laurent81784c32012-11-19 14:55:58 -08001889
Eric Laurent81784c32012-11-19 14:55:58 -08001890 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001891 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001892 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001893 // PCM data
1894 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001895 // TODO: extract as a data library function that checks that a computationally
1896 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001897 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001898 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1899 (channelMask == AUDIO_CHANNEL_OUT_MONO
1900 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001901 // hardware sample rate
1902 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001903 // normal mixer has an associated fast mixer
1904 hasFastMixer() &&
1905 // there are sufficient fast track slots available
1906 (mFastTrackAvailMask != 0)
1907 // FIXME test that MixerThread for this fast track has a capable output HAL
1908 // FIXME add a permission test also?
1909 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001910 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1911 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001912 // read the fast track multiplier property the first time it is needed
1913 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1914 if (ok != 0) {
1915 ALOGE("%s pthread_once failed: %d", __func__, ok);
1916 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001917 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001918 }
Eric Laurent4c415062016-06-17 16:14:16 -07001919
1920 // check compatibility with audio effects.
1921 { // scope for mLock
1922 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001923 for (audio_session_t session : {
1924 AUDIO_SESSION_OUTPUT_STAGE,
1925 AUDIO_SESSION_OUTPUT_MIX,
1926 sessionId,
1927 }) {
1928 sp<EffectChain> chain = getEffectChain_l(session);
1929 if (chain.get() != nullptr) {
1930 audio_output_flags_t old = *flags;
1931 chain->checkOutputFlagCompatibility(flags);
1932 if (old != *flags) {
1933 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1934 (int)session, (int)old, (int)*flags);
1935 }
Eric Laurent4c415062016-06-17 16:14:16 -07001936 }
1937 }
1938 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001939 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001940 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1941 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001942 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001943 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1944 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001945 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001946 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001947 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001948 audio_is_linear_pcm(format),
1949 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001950 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001951 }
1952 }
Eric Laurent21da6472017-11-09 16:29:26 -08001953
1954 if (!audio_has_proportional_frames(format)) {
1955 if (sharedBuffer != 0) {
1956 // Same comment as below about ignoring frameCount parameter for set()
1957 frameCount = sharedBuffer->size();
1958 } else if (frameCount == 0) {
1959 frameCount = mNormalFrameCount;
1960 }
1961 if (notificationFrameCount != frameCount) {
1962 notificationFrameCount = frameCount;
1963 }
1964 } else if (sharedBuffer != 0) {
1965 // FIXME: Ensure client side memory buffers need
1966 // not have additional alignment beyond sample
1967 // (e.g. 16 bit stereo accessed as 32 bit frame).
1968 size_t alignment = audio_bytes_per_sample(format);
1969 if (alignment & 1) {
1970 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
1971 alignment = 1;
1972 }
1973 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1974 size_t frameSize = channelCount * audio_bytes_per_sample(format);
1975 if (channelCount > 1) {
1976 // More than 2 channels does not require stronger alignment than stereo
1977 alignment <<= 1;
1978 }
1979 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
1980 ALOGE("Invalid buffer alignment: address %p, channel count %u",
1981 sharedBuffer->pointer(), channelCount);
1982 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001983 goto Exit;
1984 }
Eric Laurent21da6472017-11-09 16:29:26 -08001985
1986 // When initializing a shared buffer AudioTrack via constructors,
1987 // there's no frameCount parameter.
1988 // But when initializing a shared buffer AudioTrack via set(),
1989 // there _is_ a frameCount parameter. We silently ignore it.
1990 frameCount = sharedBuffer->size() / frameSize;
1991 } else {
1992 size_t minFrameCount = 0;
1993 // For fast tracks we try to respect the application's request for notifications per buffer.
1994 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
1995 if (notificationsPerBuffer > 0) {
1996 // Avoid possible arithmetic overflow during multiplication.
1997 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
1998 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
1999 notificationsPerBuffer, mFrameCount);
2000 } else {
2001 minFrameCount = mFrameCount * notificationsPerBuffer;
2002 }
2003 }
2004 } else {
2005 // For normal PCM streaming tracks, update minimum frame count.
2006 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2007 // cover audio hardware latency.
2008 // This is probably too conservative, but legacy application code may depend on it.
2009 // If you change this calculation, also review the start threshold which is related.
2010 uint32_t latencyMs = latency_l();
2011 if (latencyMs == 0) {
2012 ALOGE("Error when retrieving output stream latency");
2013 lStatus = UNKNOWN_ERROR;
2014 goto Exit;
2015 }
2016
2017 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2018 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2019
Eric Laurent81784c32012-11-19 14:55:58 -08002020 }
Eric Laurent21da6472017-11-09 16:29:26 -08002021 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002022 frameCount = minFrameCount;
2023 }
Eric Laurent81784c32012-11-19 14:55:58 -08002024 }
Eric Laurent21da6472017-11-09 16:29:26 -08002025
2026 // Make sure that application is notified with sufficient margin before underrun.
2027 // The client can divide the AudioTrack buffer into sub-buffers,
2028 // and expresses its desire to server as the notification frame count.
2029 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2030 size_t maxNotificationFrames;
2031 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2032 // notify every HAL buffer, regardless of the size of the track buffer
2033 maxNotificationFrames = mFrameCount;
2034 } else {
2035 // For normal tracks, use at least double-buffering if no sample rate conversion,
2036 // or at least triple-buffering if there is sample rate conversion
2037 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2038 maxNotificationFrames = frameCount / nBuffering;
2039 // If client requested a fast track but this was denied, then use the smaller maximum.
2040 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2041 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2042 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2043 maxNotificationFrames = maxNotificationFramesFastDenied;
2044 }
2045 }
2046 }
2047 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2048 if (notificationFrameCount == 0) {
2049 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2050 maxNotificationFrames, frameCount);
2051 } else {
2052 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2053 notificationFrameCount, maxNotificationFrames, frameCount);
2054 }
2055 notificationFrameCount = maxNotificationFrames;
2056 }
2057 }
2058
Glenn Kasten74935e42013-12-19 08:56:45 -08002059 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002060 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002061
Glenn Kastenc3df8382014-03-13 15:05:25 -07002062 switch (mType) {
2063
2064 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002065 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002066 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002067 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2068 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002069 sampleRate, format, channelMask, mOutput, mFormat);
2070 lStatus = BAD_VALUE;
2071 goto Exit;
2072 }
2073 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002074 break;
2075
2076 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002077 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002078 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2079 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002080 sampleRate, format, channelMask, mOutput, mFormat);
2081 lStatus = BAD_VALUE;
2082 goto Exit;
2083 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002084 break;
2085
2086 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002087 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002088 ALOGE("createTrack_l() Bad parameter: format %#x \""
2089 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002090 format, mOutput, mFormat);
2091 lStatus = BAD_VALUE;
2092 goto Exit;
2093 }
Andy Hungcd044842014-08-07 11:04:34 -07002094 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002095 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2096 lStatus = BAD_VALUE;
2097 goto Exit;
2098 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002099 break;
2100
Eric Laurent81784c32012-11-19 14:55:58 -08002101 }
2102
2103 lStatus = initCheck();
2104 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002105 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002106 goto Exit;
2107 }
2108
2109 { // scope for mLock
2110 Mutex::Autolock _l(mLock);
2111
2112 // all tracks in same audio session must share the same routing strategy otherwise
2113 // conflicts will happen when tracks are moved from one output to another by audio policy
2114 // manager
2115 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2116 for (size_t i = 0; i < mTracks.size(); ++i) {
2117 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002118 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002119 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2120 if (sessionId == t->sessionId() && strategy != actual) {
2121 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2122 strategy, actual);
2123 lStatus = BAD_VALUE;
2124 goto Exit;
2125 }
2126 }
2127 }
2128
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002129 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002130 channelMask, frameCount,
2131 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002132 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002133
Glenn Kasten03003332013-08-06 15:40:54 -07002134 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2135 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002136 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002137 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002138 goto Exit;
2139 }
2140 mTracks.add(track);
2141
2142 sp<EffectChain> chain = getEffectChain_l(sessionId);
2143 if (chain != 0) {
2144 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2145 track->setMainBuffer(chain->inBuffer());
2146 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2147 chain->incTrackCnt();
2148 }
2149
Eric Laurent05067782016-06-01 18:27:28 -07002150 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002151 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2152 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2153 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002154 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002155 }
2156 }
2157
2158 lStatus = NO_ERROR;
2159
2160Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002161 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002162 return track;
2163}
2164
Andy Hung1bc088a2018-02-09 15:57:31 -08002165template<typename T>
2166ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track)
2167{
2168 const ssize_t index = mTracks.add(track);
2169 if (index >= 0) {
2170 // set name for track when adding.
2171 int name;
2172 if (mUnusedTrackNames.empty()) {
2173 name = mTracks.size() - 1; // new name {0 ... size-1}.
2174 } else {
2175 // reuse smallest name for deleted track.
2176 auto it = mUnusedTrackNames.begin();
2177 name = *it;
2178 (void)mUnusedTrackNames.erase(it);
2179 }
2180 track->setName(name);
2181 } else {
2182 LOG_ALWAYS_FATAL("cannot add track");
2183 }
2184 return index;
2185}
2186
2187template<typename T>
2188ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2189{
2190 const int name = track->name();
2191 const ssize_t index = mTracks.remove(track);
2192 if (index >= 0) {
2193 // invalidate name when removing from mTracks.
2194 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name);
2195
2196 if (mSaveDeletedTrackNames) {
2197 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2198 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update,
2199 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2200 mDeletedTrackNames.emplace(name);
2201 }
2202
2203 mUnusedTrackNames.emplace(name);
2204 track->setName(T::TRACK_NAME_PENDING);
2205 } else {
2206 LOG_ALWAYS_FATAL_IF(name >= 0,
2207 "valid name %d for track not in mTracks (returned %zd)", name, index);
2208 }
2209 return index;
2210}
2211
Eric Laurent81784c32012-11-19 14:55:58 -08002212uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2213{
2214 return latency;
2215}
2216
2217uint32_t AudioFlinger::PlaybackThread::latency() const
2218{
2219 Mutex::Autolock _l(mLock);
2220 return latency_l();
2221}
2222uint32_t AudioFlinger::PlaybackThread::latency_l() const
2223{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002224 uint32_t latency;
2225 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2226 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002227 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002228 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002229}
2230
2231void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2232{
2233 Mutex::Autolock _l(mLock);
2234 // Don't apply master volume in SW if our HAL can do it for us.
2235 if (mOutput && mOutput->audioHwDev &&
2236 mOutput->audioHwDev->canSetMasterVolume()) {
2237 mMasterVolume = 1.0;
2238 } else {
2239 mMasterVolume = value;
2240 }
2241}
2242
2243void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2244{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002245 if (isDuplicating()) {
2246 return;
2247 }
Eric Laurent81784c32012-11-19 14:55:58 -08002248 Mutex::Autolock _l(mLock);
2249 // Don't apply master mute in SW if our HAL can do it for us.
2250 if (mOutput && mOutput->audioHwDev &&
2251 mOutput->audioHwDev->canSetMasterMute()) {
2252 mMasterMute = false;
2253 } else {
2254 mMasterMute = muted;
2255 }
2256}
2257
2258void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2259{
2260 Mutex::Autolock _l(mLock);
2261 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002262 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002263}
2264
2265void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2266{
2267 Mutex::Autolock _l(mLock);
2268 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002269 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002270}
2271
2272float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2273{
2274 Mutex::Autolock _l(mLock);
2275 return mStreamTypes[stream].volume;
2276}
2277
2278// addTrack_l() must be called with ThreadBase::mLock held
2279status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2280{
2281 status_t status = ALREADY_EXISTS;
2282
Eric Laurent81784c32012-11-19 14:55:58 -08002283 if (mActiveTracks.indexOf(track) < 0) {
2284 // the track is newly added, make sure it fills up all its
2285 // buffers before playing. This is to ensure the client will
2286 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002287 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288 TrackBase::track_state state = track->mState;
2289 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002290 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002291 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002292 mLock.lock();
2293 // abort track was stopped/paused while we released the lock
2294 if (state != track->mState) {
2295 if (status == NO_ERROR) {
2296 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002297 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002298 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002299 mLock.lock();
2300 }
2301 return INVALID_OPERATION;
2302 }
2303 // abort if start is rejected by audio policy manager
2304 if (status != NO_ERROR) {
2305 return PERMISSION_DENIED;
2306 }
2307#ifdef ADD_BATTERY_DATA
2308 // to track the speaker usage
2309 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2310#endif
2311 }
2312
Eric Laurent51716182016-02-29 18:00:56 -08002313 // set retry count for buffer fill
2314 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002315 if (track->isStopping_1()) {
2316 track->mRetryCount = kMaxTrackStopRetriesOffload;
2317 } else {
2318 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2319 }
2320 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002321 } else {
2322 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002323 track->mFillingUpStatus =
2324 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002325 }
2326
Eric Laurent81784c32012-11-19 14:55:58 -08002327 track->mResetDone = false;
2328 track->mPresentationCompleteFrames = 0;
2329 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002330 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2331 if (chain != 0) {
2332 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2333 track->sessionId());
2334 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002335 }
2336
2337 status = NO_ERROR;
2338 }
2339
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002340 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002341 return status;
2342}
2343
Eric Laurentbfb1b832013-01-07 09:53:42 -08002344bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002345{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002346 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002347 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002348 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2349 track->mState = TrackBase::STOPPED;
2350 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002351 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002352 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002353 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002354 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002355
2356 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002357}
2358
2359void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2360{
2361 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002362
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002363 String8 result;
2364 track->appendDump(result, false /* active */);
2365 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002366
Eric Laurent81784c32012-11-19 14:55:58 -08002367 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002368 if (track->isFastTrack()) {
2369 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002370 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002371 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2372 mFastTrackAvailMask |= 1 << index;
2373 // redundant as track is about to be destroyed, for dumpsys only
2374 track->mFastIndex = -1;
2375 }
2376 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2377 if (chain != 0) {
2378 chain->decTrackCnt();
2379 }
2380}
2381
2382String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2383{
Eric Laurent81784c32012-11-19 14:55:58 -08002384 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002385 String8 out_s8;
2386 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2387 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002388 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002389 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002390}
2391
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002392void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002393 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2394 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002395
Eric Laurent73e26b62015-04-27 16:55:58 -07002396 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002397
2398 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002399 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002400 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002401 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002402 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002403 desc->mChannelMask = mChannelMask;
2404 desc->mSamplingRate = mSampleRate;
2405 desc->mFormat = mFormat;
2406 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002407 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002408 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002409 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002410 break;
2411
Eric Laurent73e26b62015-04-27 16:55:58 -07002412 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002413 default:
2414 break;
2415 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002416 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002417}
2418
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002419void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002420{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002421 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002422}
2423
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002424void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002425{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002426 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002427}
2428
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002429void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002430{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002431 mCallbackThread->setAsyncError();
2432}
2433
Eric Laurent3b4529e2013-09-05 18:09:19 -07002434void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002435{
2436 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002437 // reject out of sequence requests
2438 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2439 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002440 mWaitWorkCV.signal();
2441 }
2442}
2443
Eric Laurent3b4529e2013-09-05 18:09:19 -07002444void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002445{
2446 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002447 // reject out of sequence requests
2448 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2449 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002450 mWaitWorkCV.signal();
2451 }
2452}
2453
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002454void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002455{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002456 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002457 mSampleRate = mOutput->getSampleRate();
2458 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002459 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002460 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002461 }
Andy Hung9a592762014-07-21 21:56:01 -07002462 if ((mType == MIXER || mType == DUPLICATING)
2463 && !isValidPcmSinkChannelMask(mChannelMask)) {
2464 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2465 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002466 }
Andy Hunge5412692014-05-16 11:25:07 -07002467 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002468
2469 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002470 status_t result = mOutput->stream->getFormat(&mHALFormat);
2471 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002472 // Get format from the shim, which will be different than the HAL format
2473 // if playing compressed audio over HDMI passthrough.
2474 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002475 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002476 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002477 }
Andy Hung6146c082014-03-18 11:56:15 -07002478 if ((mType == MIXER || mType == DUPLICATING)
2479 && !isValidPcmSinkFormat(mFormat)) {
2480 LOG_FATAL("HAL format %#x not supported for mixed output",
2481 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002482 }
Phil Burk062e67a2015-02-11 13:40:50 -08002483 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002484 result = mOutput->stream->getBufferSize(&mBufferSize);
2485 LOG_ALWAYS_FATAL_IF(result != OK,
2486 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002487 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002488 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002489 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002490 mFrameCount);
2491 }
2492
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002493 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2494 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002496 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497 }
2498 }
2499
Eric Laurentd1f69b02014-12-15 14:33:13 -08002500 mHwSupportsPause = false;
2501 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002502 bool supportsPause = false, supportsResume = false;
2503 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2504 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002505 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002506 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002507 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002508 } else if (supportsResume) {
2509 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002510 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002511 }
2512 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002513 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2514 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2515 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002516
Andy Hungfbfc3952015-01-15 13:33:51 -08002517 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2518 // For best precision, we use float instead of the associated output
2519 // device format (typically PCM 16 bit).
2520
2521 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2522 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2523 mBufferSize = mFrameSize * mFrameCount;
2524
2525 // TODO: We currently use the associated output device channel mask and sample rate.
2526 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2527 // (if a valid mask) to avoid premature downmix.
2528 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2529 // instead of the output device sample rate to avoid loss of high frequency information.
2530 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2531 }
2532
Andy Hung09a50072014-02-27 14:30:47 -08002533 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002534 double multiplier = 1.0;
2535 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2536 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002537 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2538 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002539
Eric Laurent81784c32012-11-19 14:55:58 -08002540 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2541 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2542 maxNormalFrameCount = maxNormalFrameCount & ~15;
2543 if (maxNormalFrameCount < minNormalFrameCount) {
2544 maxNormalFrameCount = minNormalFrameCount;
2545 }
2546 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2547 if (multiplier <= 1.0) {
2548 multiplier = 1.0;
2549 } else if (multiplier <= 2.0) {
2550 if (2 * mFrameCount <= maxNormalFrameCount) {
2551 multiplier = 2.0;
2552 } else {
2553 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2554 }
2555 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002556 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002557 }
2558 }
2559 mNormalFrameCount = multiplier * mFrameCount;
2560 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002561 if (mType == MIXER || mType == DUPLICATING) {
2562 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2563 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002564 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002565 mNormalFrameCount);
2566
Andy Hung08fb1742015-05-31 23:22:10 -07002567 // Check if we want to throttle the processing to no more than 2x normal rate
2568 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002569 mThreadThrottleTimeMs = 0;
2570 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002571 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2572
Andy Hung010a1a12014-03-13 13:57:33 -07002573 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2574 // Originally this was int16_t[] array, need to remove legacy implications.
2575 free(mSinkBuffer);
2576 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002577 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2578 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2579 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002580 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002581
Andy Hung69aed5f2014-02-25 17:24:40 -08002582 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2583 // drives the output.
2584 free(mMixerBuffer);
2585 mMixerBuffer = NULL;
2586 if (mMixerBufferEnabled) {
2587 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2588 mMixerBufferSize = mNormalFrameCount * mChannelCount
2589 * audio_bytes_per_sample(mMixerBufferFormat);
2590 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2591 }
Andy Hung98ef9782014-03-04 14:46:50 -08002592 free(mEffectBuffer);
2593 mEffectBuffer = NULL;
2594 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002595 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002596 mEffectBufferSize = mNormalFrameCount * mChannelCount
2597 * audio_bytes_per_sample(mEffectBufferFormat);
2598 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2599 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002600
Eric Laurent81784c32012-11-19 14:55:58 -08002601 // force reconfiguration of effect chains and engines to take new buffer size and audio
2602 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002603 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002604 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2605 // matter.
2606 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2607 Vector< sp<EffectChain> > effectChains = mEffectChains;
2608 for (size_t i = 0; i < effectChains.size(); i ++) {
2609 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2610 }
2611}
2612
2613
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002614status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002615{
2616 if (halFrames == NULL || dspFrames == NULL) {
2617 return BAD_VALUE;
2618 }
2619 Mutex::Autolock _l(mLock);
2620 if (initCheck() != NO_ERROR) {
2621 return INVALID_OPERATION;
2622 }
Andy Hung818e7a32016-02-16 18:08:07 -08002623 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002624 *halFrames = framesWritten;
2625
2626 if (isSuspended()) {
2627 // return an estimation of rendered frames when the output is suspended
2628 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002629 *dspFrames = (uint32_t)
2630 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002631 return NO_ERROR;
2632 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002633 status_t status;
2634 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002635 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002636 *dspFrames = (size_t)frames;
2637 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002638 }
2639}
2640
Eric Laurent4c415062016-06-17 16:14:16 -07002641// hasAudioSession_l() must be called with ThreadBase::mLock held
2642uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002643{
Eric Laurent81784c32012-11-19 14:55:58 -08002644 uint32_t result = 0;
2645 if (getEffectChain_l(sessionId) != 0) {
2646 result = EFFECT_SESSION;
2647 }
2648
2649 for (size_t i = 0; i < mTracks.size(); ++i) {
2650 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002651 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002652 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002653 if (track->isFastTrack()) {
2654 result |= FAST_SESSION;
2655 }
Eric Laurent81784c32012-11-19 14:55:58 -08002656 break;
2657 }
2658 }
2659
2660 return result;
2661}
2662
Glenn Kastend848eb42016-03-08 13:42:11 -08002663uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002664{
2665 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2666 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2667 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2668 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2669 }
2670 for (size_t i = 0; i < mTracks.size(); i++) {
2671 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002672 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002673 return AudioSystem::getStrategyForStream(track->streamType());
2674 }
2675 }
2676 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2677}
2678
2679
Phil Burk062e67a2015-02-11 13:40:50 -08002680AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002681{
2682 Mutex::Autolock _l(mLock);
2683 return mOutput;
2684}
2685
Phil Burk062e67a2015-02-11 13:40:50 -08002686AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002687{
2688 Mutex::Autolock _l(mLock);
2689 AudioStreamOut *output = mOutput;
2690 mOutput = NULL;
2691 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2692 // must push a NULL and wait for ack
2693 mOutputSink.clear();
2694 mPipeSink.clear();
2695 mNormalSink.clear();
2696 return output;
2697}
2698
2699// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002700sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002701{
2702 if (mOutput == NULL) {
2703 return NULL;
2704 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002705 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002706}
2707
2708uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2709{
2710 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2711}
2712
2713status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2714{
2715 if (!isValidSyncEvent(event)) {
2716 return BAD_VALUE;
2717 }
2718
2719 Mutex::Autolock _l(mLock);
2720
2721 for (size_t i = 0; i < mTracks.size(); ++i) {
2722 sp<Track> track = mTracks[i];
2723 if (event->triggerSession() == track->sessionId()) {
2724 (void) track->setSyncEvent(event);
2725 return NO_ERROR;
2726 }
2727 }
2728
2729 return NAME_NOT_FOUND;
2730}
2731
2732bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2733{
2734 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2735}
2736
2737void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2738 const Vector< sp<Track> >& tracksToRemove)
2739{
2740 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002741 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002742 for (size_t i = 0 ; i < count ; i++) {
2743 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002744 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002745 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002746 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002747#ifdef ADD_BATTERY_DATA
2748 // to track the speaker usage
2749 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2750#endif
2751 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002752 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002753 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002754 }
Eric Laurent81784c32012-11-19 14:55:58 -08002755 }
2756 }
2757 }
Eric Laurent81784c32012-11-19 14:55:58 -08002758}
2759
2760void AudioFlinger::PlaybackThread::checkSilentMode_l()
2761{
2762 if (!mMasterMute) {
2763 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002764 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2765 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2766 return;
2767 }
Eric Laurent81784c32012-11-19 14:55:58 -08002768 if (property_get("ro.audio.silent", value, "0") > 0) {
2769 char *endptr;
2770 unsigned long ul = strtoul(value, &endptr, 0);
2771 if (*endptr == '\0' && ul != 0) {
2772 ALOGD("Silence is golden");
2773 // The setprop command will not allow a property to be changed after
2774 // the first time it is set, so we don't have to worry about un-muting.
2775 setMasterMute_l(true);
2776 }
2777 }
2778 }
2779}
2780
2781// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002782ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002783{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002784 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002785 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002786 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002787 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002788
2789 // If an NBAIO sink is present, use it to write the normal mixer's submix
2790 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002791
Andy Hung010a1a12014-03-13 13:57:33 -07002792 const size_t count = mBytesRemaining / mFrameSize;
2793
Simon Wilson2d590962012-11-29 15:18:50 -08002794 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002795 // update the setpoint when AudioFlinger::mScreenState changes
2796 uint32_t screenState = AudioFlinger::mScreenState;
2797 if (screenState != mScreenState) {
2798 mScreenState = screenState;
2799 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2800 if (pipe != NULL) {
2801 pipe->setAvgFrames((mScreenState & 1) ?
2802 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2803 }
2804 }
Andy Hung010a1a12014-03-13 13:57:33 -07002805 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002806 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002807 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002808 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002809 } else {
2810 bytesWritten = framesWritten;
2811 }
2812 // otherwise use the HAL / AudioStreamOut directly
2813 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002814 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002815
Eric Laurentbfb1b832013-01-07 09:53:42 -08002816 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002817 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2818 mWriteAckSequence += 2;
2819 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002821 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002822 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002823 // FIXME We should have an implementation of timestamps for direct output threads.
2824 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002825 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002826
Eric Laurentbfb1b832013-01-07 09:53:42 -08002827 if (mUseAsyncWrite &&
2828 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2829 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002830 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002831 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002832 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002833 }
Eric Laurent81784c32012-11-19 14:55:58 -08002834 }
2835
Eric Laurent81784c32012-11-19 14:55:58 -08002836 mNumWrites++;
2837 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002838 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002839 return bytesWritten;
2840}
2841
2842void AudioFlinger::PlaybackThread::threadLoop_drain()
2843{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002844 bool supportsDrain = false;
2845 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002846 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2847 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002848 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2849 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002850 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002851 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002852 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002853 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002854 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002855 }
2856}
2857
2858void AudioFlinger::PlaybackThread::threadLoop_exit()
2859{
Eric Laurent275e8e92014-11-30 15:14:47 -08002860 {
2861 Mutex::Autolock _l(mLock);
2862 for (size_t i = 0; i < mTracks.size(); i++) {
2863 sp<Track> track = mTracks[i];
2864 track->invalidate();
2865 }
Andy Hungdae27702016-10-31 14:01:16 -07002866 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2867 // After we exit there are no more track changes sent to BatteryNotifier
2868 // because that requires an active threadLoop.
2869 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2870 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002871 }
Eric Laurent81784c32012-11-19 14:55:58 -08002872}
2873
2874/*
2875The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002876 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002877 - mActiveSleepTimeUs from activeSleepTimeUs()
2878 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002879 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2880 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002881 - maxPeriod from frame count and sample rate (MIXER only)
2882
2883The parameters that affect these derived values are:
2884 - frame count
2885 - frame size
2886 - sample rate
2887 - device type: A2DP or not
2888 - device latency
2889 - format: PCM or not
2890 - active sleep time
2891 - idle sleep time
2892*/
2893
2894void AudioFlinger::PlaybackThread::cacheParameters_l()
2895{
Andy Hung25c2dac2014-02-27 14:56:00 -08002896 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002897 mActiveSleepTimeUs = activeSleepTimeUs();
2898 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002899
2900 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2901 // truncating audio when going to standby.
2902 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2903 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2904 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2905 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2906 }
2907 }
Eric Laurent81784c32012-11-19 14:55:58 -08002908}
2909
Eric Laurent13084622016-05-17 10:51:49 -07002910bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002911{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002912 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002913 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002914 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002915 size_t size = mTracks.size();
2916 for (size_t i = 0; i < size; i++) {
2917 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002918 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002919 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002920 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002921 }
2922 }
Eric Laurent13084622016-05-17 10:51:49 -07002923 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002924}
2925
Haynes Mathew George05317d22016-05-03 16:34:26 -07002926void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2927{
2928 Mutex::Autolock _l(mLock);
2929 invalidateTracks_l(streamType);
2930}
2931
Eric Laurent81784c32012-11-19 14:55:58 -08002932status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2933{
Glenn Kastend848eb42016-03-08 13:42:11 -08002934 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002935 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002936 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08002937 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2938 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2939 &halInBuffer);
2940 if (result != OK) return result;
2941 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07002942 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002943 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002944 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002945 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002946 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002947 if (mType != DIRECT) {
2948 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002949 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07002950 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08002951 &halInBuffer);
2952 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07002953#ifdef FLOAT_EFFECT_CHAIN
2954 buffer = halInBuffer->audioBuffer()->f32;
2955#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08002956 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07002957#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08002958 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2959 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002960 }
2961
2962 // Attach all tracks with same session ID to this chain.
2963 for (size_t i = 0; i < mTracks.size(); ++i) {
2964 sp<Track> track = mTracks[i];
2965 if (session == track->sessionId()) {
2966 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2967 buffer);
2968 track->setMainBuffer(buffer);
2969 chain->incTrackCnt();
2970 }
2971 }
2972
2973 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002974 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002975 if (session == track->sessionId()) {
2976 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2977 chain->incActiveTrackCnt();
2978 }
2979 }
2980 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002981 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002982 chain->setInBuffer(halInBuffer);
2983 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002984 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002985 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002986 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2987 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002988 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002989 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002990 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002991 // Effect chain for other sessions are inserted at beginning of effect
2992 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002993 // sessions is not important.
2994 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2995 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2996 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002997 size_t size = mEffectChains.size();
2998 size_t i = 0;
2999 for (i = 0; i < size; i++) {
3000 if (mEffectChains[i]->sessionId() < session) {
3001 break;
3002 }
3003 }
3004 mEffectChains.insertAt(chain, i);
3005 checkSuspendOnAddEffectChain_l(chain);
3006
3007 return NO_ERROR;
3008}
3009
3010size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3011{
Glenn Kastend848eb42016-03-08 13:42:11 -08003012 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003013
3014 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3015
3016 for (size_t i = 0; i < mEffectChains.size(); i++) {
3017 if (chain == mEffectChains[i]) {
3018 mEffectChains.removeAt(i);
3019 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003020 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003021 if (session == track->sessionId()) {
3022 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3023 chain.get(), session);
3024 chain->decActiveTrackCnt();
3025 }
3026 }
3027
3028 // detach all tracks with same session ID from this chain
3029 for (size_t i = 0; i < mTracks.size(); ++i) {
3030 sp<Track> track = mTracks[i];
3031 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003032 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003033 chain->decTrackCnt();
3034 }
3035 }
3036 break;
3037 }
3038 }
3039 return mEffectChains.size();
3040}
3041
3042status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003043 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003044{
3045 Mutex::Autolock _l(mLock);
3046 return attachAuxEffect_l(track, EffectId);
3047}
3048
3049status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003050 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003051{
3052 status_t status = NO_ERROR;
3053
3054 if (EffectId == 0) {
3055 track->setAuxBuffer(0, NULL);
3056 } else {
3057 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3058 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3059 if (effect != 0) {
3060 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3061 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3062 } else {
3063 status = INVALID_OPERATION;
3064 }
3065 } else {
3066 status = BAD_VALUE;
3067 }
3068 }
3069 return status;
3070}
3071
3072void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3073{
3074 for (size_t i = 0; i < mTracks.size(); ++i) {
3075 sp<Track> track = mTracks[i];
3076 if (track->auxEffectId() == effectId) {
3077 attachAuxEffect_l(track, 0);
3078 }
3079 }
3080}
3081
3082bool AudioFlinger::PlaybackThread::threadLoop()
3083{
Glenn Kasten388d5712017-04-07 14:38:41 -07003084 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003085
Eric Laurent81784c32012-11-19 14:55:58 -08003086 Vector< sp<Track> > tracksToRemove;
3087
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003088 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003089 nsecs_t lastWriteFinished = -1; // time last server write completed
3090 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003091
3092 // MIXER
3093 nsecs_t lastWarning = 0;
3094
3095 // DUPLICATING
3096 // FIXME could this be made local to while loop?
3097 writeFrames = 0;
3098
3099 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003100 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003101
3102 if (mType == MIXER) {
3103 sleepTimeShift = 0;
3104 }
3105
3106 CpuStats cpuStats;
3107 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3108
3109 acquireWakeLock();
3110
Glenn Kasteneef598c2017-04-03 14:41:13 -07003111 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3112 // thread associated with this PlaybackThread.
3113 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3114 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003115 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3116 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003117 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003118 const char *logString = NULL;
3119
rago1bb90822017-05-02 18:31:48 -07003120 // Estimated time for next buffer to be written to hal. This is used only on
3121 // suspended mode (for now) to help schedule the wait time until next iteration.
3122 nsecs_t timeLoopNextNs = 0;
3123
Eric Laurent664539d2013-09-23 18:24:31 -07003124 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003125
Eric Laurent81784c32012-11-19 14:55:58 -08003126 while (!exitPending())
3127 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003128 // Log merge requests are performed during AudioFlinger binder transactions, but
3129 // that does not cover audio playback. It's requested here for that reason.
3130 mAudioFlinger->requestLogMerge();
3131
Eric Laurent81784c32012-11-19 14:55:58 -08003132 cpuStats.sample(myName);
3133
3134 Vector< sp<EffectChain> > effectChains;
3135
Eric Laurent81784c32012-11-19 14:55:58 -08003136 { // scope for mLock
3137
3138 Mutex::Autolock _l(mLock);
3139
Eric Laurent021cf962014-05-13 10:18:14 -07003140 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003141
Glenn Kasteneef598c2017-04-03 14:41:13 -07003142 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003143 if (logString != NULL) {
3144 mNBLogWriter->logTimestamp();
3145 mNBLogWriter->log(logString);
3146 logString = NULL;
3147 }
3148
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003149 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003150 // and associate with the sink frames written out. We need
3151 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003152 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003153 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003154 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003155 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003156 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003157 ExtendedTimestamp timestamp; // use private copy to fetch
3158 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003159
3160 // We keep track of the last valid kernel position in case we are in underrun
3161 // and the normal mixer period is the same as the fast mixer period, or there
3162 // is some error from the HAL.
3163 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3164 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3165 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3166 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3167 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3168
3169 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3170 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3171 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3172 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003173 }
3174
3175 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3176 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003177 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003178 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003179 }
3180
Andy Hung818e7a32016-02-16 18:08:07 -08003181 // copy over kernel info
3182 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003183 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3184 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003185 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3186 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003187 }
3188 // mFramesWritten for non-offloaded tracks are contiguous
3189 // even after standby() is called. This is useful for the track frame
3190 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003191 bool serverLocationUpdate = false;
3192 if (mFramesWritten != lastFramesWritten) {
3193 serverLocationUpdate = true;
3194 lastFramesWritten = mFramesWritten;
3195 }
3196 // Only update timestamps if there is a meaningful change.
3197 // Either the kernel timestamp must be valid or we have written something.
3198 if (kernelLocationUpdate || serverLocationUpdate) {
3199 if (serverLocationUpdate) {
3200 // use the time before we called the HAL write - it is a bit more accurate
3201 // to when the server last read data than the current time here.
3202 //
3203 // If we haven't written anything, mLastWriteTime will be -1
3204 // and we use systemTime().
3205 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3206 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3207 ? systemTime() : mLastWriteTime;
3208 }
Andy Hungdae27702016-10-31 14:01:16 -07003209
3210 for (const sp<Track> &t : mActiveTracks) {
3211 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003212 t->updateTrackFrameInfo(
3213 t->mAudioTrackServerProxy->framesReleased(),
3214 mFramesWritten,
3215 mTimestamp);
3216 }
Andy Hunge10393e2015-06-12 13:59:33 -07003217 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003218 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003219#if 0
3220 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003221 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003222 timespec ts;
3223 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003224 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003225 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003226 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003227 }
3228 ++z;
3229#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003230 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003231 if (mSignalPending) {
3232 // A signal was raised while we were unlocked
3233 mSignalPending = false;
3234 } else if (waitingAsyncCallback_l()) {
3235 if (exitPending()) {
3236 break;
3237 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003238 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003239 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003240 releaseWakeLock_l();
3241 released = true;
3242 }
Andy Hung10cbff12017-02-21 17:30:14 -08003243
3244 const int64_t waitNs = computeWaitTimeNs_l();
3245 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3246 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3247 if (status == TIMED_OUT) {
3248 mSignalPending = true; // if timeout recheck everything
3249 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003250 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003251 if (released) {
3252 acquireWakeLock_l();
3253 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003254 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3255 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003256
3257 continue;
3258 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003259 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003260 isSuspended()) {
3261 // put audio hardware into standby after short delay
3262 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003263
3264 threadLoop_standby();
3265
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003266 // This is where we go into standby
3267 if (!mStandby) {
3268 LOG_AUDIO_STATE();
3269 }
Eric Laurent81784c32012-11-19 14:55:58 -08003270 mStandby = true;
3271 }
3272
3273 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3274 // we're about to wait, flush the binder command buffer
3275 IPCThreadState::self()->flushCommands();
3276
3277 clearOutputTracks();
3278
3279 if (exitPending()) {
3280 break;
3281 }
3282
3283 releaseWakeLock_l();
3284 // wait until we have something to do...
3285 ALOGV("%s going to sleep", myName.string());
3286 mWaitWorkCV.wait(mLock);
3287 ALOGV("%s waking up", myName.string());
3288 acquireWakeLock_l();
3289
3290 mMixerStatus = MIXER_IDLE;
3291 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3292 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003293 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003294 checkSilentMode_l();
3295
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003296 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3297 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003298 if (mType == MIXER) {
3299 sleepTimeShift = 0;
3300 }
3301
3302 continue;
3303 }
3304 }
Eric Laurent81784c32012-11-19 14:55:58 -08003305 // mMixerStatusIgnoringFastTracks is also updated internally
3306 mMixerStatus = prepareTracks_l(&tracksToRemove);
3307
Andy Hungdae27702016-10-31 14:01:16 -07003308 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003309
Eric Laurent81784c32012-11-19 14:55:58 -08003310 // prevent any changes in effect chain list and in each effect chain
3311 // during mixing and effect process as the audio buffers could be deleted
3312 // or modified if an effect is created or deleted
3313 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003314 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003315
Eric Laurentbfb1b832013-01-07 09:53:42 -08003316 if (mBytesRemaining == 0) {
3317 mCurrentWriteLength = 0;
3318 if (mMixerStatus == MIXER_TRACKS_READY) {
3319 // threadLoop_mix() sets mCurrentWriteLength
3320 threadLoop_mix();
3321 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3322 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003323 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003324 // must be written to HAL
3325 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003326 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003327 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003328 }
3329 }
Andy Hung98ef9782014-03-04 14:46:50 -08003330 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003331 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003332 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3333 // or mSinkBuffer (if there are no effects).
3334 //
3335 // This is done pre-effects computation; if effects change to
3336 // support higher precision, this needs to move.
3337 //
3338 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003339 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003340 if (mMixerBufferValid) {
3341 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3342 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3343
Andy Hung2ddee192015-12-18 17:34:44 -08003344 // mono blend occurs for mixer threads only (not direct or offloaded)
3345 // and is handled here if we're going directly to the sink.
3346 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003347 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3348 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003349 }
3350
Andy Hung98ef9782014-03-04 14:46:50 -08003351 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3352 mNormalFrameCount * mChannelCount);
3353 }
3354
Eric Laurentbfb1b832013-01-07 09:53:42 -08003355 mBytesRemaining = mCurrentWriteLength;
3356 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003357 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3358 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3359 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3360 mBytesWritten += mBytesRemaining;
3361 mFramesWritten += framesRemaining;
3362 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003363 mBytesRemaining = 0;
3364 }
Eric Laurent81784c32012-11-19 14:55:58 -08003365
Eric Laurentbfb1b832013-01-07 09:53:42 -08003366 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003367 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003368 for (size_t i = 0; i < effectChains.size(); i ++) {
3369 effectChains[i]->process_l();
3370 }
Eric Laurent81784c32012-11-19 14:55:58 -08003371 }
3372 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003373 // Process effect chains for offloaded thread even if no audio
3374 // was read from audio track: process only updates effect state
3375 // and thus does have to be synchronized with audio writes but may have
3376 // to be called while waiting for async write callback
3377 if (mType == OFFLOAD) {
3378 for (size_t i = 0; i < effectChains.size(); i ++) {
3379 effectChains[i]->process_l();
3380 }
3381 }
Eric Laurent81784c32012-11-19 14:55:58 -08003382
Andy Hung98ef9782014-03-04 14:46:50 -08003383 // Only if the Effects buffer is enabled and there is data in the
3384 // Effects buffer (buffer valid), we need to
3385 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003386 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003387 if (mEffectBufferValid) {
3388 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003389
3390 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003391 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3392 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003393 }
3394
Andy Hung98ef9782014-03-04 14:46:50 -08003395 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3396 mNormalFrameCount * mChannelCount);
3397 }
3398
Eric Laurent81784c32012-11-19 14:55:58 -08003399 // enable changes in effect chain
3400 unlockEffectChains(effectChains);
3401
Eric Laurentbfb1b832013-01-07 09:53:42 -08003402 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003403 // mSleepTimeUs == 0 means we must write to audio hardware
3404 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003405 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003406 // We save lastWriteFinished here, as previousLastWriteFinished,
3407 // for throttling. On thread start, previousLastWriteFinished will be
3408 // set to -1, which properly results in no throttling after the first write.
3409 nsecs_t previousLastWriteFinished = lastWriteFinished;
3410 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003411 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003412 // FIXME rewrite to reduce number of system calls
3413 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003414 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003415 lastWriteFinished = systemTime();
3416 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003417 if (ret < 0) {
3418 mBytesRemaining = 0;
3419 } else {
3420 mBytesWritten += ret;
3421 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003422 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003423 }
3424 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3425 (mMixerStatus == MIXER_DRAIN_ALL)) {
3426 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003427 }
Andy Hung08fb1742015-05-31 23:22:10 -07003428 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003429 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003430 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003431 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003432 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003433 ATRACE_NAME("underrun");
3434 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003435 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003436 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003437 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003438 }
Andy Hung08fb1742015-05-31 23:22:10 -07003439
3440 if (mThreadThrottle
3441 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3442 && ret > 0) { // we wrote something
3443 // Limit MixerThread data processing to no more than twice the
3444 // expected processing rate.
3445 //
3446 // This helps prevent underruns with NuPlayer and other applications
3447 // which may set up buffers that are close to the minimum size, or use
3448 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3449 //
3450 // The throttle smooths out sudden large data drains from the device,
3451 // e.g. when it comes out of standby, which often causes problems with
3452 // (1) mixer threads without a fast mixer (which has its own warm-up)
3453 // (2) minimum buffer sized tracks (even if the track is full,
3454 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003455 //
3456 // Total time spent in last processing cycle equals time spent in
3457 // 1. threadLoop_write, as well as time spent in
3458 // 2. threadLoop_mix (significant for heavy mixing, especially
3459 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003460
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003461 // it's OK if deltaMs (and deltaNs) is an overestimate.
3462 nsecs_t deltaNs;
3463 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3464 __builtin_sub_overflow(
3465 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3466 const int32_t deltaMs = deltaNs / 1000000;
3467
Ivan Lozanoea04d392017-11-07 14:37:07 -08003468 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003469 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3470 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003471 // notify of throttle start on verbose log
3472 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3473 "mixer(%p) throttle begin:"
3474 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003475 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003476 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003477 // Throttle must be attributed to the previous mixer loop's write time
3478 // to allow back-to-back throttling.
3479 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003480 } else {
3481 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3482 if (diff > 0) {
3483 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003484 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003485 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3486 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003487 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003488 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3489 }
Andy Hung08fb1742015-05-31 23:22:10 -07003490 }
3491 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003492 }
Eric Laurent81784c32012-11-19 14:55:58 -08003493
Eric Laurentbfb1b832013-01-07 09:53:42 -08003494 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003495 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003496 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003497 // suspended requires accurate metering of sleep time.
3498 if (isSuspended()) {
3499 // advance by expected sleepTime
3500 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3501 const nsecs_t nowNs = systemTime();
3502
3503 // compute expected next time vs current time.
3504 // (negative deltas are treated as delays).
3505 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3506 if (deltaNs < -kMaxNextBufferDelayNs) {
3507 // Delays longer than the max allowed trigger a reset.
3508 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3509 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3510 timeLoopNextNs = nowNs + deltaNs;
3511 } else if (deltaNs < 0) {
3512 // Delays within the max delay allowed: zero the delta/sleepTime
3513 // to help the system catch up in the next iteration(s)
3514 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3515 deltaNs = 0;
3516 }
3517 // update sleep time (which is >= 0)
3518 mSleepTimeUs = deltaNs / 1000;
3519 }
Eric Laurente93cc032016-05-05 10:15:10 -07003520 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3521 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003522 }
Glenn Kastene7754022014-10-31 12:11:26 -07003523 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003524 }
Eric Laurent81784c32012-11-19 14:55:58 -08003525 }
3526
3527 // Finally let go of removed track(s), without the lock held
3528 // since we can't guarantee the destructors won't acquire that
3529 // same lock. This will also mutate and push a new fast mixer state.
3530 threadLoop_removeTracks(tracksToRemove);
3531 tracksToRemove.clear();
3532
3533 // FIXME I don't understand the need for this here;
3534 // it was in the original code but maybe the
3535 // assignment in saveOutputTracks() makes this unnecessary?
3536 clearOutputTracks();
3537
3538 // Effect chains will be actually deleted here if they were removed from
3539 // mEffectChains list during mixing or effects processing
3540 effectChains.clear();
3541
3542 // FIXME Note that the above .clear() is no longer necessary since effectChains
3543 // is now local to this block, but will keep it for now (at least until merge done).
3544 }
3545
Eric Laurentbfb1b832013-01-07 09:53:42 -08003546 threadLoop_exit();
3547
Eric Laurentcf817a22014-08-04 20:36:31 -07003548 if (!mStandby) {
3549 threadLoop_standby();
3550 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003551 }
3552
3553 releaseWakeLock();
3554
3555 ALOGV("Thread %p type %d exiting", this, mType);
3556 return false;
3557}
3558
Eric Laurentbfb1b832013-01-07 09:53:42 -08003559// removeTracks_l() must be called with ThreadBase::mLock held
3560void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3561{
3562 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003563 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003564 for (size_t i=0 ; i<count ; i++) {
3565 const sp<Track>& track = tracksToRemove.itemAt(i);
3566 mActiveTracks.remove(track);
3567 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3568 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3569 if (chain != 0) {
3570 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3571 track->sessionId());
3572 chain->decActiveTrackCnt();
3573 }
3574 if (track->isTerminated()) {
3575 removeTrack_l(track);
3576 }
3577 }
3578 }
3579
3580}
Eric Laurent81784c32012-11-19 14:55:58 -08003581
Eric Laurentaccc1472013-09-20 09:36:34 -07003582status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3583{
3584 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003585 ExtendedTimestamp ets;
3586 status_t status = mNormalSink->getTimestamp(ets);
3587 if (status == NO_ERROR) {
3588 status = ets.getBestTimestamp(&timestamp);
3589 }
3590 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003591 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003592 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003593 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003594 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003595 timestamp.mPosition = (uint32_t)position64;
3596 return NO_ERROR;
3597 }
3598 }
3599 return INVALID_OPERATION;
3600}
Eric Laurent1c333e22014-05-20 10:48:17 -07003601
Eric Laurent054d9d32015-04-24 08:48:48 -07003602status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3603 audio_patch_handle_t *handle)
3604{
Andy Hungf60abce2016-08-26 11:37:54 -07003605 status_t status;
3606 if (property_get_bool("af.patch_park", false /* default_value */)) {
3607 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3608 // or if HAL does not properly lock against access.
3609 AutoPark<FastMixer> park(mFastMixer);
3610 status = PlaybackThread::createAudioPatch_l(patch, handle);
3611 } else {
3612 status = PlaybackThread::createAudioPatch_l(patch, handle);
3613 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003614 return status;
3615}
3616
Eric Laurent1c333e22014-05-20 10:48:17 -07003617status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3618 audio_patch_handle_t *handle)
3619{
3620 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003621
3622 // store new device and send to effects
3623 audio_devices_t type = AUDIO_DEVICE_NONE;
3624 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3625 type |= patch->sinks[i].ext.device.type;
3626 }
3627
3628#ifdef ADD_BATTERY_DATA
3629 // when changing the audio output device, call addBatteryData to notify
3630 // the change
3631 if (mOutDevice != type) {
3632 uint32_t params = 0;
3633 // check whether speaker is on
3634 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3635 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003636 }
3637
Eric Laurent054d9d32015-04-24 08:48:48 -07003638 audio_devices_t deviceWithoutSpeaker
3639 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3640 // check if any other device (except speaker) is on
3641 if (type & deviceWithoutSpeaker) {
3642 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3643 }
3644
3645 if (params != 0) {
3646 addBatteryData(params);
3647 }
3648 }
3649#endif
3650
3651 for (size_t i = 0; i < mEffectChains.size(); i++) {
3652 mEffectChains[i]->setDevice_l(type);
3653 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003654
3655 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3656 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3657 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003658 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003659 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003660
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003661 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003662 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3663 status = hwDevice->createAudioPatch(patch->num_sources,
3664 patch->sources,
3665 patch->num_sinks,
3666 patch->sinks,
3667 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003668 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003669 char *address;
3670 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3671 //FIXME: we only support address on first sink with HAL version < 3.0
3672 address = audio_device_address_to_parameter(
3673 patch->sinks[0].ext.device.type,
3674 patch->sinks[0].ext.device.address);
3675 } else {
3676 address = (char *)calloc(1, 1);
3677 }
3678 AudioParameter param = AudioParameter(String8(address));
3679 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003680 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003681 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003682 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003683 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003684 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003685 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003686 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3687 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003688 return status;
3689}
3690
Eric Laurent054d9d32015-04-24 08:48:48 -07003691status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3692{
Andy Hungf60abce2016-08-26 11:37:54 -07003693 status_t status;
3694 if (property_get_bool("af.patch_park", false /* default_value */)) {
3695 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3696 // or if HAL does not properly lock against access.
3697 AutoPark<FastMixer> park(mFastMixer);
3698 status = PlaybackThread::releaseAudioPatch_l(handle);
3699 } else {
3700 status = PlaybackThread::releaseAudioPatch_l(handle);
3701 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003702 return status;
3703}
3704
Eric Laurent1c333e22014-05-20 10:48:17 -07003705status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3706{
3707 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003708
3709 mOutDevice = AUDIO_DEVICE_NONE;
3710
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003711 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003712 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3713 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003714 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003715 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003716 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003717 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003718 }
3719 return status;
3720}
3721
Eric Laurent83b88082014-06-20 18:31:16 -07003722void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3723{
3724 Mutex::Autolock _l(mLock);
3725 mTracks.add(track);
3726}
3727
3728void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3729{
3730 Mutex::Autolock _l(mLock);
3731 destroyTrack_l(track);
3732}
3733
3734void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3735{
3736 ThreadBase::getAudioPortConfig(config);
3737 config->role = AUDIO_PORT_ROLE_SOURCE;
3738 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3739 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3740}
3741
Eric Laurent81784c32012-11-19 14:55:58 -08003742// ----------------------------------------------------------------------------
3743
3744AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003745 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3746 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003747 // mAudioMixer below
3748 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003749 mFastMixerFutex(0),
3750 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003751 // mOutputSink below
3752 // mPipeSink below
3753 // mNormalSink below
3754{
3755 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003756 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003757 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003758 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3759 mNormalFrameCount);
3760 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3761
Andy Hungfbfc3952015-01-15 13:33:51 -08003762 if (type == DUPLICATING) {
3763 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3764 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3765 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3766 return;
3767 }
Eric Laurent81784c32012-11-19 14:55:58 -08003768 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003769 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003770 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003771 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003772#if !LOG_NDEBUG
3773 ssize_t index =
3774#else
3775 (void)
3776#endif
3777 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003778 ALOG_ASSERT(index == 0);
3779
3780 // initialize fast mixer depending on configuration
3781 bool initFastMixer;
3782 switch (kUseFastMixer) {
3783 case FastMixer_Never:
3784 initFastMixer = false;
3785 break;
3786 case FastMixer_Always:
3787 initFastMixer = true;
3788 break;
3789 case FastMixer_Static:
3790 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003791 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3792 // where the period is less than an experimentally determined threshold that can be
3793 // scheduled reliably with CFS. However, the BT A2DP HAL is
3794 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3795 initFastMixer = mFrameCount < mNormalFrameCount
3796 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003797 break;
3798 }
Andy Hungfda69402017-02-15 14:33:12 -08003799 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3800 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3801 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003802 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003803 audio_format_t fastMixerFormat;
3804 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3805 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3806 } else {
3807 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3808 }
3809 if (mFormat != fastMixerFormat) {
3810 // change our Sink format to accept our intermediate precision
3811 mFormat = fastMixerFormat;
3812 free(mSinkBuffer);
3813 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3814 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3815 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3816 }
Eric Laurent81784c32012-11-19 14:55:58 -08003817
3818 // create a MonoPipe to connect our submix to FastMixer
3819 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003820#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003821 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003822#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003823 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003824 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003825 format.mFormat = fastMixerFormat;
3826 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3827
Eric Laurent81784c32012-11-19 14:55:58 -08003828 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3829 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3830 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3831 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3832 const NBAIO_Format offers[1] = {format};
3833 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003834#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003835 ssize_t index =
3836#else
3837 (void)
3838#endif
3839 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003840 ALOG_ASSERT(index == 0);
3841 monoPipe->setAvgFrames((mScreenState & 1) ?
3842 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3843 mPipeSink = monoPipe;
3844
Glenn Kasten46909e72013-02-26 09:20:22 -08003845#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003846 if (mTeeSinkOutputEnabled) {
3847 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003848 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3849 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003850 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003851 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003852 ALOG_ASSERT(index == 0);
3853 mTeeSink = teeSink;
3854 PipeReader *teeSource = new PipeReader(*teeSink);
3855 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003856 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003857 ALOG_ASSERT(index == 0);
3858 mTeeSource = teeSource;
3859 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003860#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003861
3862 // create fast mixer and configure it initially with just one fast track for our submix
3863 mFastMixer = new FastMixer();
3864 FastMixerStateQueue *sq = mFastMixer->sq();
3865#ifdef STATE_QUEUE_DUMP
3866 sq->setObserverDump(&mStateQueueObserverDump);
3867 sq->setMutatorDump(&mStateQueueMutatorDump);
3868#endif
3869 FastMixerState *state = sq->begin();
3870 FastTrack *fastTrack = &state->mFastTracks[0];
3871 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3872 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3873 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003874 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3875 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003876 fastTrack->mGeneration++;
3877 state->mFastTracksGen++;
3878 state->mTrackMask = 1;
3879 // fast mixer will use the HAL output sink
3880 state->mOutputSink = mOutputSink.get();
3881 state->mOutputSinkGen++;
3882 state->mFrameCount = mFrameCount;
3883 state->mCommand = FastMixerState::COLD_IDLE;
3884 // already done in constructor initialization list
3885 //mFastMixerFutex = 0;
3886 state->mColdFutexAddr = &mFastMixerFutex;
3887 state->mColdGen++;
3888 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003889#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003890 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003891#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003892 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3893 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003894 sq->end();
3895 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3896
3897 // start the fast mixer
3898 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3899 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003900 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003901 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003902
3903#ifdef AUDIO_WATCHDOG
3904 // create and start the watchdog
3905 mAudioWatchdog = new AudioWatchdog();
3906 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3907 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3908 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003909 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003910#endif
3911
Eric Laurent81784c32012-11-19 14:55:58 -08003912 }
3913
3914 switch (kUseFastMixer) {
3915 case FastMixer_Never:
3916 case FastMixer_Dynamic:
3917 mNormalSink = mOutputSink;
3918 break;
3919 case FastMixer_Always:
3920 mNormalSink = mPipeSink;
3921 break;
3922 case FastMixer_Static:
3923 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3924 break;
3925 }
3926}
3927
3928AudioFlinger::MixerThread::~MixerThread()
3929{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003930 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003931 FastMixerStateQueue *sq = mFastMixer->sq();
3932 FastMixerState *state = sq->begin();
3933 if (state->mCommand == FastMixerState::COLD_IDLE) {
3934 int32_t old = android_atomic_inc(&mFastMixerFutex);
3935 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003936 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003937 }
3938 }
3939 state->mCommand = FastMixerState::EXIT;
3940 sq->end();
3941 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3942 mFastMixer->join();
3943 // Though the fast mixer thread has exited, it's state queue is still valid.
3944 // We'll use that extract the final state which contains one remaining fast track
3945 // corresponding to our sub-mix.
3946 state = sq->begin();
3947 ALOG_ASSERT(state->mTrackMask == 1);
3948 FastTrack *fastTrack = &state->mFastTracks[0];
3949 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3950 delete fastTrack->mBufferProvider;
3951 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003952 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003953#ifdef AUDIO_WATCHDOG
3954 if (mAudioWatchdog != 0) {
3955 mAudioWatchdog->requestExit();
3956 mAudioWatchdog->requestExitAndWait();
3957 mAudioWatchdog.clear();
3958 }
3959#endif
3960 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003961 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003962 delete mAudioMixer;
3963}
3964
3965
3966uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3967{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003968 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003969 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3970 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3971 }
3972 return latency;
3973}
3974
3975
3976void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3977{
3978 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3979}
3980
Eric Laurentbfb1b832013-01-07 09:53:42 -08003981ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003982{
3983 // FIXME we should only do one push per cycle; confirm this is true
3984 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003985 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003986 FastMixerStateQueue *sq = mFastMixer->sq();
3987 FastMixerState *state = sq->begin();
3988 if (state->mCommand != FastMixerState::MIX_WRITE &&
3989 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3990 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003991
3992 // FIXME workaround for first HAL write being CPU bound on some devices
3993 ATRACE_BEGIN("write");
3994 mOutput->write((char *)mSinkBuffer, 0);
3995 ATRACE_END();
3996
Eric Laurent81784c32012-11-19 14:55:58 -08003997 int32_t old = android_atomic_inc(&mFastMixerFutex);
3998 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003999 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004000 }
4001#ifdef AUDIO_WATCHDOG
4002 if (mAudioWatchdog != 0) {
4003 mAudioWatchdog->resume();
4004 }
4005#endif
4006 }
4007 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004008#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004009 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004010 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004011#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004012 sq->end();
4013 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4014 if (kUseFastMixer == FastMixer_Dynamic) {
4015 mNormalSink = mPipeSink;
4016 }
4017 } else {
4018 sq->end(false /*didModify*/);
4019 }
4020 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004021 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004022}
4023
4024void AudioFlinger::MixerThread::threadLoop_standby()
4025{
4026 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004027 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004028 FastMixerStateQueue *sq = mFastMixer->sq();
4029 FastMixerState *state = sq->begin();
4030 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004031 // Report any frames trapped in the Monopipe
4032 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4033 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4034 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4035 "monoPipeWritten:%lld monoPipeLeft:%lld",
4036 (long long)mFramesWritten, (long long)mSuspendedFrames,
4037 (long long)mPipeSink->framesWritten(), pipeFrames);
4038 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4039
Eric Laurent81784c32012-11-19 14:55:58 -08004040 state->mCommand = FastMixerState::COLD_IDLE;
4041 state->mColdFutexAddr = &mFastMixerFutex;
4042 state->mColdGen++;
4043 mFastMixerFutex = 0;
4044 sq->end();
4045 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4046 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4047 if (kUseFastMixer == FastMixer_Dynamic) {
4048 mNormalSink = mOutputSink;
4049 }
4050#ifdef AUDIO_WATCHDOG
4051 if (mAudioWatchdog != 0) {
4052 mAudioWatchdog->pause();
4053 }
4054#endif
4055 } else {
4056 sq->end(false /*didModify*/);
4057 }
4058 }
4059 PlaybackThread::threadLoop_standby();
4060}
4061
Eric Laurentbfb1b832013-01-07 09:53:42 -08004062bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4063{
4064 return false;
4065}
4066
4067bool AudioFlinger::PlaybackThread::shouldStandby_l()
4068{
4069 return !mStandby;
4070}
4071
4072bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4073{
4074 Mutex::Autolock _l(mLock);
4075 return waitingAsyncCallback_l();
4076}
4077
Eric Laurent81784c32012-11-19 14:55:58 -08004078// shared by MIXER and DIRECT, overridden by DUPLICATING
4079void AudioFlinger::PlaybackThread::threadLoop_standby()
4080{
4081 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004082 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004083 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004084 // discard any pending drain or write ack by incrementing sequence
4085 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4086 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004087 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004088 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4089 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004090 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004091 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004092}
4093
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004094void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4095{
4096 ALOGV("signal playback thread");
4097 broadcast_l();
4098}
4099
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004100void AudioFlinger::PlaybackThread::onAsyncError()
4101{
4102 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4103 invalidateTracks((audio_stream_type_t)i);
4104 }
4105}
4106
Eric Laurent81784c32012-11-19 14:55:58 -08004107void AudioFlinger::MixerThread::threadLoop_mix()
4108{
Eric Laurent81784c32012-11-19 14:55:58 -08004109 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004110 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004111 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004112 // increase sleep time progressively when application underrun condition clears.
4113 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4114 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4115 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004116 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004117 sleepTimeShift--;
4118 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004119 mSleepTimeUs = 0;
4120 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004121 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004122
Eric Laurent81784c32012-11-19 14:55:58 -08004123}
4124
4125void AudioFlinger::MixerThread::threadLoop_sleepTime()
4126{
4127 // If no tracks are ready, sleep once for the duration of an output
4128 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004129 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004130 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004131 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4132 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4133 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004134 }
4135 // reduce sleep time in case of consecutive application underruns to avoid
4136 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4137 // duration we would end up writing less data than needed by the audio HAL if
4138 // the condition persists.
4139 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4140 sleepTimeShift++;
4141 }
4142 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004143 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004144 }
4145 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004146 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4147 // before effects processing or output.
4148 if (mMixerBufferValid) {
4149 memset(mMixerBuffer, 0, mMixerBufferSize);
4150 } else {
4151 memset(mSinkBuffer, 0, mSinkBufferSize);
4152 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004153 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004154 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4155 "anticipated start");
4156 }
4157 // TODO add standby time extension fct of effect tail
4158}
4159
4160// prepareTracks_l() must be called with ThreadBase::mLock held
4161AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4162 Vector< sp<Track> > *tracksToRemove)
4163{
Andy Hung1bc088a2018-02-09 15:57:31 -08004164 // clean up deleted track names in AudioMixer before allocating new tracks
4165 (void)mTracks.processDeletedTrackNames([this](int name) {
4166 // for each name, destroy it in the AudioMixer
4167 if (mAudioMixer->exists(name)) {
4168 mAudioMixer->destroy(name);
4169 }
4170 });
4171 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004172
4173 mixer_state mixerStatus = MIXER_IDLE;
4174 // find out which tracks need to be processed
4175 size_t count = mActiveTracks.size();
4176 size_t mixedTracks = 0;
4177 size_t tracksWithEffect = 0;
4178 // counts only _active_ fast tracks
4179 size_t fastTracks = 0;
4180 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4181
4182 float masterVolume = mMasterVolume;
4183 bool masterMute = mMasterMute;
4184
4185 if (masterMute) {
4186 masterVolume = 0;
4187 }
4188 // Delegate master volume control to effect in output mix effect chain if needed
4189 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4190 if (chain != 0) {
4191 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4192 chain->setVolume_l(&v, &v);
4193 masterVolume = (float)((v + (1 << 23)) >> 24);
4194 chain.clear();
4195 }
4196
4197 // prepare a new state to push
4198 FastMixerStateQueue *sq = NULL;
4199 FastMixerState *state = NULL;
4200 bool didModify = false;
4201 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004202 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004203 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004204 sq = mFastMixer->sq();
4205 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004206 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004207 }
4208
Andy Hung69aed5f2014-02-25 17:24:40 -08004209 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004210 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004211
Eric Laurent81784c32012-11-19 14:55:58 -08004212 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004213 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004214
4215 // this const just means the local variable doesn't change
4216 Track* const track = t.get();
4217
4218 // process fast tracks
4219 if (track->isFastTrack()) {
4220
4221 // It's theoretically possible (though unlikely) for a fast track to be created
4222 // and then removed within the same normal mix cycle. This is not a problem, as
4223 // the track never becomes active so it's fast mixer slot is never touched.
4224 // The converse, of removing an (active) track and then creating a new track
4225 // at the identical fast mixer slot within the same normal mix cycle,
4226 // is impossible because the slot isn't marked available until the end of each cycle.
4227 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004228 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004229 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4230 FastTrack *fastTrack = &state->mFastTracks[j];
4231
4232 // Determine whether the track is currently in underrun condition,
4233 // and whether it had a recent underrun.
4234 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4235 FastTrackUnderruns underruns = ftDump->mUnderruns;
4236 uint32_t recentFull = (underruns.mBitFields.mFull -
4237 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4238 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4239 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4240 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4241 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4242 uint32_t recentUnderruns = recentPartial + recentEmpty;
4243 track->mObservedUnderruns = underruns;
4244 // don't count underruns that occur while stopping or pausing
4245 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004246 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4247 recentUnderruns > 0) {
4248 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4249 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004250 } else {
4251 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004252 }
4253
4254 // This is similar to the state machine for normal tracks,
4255 // with a few modifications for fast tracks.
4256 bool isActive = true;
4257 switch (track->mState) {
4258 case TrackBase::STOPPING_1:
4259 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004260 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004261 track->mState = TrackBase::STOPPING_2;
4262 }
4263 break;
4264 case TrackBase::PAUSING:
4265 // ramp down is not yet implemented
4266 track->setPaused();
4267 break;
4268 case TrackBase::RESUMING:
4269 // ramp up is not yet implemented
4270 track->mState = TrackBase::ACTIVE;
4271 break;
4272 case TrackBase::ACTIVE:
4273 if (recentFull > 0 || recentPartial > 0) {
4274 // track has provided at least some frames recently: reset retry count
4275 track->mRetryCount = kMaxTrackRetries;
4276 }
4277 if (recentUnderruns == 0) {
4278 // no recent underruns: stay active
4279 break;
4280 }
4281 // there has recently been an underrun of some kind
4282 if (track->sharedBuffer() == 0) {
4283 // were any of the recent underruns "empty" (no frames available)?
4284 if (recentEmpty == 0) {
4285 // no, then ignore the partial underruns as they are allowed indefinitely
4286 break;
4287 }
4288 // there has recently been an "empty" underrun: decrement the retry counter
4289 if (--(track->mRetryCount) > 0) {
4290 break;
4291 }
4292 // indicate to client process that the track was disabled because of underrun;
4293 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004294 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004295 // remove from active list, but state remains ACTIVE [confusing but true]
4296 isActive = false;
4297 break;
4298 }
4299 // fall through
4300 case TrackBase::STOPPING_2:
4301 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004302 case TrackBase::STOPPED:
4303 case TrackBase::FLUSHED: // flush() while active
4304 // Check for presentation complete if track is inactive
4305 // We have consumed all the buffers of this track.
4306 // This would be incomplete if we auto-paused on underrun
4307 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004308 uint32_t latency = 0;
4309 status_t result = mOutput->stream->getLatency(&latency);
4310 ALOGE_IF(result != OK,
4311 "Error when retrieving output stream latency: %d", result);
4312 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004313 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004314 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4315 // track stays in active list until presentation is complete
4316 break;
4317 }
4318 }
4319 if (track->isStopping_2()) {
4320 track->mState = TrackBase::STOPPED;
4321 }
4322 if (track->isStopped()) {
4323 // Can't reset directly, as fast mixer is still polling this track
4324 // track->reset();
4325 // So instead mark this track as needing to be reset after push with ack
4326 resetMask |= 1 << i;
4327 }
4328 isActive = false;
4329 break;
4330 case TrackBase::IDLE:
4331 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004332 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004333 }
4334
4335 if (isActive) {
4336 // was it previously inactive?
4337 if (!(state->mTrackMask & (1 << j))) {
4338 ExtendedAudioBufferProvider *eabp = track;
4339 VolumeProvider *vp = track;
4340 fastTrack->mBufferProvider = eabp;
4341 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004342 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004343 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004344 fastTrack->mGeneration++;
4345 state->mTrackMask |= 1 << j;
4346 didModify = true;
4347 // no acknowledgement required for newly active tracks
4348 }
4349 // cache the combined master volume and stream type volume for fast mixer; this
4350 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004351 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004352 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004353 track->mCachedVolume = masterVolume
4354 * mStreamTypes[track->streamType()].volume
4355 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004356 ++fastTracks;
4357 } else {
4358 // was it previously active?
4359 if (state->mTrackMask & (1 << j)) {
4360 fastTrack->mBufferProvider = NULL;
4361 fastTrack->mGeneration++;
4362 state->mTrackMask &= ~(1 << j);
4363 didModify = true;
4364 // If any fast tracks were removed, we must wait for acknowledgement
4365 // because we're about to decrement the last sp<> on those tracks.
4366 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4367 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004368 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4369 // AudioTrack may start (which may not be with a start() but with a write()
4370 // after underrun) and immediately paused or released. In that case the
4371 // FastTrack state hasn't had time to update.
4372 // TODO Remove the ALOGW when this theory is confirmed.
4373 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004374 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4375 j, track->mState, state->mTrackMask, recentUnderruns,
4376 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004377 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004378 }
4379 tracksToRemove->add(track);
4380 // Avoids a misleading display in dumpsys
4381 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4382 }
4383 continue;
4384 }
4385
4386 { // local variable scope to avoid goto warning
4387
4388 audio_track_cblk_t* cblk = track->cblk();
4389
4390 // The first time a track is added we wait
4391 // for all its buffers to be filled before processing it
4392 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004393
4394 // if an active track doesn't exist in the AudioMixer, create it.
4395 if (!mAudioMixer->exists(name)) {
4396 status_t status = mAudioMixer->create(
4397 name,
4398 track->mChannelMask,
4399 track->mFormat,
4400 track->mSessionId);
4401 if (status != OK) {
4402 ALOGW("%s: cannot create track name"
4403 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4404 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4405 tracksToRemove->add(track);
4406 track->invalidate(); // consider it dead.
4407 continue;
4408 }
4409 }
4410
Eric Laurent81784c32012-11-19 14:55:58 -08004411 // make sure that we have enough frames to mix one full buffer.
4412 // enforce this condition only once to enable draining the buffer in case the client
4413 // app does not call stop() and relies on underrun to stop:
4414 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4415 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004416 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004417 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004418 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004419
4420 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004421 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004422 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4423 // add frames already consumed but not yet released by the resampler
4424 // because mAudioTrackServerProxy->framesReady() will include these frames
4425 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4426
Eric Laurent81784c32012-11-19 14:55:58 -08004427 uint32_t minFrames = 1;
4428 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4429 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004430 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004431 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004432
4433 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004434 if (ATRACE_ENABLED()) {
4435 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004436 std::string traceName("nRdy");
4437 traceName += std::to_string(track->name());
4438 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004439 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004440 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004441 !track->isPaused() && !track->isTerminated())
4442 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004443 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004444
4445 mixedTracks++;
4446
Andy Hung69aed5f2014-02-25 17:24:40 -08004447 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4448 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004449 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004450 if (track->mainBuffer() != mSinkBuffer &&
4451 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004452 if (mEffectBufferEnabled) {
4453 mEffectBufferValid = true; // Later can set directly.
4454 }
Eric Laurent81784c32012-11-19 14:55:58 -08004455 chain = getEffectChain_l(track->sessionId());
4456 // Delegate volume control to effect in track effect chain if needed
4457 if (chain != 0) {
4458 tracksWithEffect++;
4459 } else {
4460 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4461 "session %d",
4462 name, track->sessionId());
4463 }
4464 }
4465
4466
4467 int param = AudioMixer::VOLUME;
4468 if (track->mFillingUpStatus == Track::FS_FILLED) {
4469 // no ramp for the first volume setting
4470 track->mFillingUpStatus = Track::FS_ACTIVE;
4471 if (track->mState == TrackBase::RESUMING) {
4472 track->mState = TrackBase::ACTIVE;
4473 param = AudioMixer::RAMP_VOLUME;
4474 }
4475 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004476 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004477 // FIXME should not make a decision based on mServer
4478 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004479 // If the track is stopped before the first frame was mixed,
4480 // do not apply ramp
4481 param = AudioMixer::RAMP_VOLUME;
4482 }
4483
4484 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004485 uint32_t vl, vr; // in U8.24 integer format
4486 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004487 // read original volumes with volume control
4488 float typeVolume = mStreamTypes[track->streamType()].volume;
4489 float v = masterVolume * typeVolume;
4490
Glenn Kastene4756fe2012-11-29 13:38:14 -08004491 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004492 vl = vr = 0;
4493 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004494 if (track->isPausing()) {
4495 track->setPaused();
4496 }
4497 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004498 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004499 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004500 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4501 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004502 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004503 if (vlf > GAIN_FLOAT_UNITY) {
4504 ALOGV("Track left volume out of range: %.3g", vlf);
4505 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004506 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004507 if (vrf > GAIN_FLOAT_UNITY) {
4508 ALOGV("Track right volume out of range: %.3g", vrf);
4509 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004510 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004511 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004512 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004513 // now apply the master volume and stream type volume and shaper volume
4514 vlf *= v * vh;
4515 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004516 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004517 // then derive vl and vr as U8.24 versions for the effect chain
4518 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4519 vl = (uint32_t) (scaleto8_24 * vlf);
4520 vr = (uint32_t) (scaleto8_24 * vrf);
4521 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004522 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004523 // send level comes from shared memory and so may be corrupt
4524 if (sendLevel > MAX_GAIN_INT) {
4525 ALOGV("Track send level out of range: %04X", sendLevel);
4526 sendLevel = MAX_GAIN_INT;
4527 }
Andy Hung6be49402014-05-30 10:42:03 -07004528 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4529 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004530 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004531
Eric Laurent81784c32012-11-19 14:55:58 -08004532 // Delegate volume control to effect in track effect chain if needed
4533 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4534 // Do not ramp volume if volume is controlled by effect
4535 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004536 // Update remaining floating point volume levels
4537 vlf = (float)vl / (1 << 24);
4538 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004539 track->mHasVolumeController = true;
4540 } else {
4541 // force no volume ramp when volume controller was just disabled or removed
4542 // from effect chain to avoid volume spike
4543 if (track->mHasVolumeController) {
4544 param = AudioMixer::VOLUME;
4545 }
4546 track->mHasVolumeController = false;
4547 }
4548
Eric Laurent7c29ec92017-09-20 17:54:22 -07004549 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4550 // still applied by the mixer.
4551 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4552 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4553 if (v != mLeftVolFloat) {
4554 status_t result = mOutput->stream->setVolume(v, v);
4555 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4556 if (result == OK) {
4557 mLeftVolFloat = v;
4558 }
4559 }
4560 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4561 // remove stream volume contribution from software volume.
4562 if (v != 0.0f && mLeftVolFloat == v) {
4563 vlf = min(1.0f, vlf / v);
4564 vrf = min(1.0f, vrf / v);
4565 vaf = min(1.0f, vaf / v);
4566 }
4567 }
Eric Laurent81784c32012-11-19 14:55:58 -08004568 // XXX: these things DON'T need to be done each time
4569 mAudioMixer->setBufferProvider(name, track);
4570 mAudioMixer->enable(name);
4571
Andy Hung6be49402014-05-30 10:42:03 -07004572 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4573 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4574 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004575 mAudioMixer->setParameter(
4576 name,
4577 AudioMixer::TRACK,
4578 AudioMixer::FORMAT, (void *)track->format());
4579 mAudioMixer->setParameter(
4580 name,
4581 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004582 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004583 mAudioMixer->setParameter(
4584 name,
4585 AudioMixer::TRACK,
4586 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004587 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004588 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004589 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004590 if (reqSampleRate == 0) {
4591 reqSampleRate = mSampleRate;
4592 } else if (reqSampleRate > maxSampleRate) {
4593 reqSampleRate = maxSampleRate;
4594 }
Eric Laurent81784c32012-11-19 14:55:58 -08004595 mAudioMixer->setParameter(
4596 name,
4597 AudioMixer::RESAMPLE,
4598 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004599 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004600
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004601 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004602 mAudioMixer->setParameter(
4603 name,
4604 AudioMixer::TIMESTRETCH,
4605 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004606 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004607
Andy Hung69aed5f2014-02-25 17:24:40 -08004608 /*
4609 * Select the appropriate output buffer for the track.
4610 *
Andy Hung98ef9782014-03-04 14:46:50 -08004611 * Tracks with effects go into their own effects chain buffer
4612 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004613 *
4614 * Other tracks can use mMixerBuffer for higher precision
4615 * channel accumulation. If this buffer is enabled
4616 * (mMixerBufferEnabled true), then selected tracks will accumulate
4617 * into it.
4618 *
4619 */
4620 if (mMixerBufferEnabled
4621 && (track->mainBuffer() == mSinkBuffer
4622 || track->mainBuffer() == mMixerBuffer)) {
4623 mAudioMixer->setParameter(
4624 name,
4625 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004626 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004627 mAudioMixer->setParameter(
4628 name,
4629 AudioMixer::TRACK,
4630 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4631 // TODO: override track->mainBuffer()?
4632 mMixerBufferValid = true;
4633 } else {
4634 mAudioMixer->setParameter(
4635 name,
4636 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004637 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004638 mAudioMixer->setParameter(
4639 name,
4640 AudioMixer::TRACK,
4641 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4642 }
Eric Laurent81784c32012-11-19 14:55:58 -08004643 mAudioMixer->setParameter(
4644 name,
4645 AudioMixer::TRACK,
4646 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4647
4648 // reset retry count
4649 track->mRetryCount = kMaxTrackRetries;
4650
4651 // If one track is ready, set the mixer ready if:
4652 // - the mixer was not ready during previous round OR
4653 // - no other track is not ready
4654 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4655 mixerStatus != MIXER_TRACKS_ENABLED) {
4656 mixerStatus = MIXER_TRACKS_READY;
4657 }
4658 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004659 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004660 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4661 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004662 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004663 } else {
4664 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004665 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004666
Eric Laurent81784c32012-11-19 14:55:58 -08004667 // clear effect chain input buffer if an active track underruns to avoid sending
4668 // previous audio buffer again to effects
4669 chain = getEffectChain_l(track->sessionId());
4670 if (chain != 0) {
4671 chain->clearInputBuffer();
4672 }
4673
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004674 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004675 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4676 track->isStopped() || track->isPaused()) {
4677 // We have consumed all the buffers of this track.
4678 // Remove it from the list of active tracks.
4679 // TODO: use actual buffer filling status instead of latency when available from
4680 // audio HAL
4681 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004682 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004683 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4684 if (track->isStopped()) {
4685 track->reset();
4686 }
4687 tracksToRemove->add(track);
4688 }
4689 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004690 // No buffers for this track. Give it a few chances to
4691 // fill a buffer, then remove it from active list.
4692 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004693 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004694 tracksToRemove->add(track);
4695 // indicate to client process that the track was disabled because of underrun;
4696 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004697 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004698 // If one track is not ready, mark the mixer also not ready if:
4699 // - the mixer was ready during previous round OR
4700 // - no other track is ready
4701 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4702 mixerStatus != MIXER_TRACKS_READY) {
4703 mixerStatus = MIXER_TRACKS_ENABLED;
4704 }
4705 }
4706 mAudioMixer->disable(name);
4707 }
4708
4709 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004710
4711 }
4712
4713 // Push the new FastMixer state if necessary
4714 bool pauseAudioWatchdog = false;
4715 if (didModify) {
4716 state->mFastTracksGen++;
4717 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4718 if (kUseFastMixer == FastMixer_Dynamic &&
4719 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4720 state->mCommand = FastMixerState::COLD_IDLE;
4721 state->mColdFutexAddr = &mFastMixerFutex;
4722 state->mColdGen++;
4723 mFastMixerFutex = 0;
4724 if (kUseFastMixer == FastMixer_Dynamic) {
4725 mNormalSink = mOutputSink;
4726 }
4727 // If we go into cold idle, need to wait for acknowledgement
4728 // so that fast mixer stops doing I/O.
4729 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4730 pauseAudioWatchdog = true;
4731 }
Eric Laurent81784c32012-11-19 14:55:58 -08004732 }
4733 if (sq != NULL) {
4734 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004735 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4736 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4737 // when bringing the output sink into standby.)
4738 //
4739 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4740 //
4741 // This occurs with BT suspend when we idle the FastMixer with
4742 // active tracks, which may be added or removed.
4743 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004744 }
4745#ifdef AUDIO_WATCHDOG
4746 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4747 mAudioWatchdog->pause();
4748 }
4749#endif
4750
4751 // Now perform the deferred reset on fast tracks that have stopped
4752 while (resetMask != 0) {
4753 size_t i = __builtin_ctz(resetMask);
4754 ALOG_ASSERT(i < count);
4755 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004756 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004757 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4758 track->reset();
4759 }
4760
4761 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004762 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004763
Eric Laurent97d547d2014-09-02 14:45:53 -07004764 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4765 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004766 }
4767
4768 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004769 // as long as there are effects we should clear the effects buffer, to avoid
4770 // passing a non-clean buffer to the effect chain
4771 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004772 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004773 // sink or mix buffer must be cleared if all tracks are connected to an
4774 // effect chain as in this case the mixer will not write to the sink or mix buffer
4775 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004776 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4777 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004778 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004779 if (mMixerBufferValid) {
4780 memset(mMixerBuffer, 0, mMixerBufferSize);
4781 // TODO: In testing, mSinkBuffer below need not be cleared because
4782 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4783 // after mixing.
4784 //
4785 // To enforce this guarantee:
4786 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4787 // (mixedTracks == 0 && fastTracks > 0))
4788 // must imply MIXER_TRACKS_READY.
4789 // Later, we may clear buffers regardless, and skip much of this logic.
4790 }
Andy Hung98ef9782014-03-04 14:46:50 -08004791 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004792 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004793 }
4794
4795 // if any fast tracks, then status is ready
4796 mMixerStatusIgnoringFastTracks = mixerStatus;
4797 if (fastTracks > 0) {
4798 mixerStatus = MIXER_TRACKS_READY;
4799 }
4800 return mixerStatus;
4801}
4802
Eric Laurentad7dd962016-09-22 12:38:37 -07004803// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004804uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004805{
4806 uint32_t trackCount = 0;
4807 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004808 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004809 trackCount++;
4810 }
4811 }
4812 return trackCount;
4813}
4814
Andy Hung1bc088a2018-02-09 15:57:31 -08004815// isTrackAllowed_l() must be called with ThreadBase::mLock held
4816bool AudioFlinger::MixerThread::isTrackAllowed_l(
4817 audio_channel_mask_t channelMask, audio_format_t format,
4818 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004819{
Andy Hung1bc088a2018-02-09 15:57:31 -08004820 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4821 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004822 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004823 // Check validity as we don't call AudioMixer::create() here.
4824 if (!AudioMixer::isValidFormat(format)) {
4825 ALOGW("%s: invalid format: %#x", __func__, format);
4826 return false;
4827 }
4828 if (!AudioMixer::isValidChannelMask(channelMask)) {
4829 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4830 return false;
4831 }
4832 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004833}
4834
Eric Laurent10351942014-05-08 18:49:52 -07004835// checkForNewParameter_l() must be called with ThreadBase::mLock held
4836bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4837 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004838{
Eric Laurent81784c32012-11-19 14:55:58 -08004839 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004840 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004841
Eric Laurent10351942014-05-08 18:49:52 -07004842 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004843
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004844 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004845
Eric Laurent10351942014-05-08 18:49:52 -07004846 AudioParameter param = AudioParameter(keyValuePair);
4847 int value;
4848 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4849 reconfig = true;
4850 }
4851 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004852 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004853 status = BAD_VALUE;
4854 } else {
4855 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004856 reconfig = true;
4857 }
Eric Laurent10351942014-05-08 18:49:52 -07004858 }
4859 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004860 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004861 status = BAD_VALUE;
4862 } else {
4863 // no need to save value, since it's constant
4864 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004865 }
Eric Laurent10351942014-05-08 18:49:52 -07004866 }
4867 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4868 // do not accept frame count changes if tracks are open as the track buffer
4869 // size depends on frame count and correct behavior would not be guaranteed
4870 // if frame count is changed after track creation
4871 if (!mTracks.isEmpty()) {
4872 status = INVALID_OPERATION;
4873 } else {
4874 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004875 }
Eric Laurent10351942014-05-08 18:49:52 -07004876 }
4877 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004878#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004879 // when changing the audio output device, call addBatteryData to notify
4880 // the change
4881 if (mOutDevice != value) {
4882 uint32_t params = 0;
4883 // check whether speaker is on
4884 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4885 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004886 }
Eric Laurent10351942014-05-08 18:49:52 -07004887
4888 audio_devices_t deviceWithoutSpeaker
4889 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4890 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004891 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004892 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4893 }
4894
4895 if (params != 0) {
4896 addBatteryData(params);
4897 }
4898 }
Eric Laurent81784c32012-11-19 14:55:58 -08004899#endif
4900
Eric Laurent10351942014-05-08 18:49:52 -07004901 // forward device change to effects that have requested to be
4902 // aware of attached audio device.
4903 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004904 a2dpDeviceChanged =
4905 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004906 mOutDevice = value;
4907 for (size_t i = 0; i < mEffectChains.size(); i++) {
4908 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004909 }
4910 }
Eric Laurent10351942014-05-08 18:49:52 -07004911 }
Eric Laurent81784c32012-11-19 14:55:58 -08004912
Eric Laurent10351942014-05-08 18:49:52 -07004913 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004914 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004915 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004916 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004917 mStandby = true;
4918 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004919 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004920 }
Eric Laurent10351942014-05-08 18:49:52 -07004921 if (status == NO_ERROR && reconfig) {
4922 readOutputParameters_l();
4923 delete mAudioMixer;
4924 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08004925 for (const auto &track : mTracks) {
4926 const int name = track->name();
4927 status_t status = mAudioMixer->create(
4928 name,
4929 track->mChannelMask,
4930 track->mFormat,
4931 track->mSessionId);
4932 ALOGW_IF(status != NO_ERROR,
4933 "%s: cannot create track name"
4934 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4935 __func__,
4936 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004937 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004938 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004939 }
Eric Laurent81784c32012-11-19 14:55:58 -08004940 }
4941
Eric Laurent42537be2016-01-08 17:16:42 -08004942 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004943}
4944
4945
4946void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4947{
Eric Laurent81784c32012-11-19 14:55:58 -08004948 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004949 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08004950 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08004951 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004952
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004953 if (hasFastMixer()) {
4954 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4955
4956 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4957 // while we are dumping it. It may be inconsistent, but it won't mutate!
4958 // This is a large object so we place it on the heap.
4959 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4960 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4961 copy->dump(fd);
4962 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004963
4964#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004965 // Similar for state queue
4966 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4967 observerCopy.dump(fd);
4968 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4969 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004970#endif
4971
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004972#ifdef AUDIO_WATCHDOG
4973 if (mAudioWatchdog != 0) {
4974 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4975 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4976 wdCopy.dump(fd);
4977 }
4978#endif
4979
4980 } else {
4981 dprintf(fd, " No FastMixer\n");
4982 }
4983
Glenn Kasten46909e72013-02-26 09:20:22 -08004984#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004985 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004986 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004987#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004988
Eric Laurent81784c32012-11-19 14:55:58 -08004989}
4990
4991uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4992{
4993 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4994}
4995
4996uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4997{
4998 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4999}
5000
5001void AudioFlinger::MixerThread::cacheParameters_l()
5002{
5003 PlaybackThread::cacheParameters_l();
5004
5005 // FIXME: Relaxed timing because of a certain device that can't meet latency
5006 // Should be reduced to 2x after the vendor fixes the driver issue
5007 // increase threshold again due to low power audio mode. The way this warning
5008 // threshold is calculated and its usefulness should be reconsidered anyway.
5009 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5010}
5011
5012// ----------------------------------------------------------------------------
5013
5014AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005015 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5016 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005017{
5018}
5019
Eric Laurentbfb1b832013-01-07 09:53:42 -08005020AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5021 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005022 ThreadBase::type_t type, bool systemReady)
5023 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005024 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005025{
5026}
5027
Eric Laurent81784c32012-11-19 14:55:58 -08005028AudioFlinger::DirectOutputThread::~DirectOutputThread()
5029{
5030}
5031
Eric Laurent5850c4c2016-11-10 13:04:31 -08005032void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005033{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005034 float left, right;
5035
5036 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5037 left = right = 0;
5038 } else {
5039 float typeVolume = mStreamTypes[track->streamType()].volume;
5040 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005041 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005042
Andy Hung10cbff12017-02-21 17:30:14 -08005043 // Get volumeshaper scaling
5044 std::pair<float /* volume */, bool /* active */>
5045 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005046 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005047 v *= vh.first;
5048 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005049
Glenn Kastenc56f3422014-03-21 17:53:17 -07005050 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5051 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5052 if (left > GAIN_FLOAT_UNITY) {
5053 left = GAIN_FLOAT_UNITY;
5054 }
5055 left *= v;
5056 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5057 if (right > GAIN_FLOAT_UNITY) {
5058 right = GAIN_FLOAT_UNITY;
5059 }
5060 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005061 }
5062
5063 if (lastTrack) {
5064 if (left != mLeftVolFloat || right != mRightVolFloat) {
5065 mLeftVolFloat = left;
5066 mRightVolFloat = right;
5067
5068 // Convert volumes from float to 8.24
5069 uint32_t vl = (uint32_t)(left * (1 << 24));
5070 uint32_t vr = (uint32_t)(right * (1 << 24));
5071
5072 // Delegate volume control to effect in track effect chain if needed
5073 // only one effect chain can be present on DirectOutputThread, so if
5074 // there is one, the track is connected to it
5075 if (!mEffectChains.isEmpty()) {
5076 mEffectChains[0]->setVolume_l(&vl, &vr);
5077 left = (float)vl / (1 << 24);
5078 right = (float)vr / (1 << 24);
5079 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005080 status_t result = mOutput->stream->setVolume(left, right);
5081 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005082 }
5083 }
5084}
5085
Phil Burk43b4dcc2015-06-09 16:53:44 -07005086void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5087{
5088 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005089 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005090
Eric Laurent0f0631e2015-07-06 18:01:25 -07005091 if (previousTrack != 0 && latestTrack != 0) {
5092 if (mType == DIRECT) {
5093 if (previousTrack.get() != latestTrack.get()) {
5094 mFlushPending = true;
5095 }
5096 } else /* mType == OFFLOAD */ {
5097 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5098 mFlushPending = true;
5099 }
5100 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005101 }
5102 PlaybackThread::onAddNewTrack_l();
5103}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005104
Eric Laurent81784c32012-11-19 14:55:58 -08005105AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5106 Vector< sp<Track> > *tracksToRemove
5107)
5108{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005109 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005110 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005111 bool doHwPause = false;
5112 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005113
5114 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005115 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005116 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005117 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005118 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005119 continue;
5120 }
5121
Eric Laurent5850c4c2016-11-10 13:04:31 -08005122 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005123#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005124 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005125#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005126 // Only consider last track started for volume and mixer state control.
5127 // In theory an older track could underrun and restart after the new one starts
5128 // but as we only care about the transition phase between two tracks on a
5129 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005130 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005131 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005132
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005133 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005134 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005135 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005136 doHwPause = true;
5137 mHwPaused = true;
5138 }
5139 tracksToRemove->add(track);
5140 } else if (track->isFlushPending()) {
5141 track->flushAck();
5142 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005143 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005144 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005145 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005146 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005147 if (last) {
5148 mLeftVolFloat = mRightVolFloat = -1.0;
5149 if (mHwPaused) {
5150 doHwResume = true;
5151 mHwPaused = false;
5152 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005153 }
5154 }
5155
Eric Laurent81784c32012-11-19 14:55:58 -08005156 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005157 // for all its buffers to be filled before processing it.
5158 // Allow draining the buffer in case the client
5159 // app does not call stop() and relies on underrun to stop:
5160 // hence the test on (track->mRetryCount > 1).
5161 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005162 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005163 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005164 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005165 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005166 minFrames = mNormalFrameCount;
5167 } else {
5168 minFrames = 1;
5169 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005170
Eric Laurentab5cdba2014-06-09 17:22:27 -07005171 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5172 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005173 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005174 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005175
5176 if (track->mFillingUpStatus == Track::FS_FILLED) {
5177 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005178 if (last) {
5179 // make sure processVolume_l() will apply new volume even if 0
5180 mLeftVolFloat = mRightVolFloat = -1.0;
5181 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005182 if (!mHwSupportsPause) {
5183 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005184 }
5185 }
5186
5187 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005188 processVolume_l(track, last);
5189 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005190 sp<Track> previousTrack = mPreviousTrack.promote();
5191 if (previousTrack != 0) {
5192 if (track != previousTrack.get()) {
5193 // Flush any data still being written from last track
5194 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005195 // Invalidate previous track to force a seek when resuming.
5196 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005197 }
5198 }
5199 mPreviousTrack = track;
5200
Eric Laurentd595b7c2013-04-03 17:27:56 -07005201 // reset retry count
5202 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005203 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005204 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005205 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005206 doHwResume = true;
5207 mHwPaused = false;
5208 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005209 }
Eric Laurent81784c32012-11-19 14:55:58 -08005210 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005211 // clear effect chain input buffer if the last active track started underruns
5212 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005213 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005214 mEffectChains[0]->clearInputBuffer();
5215 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005216 if (track->isStopping_1()) {
5217 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005218 if (last && mHwPaused) {
5219 doHwResume = true;
5220 mHwPaused = false;
5221 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005222 }
5223 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5224 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005225 // We have consumed all the buffers of this track.
5226 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005227 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005228 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005229 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5230 } else {
5231 audioHALFrames = 0;
5232 }
5233
Andy Hung818e7a32016-02-16 18:08:07 -08005234 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005235 if (mStandby || !last ||
5236 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005237 if (track->isStopping_2()) {
5238 track->mState = TrackBase::STOPPED;
5239 }
Eric Laurent81784c32012-11-19 14:55:58 -08005240 if (track->isStopped()) {
5241 track->reset();
5242 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005243 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005244 }
5245 } else {
5246 // No buffers for this track. Give it a few chances to
5247 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005248 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005249 if (--(track->mRetryCount) <= 0) {
5250 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005251 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005252 // indicate to client process that the track was disabled because of underrun;
5253 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005254 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005255 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005256 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5257 "minFrames = %u, mFormat = %#x",
5258 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005259 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005260 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005261 doHwPause = true;
5262 mHwPaused = true;
5263 }
Eric Laurent81784c32012-11-19 14:55:58 -08005264 }
5265 }
5266 }
5267 }
5268
Eric Laurentd1f69b02014-12-15 14:33:13 -08005269 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005270 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005271 for (size_t i = 0; i < mTracks.size(); i++) {
5272 if (mTracks[i]->isFlushPending()) {
5273 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005274 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005275 }
5276 }
5277 }
5278
5279 // make sure the pause/flush/resume sequence is executed in the right order.
5280 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5281 // before flush and then resume HW. This can happen in case of pause/flush/resume
5282 // if resume is received before pause is executed.
5283 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005284 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005285 status_t result = mOutput->stream->pause();
5286 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005287 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005288 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005289 flushHw_l();
5290 }
5291 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005292 status_t result = mOutput->stream->resume();
5293 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005294 }
Eric Laurent81784c32012-11-19 14:55:58 -08005295 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005296 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005297
5298 return mixerStatus;
5299}
5300
5301void AudioFlinger::DirectOutputThread::threadLoop_mix()
5302{
Eric Laurent81784c32012-11-19 14:55:58 -08005303 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005304 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005305 // output audio to hardware
5306 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005307 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005308 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005309 status_t status = mActiveTrack->getNextBuffer(&buffer);
5310 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005311 // no need to pad with 0 for compressed audio
5312 if (audio_has_proportional_frames(mFormat)) {
5313 memset(curBuf, 0, frameCount * mFrameSize);
5314 }
Eric Laurent81784c32012-11-19 14:55:58 -08005315 break;
5316 }
5317 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5318 frameCount -= buffer.frameCount;
5319 curBuf += buffer.frameCount * mFrameSize;
5320 mActiveTrack->releaseBuffer(&buffer);
5321 }
Andy Hung2098f272014-02-27 14:00:06 -08005322 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005323 mSleepTimeUs = 0;
5324 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005325 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005326}
5327
5328void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5329{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005330 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005331 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005332 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005333 return;
5334 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005335 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005336 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005337 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005338 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005339 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005340 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005341 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005342 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005343 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005344 }
5345}
5346
Eric Laurentd1f69b02014-12-15 14:33:13 -08005347void AudioFlinger::DirectOutputThread::threadLoop_exit()
5348{
5349 {
5350 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005351 for (size_t i = 0; i < mTracks.size(); i++) {
5352 if (mTracks[i]->isFlushPending()) {
5353 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005354 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005355 }
5356 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005357 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005358 flushHw_l();
5359 }
5360 }
5361 PlaybackThread::threadLoop_exit();
5362}
5363
5364// must be called with thread mutex locked
5365bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5366{
5367 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005368 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005369
vivek mehta9cd7ad12016-03-17 00:18:29 -07005370 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5371 return !mStandby;
5372 }
5373
Eric Laurentd1f69b02014-12-15 14:33:13 -08005374 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5375 // after a timeout and we will enter standby then.
5376 if (mTracks.size() > 0) {
5377 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005378 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5379 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005380 }
5381
Eric Laurent5cff4032015-05-26 13:49:58 -07005382 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005383}
5384
Eric Laurent10351942014-05-08 18:49:52 -07005385// checkForNewParameter_l() must be called with ThreadBase::mLock held
5386bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5387 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005388{
5389 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005390 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005391
Eric Laurent10351942014-05-08 18:49:52 -07005392 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005393
Eric Laurent10351942014-05-08 18:49:52 -07005394 AudioParameter param = AudioParameter(keyValuePair);
5395 int value;
5396 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5397 // forward device change to effects that have requested to be
5398 // aware of attached audio device.
5399 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005400 a2dpDeviceChanged =
5401 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005402 mOutDevice = value;
5403 for (size_t i = 0; i < mEffectChains.size(); i++) {
5404 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005405 }
5406 }
Eric Laurent81784c32012-11-19 14:55:58 -08005407 }
Eric Laurent10351942014-05-08 18:49:52 -07005408 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5409 // do not accept frame count changes if tracks are open as the track buffer
5410 // size depends on frame count and correct behavior would not be garantied
5411 // if frame count is changed after track creation
5412 if (!mTracks.isEmpty()) {
5413 status = INVALID_OPERATION;
5414 } else {
5415 reconfig = true;
5416 }
5417 }
5418 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005419 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005420 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005421 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005422 mStandby = true;
5423 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005424 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005425 }
5426 if (status == NO_ERROR && reconfig) {
5427 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005428 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005429 }
5430 }
5431
Eric Laurent42537be2016-01-08 17:16:42 -08005432 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005433}
5434
5435uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5436{
5437 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005438 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005439 time = PlaybackThread::activeSleepTimeUs();
5440 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005441 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005442 }
5443 return time;
5444}
5445
5446uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5447{
5448 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005449 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005450 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5451 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005452 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005453 }
5454 return time;
5455}
5456
5457uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5458{
5459 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005460 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005461 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5462 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005463 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005464 }
5465 return time;
5466}
5467
5468void AudioFlinger::DirectOutputThread::cacheParameters_l()
5469{
5470 PlaybackThread::cacheParameters_l();
5471
5472 // use shorter standby delay as on normal output to release
5473 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005474 // no delay on outputs with HW A/V sync
5475 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005476 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005477 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005478 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005479 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005480 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005481 }
Eric Laurent81784c32012-11-19 14:55:58 -08005482}
5483
Eric Laurente659ef42014-09-29 13:06:46 -07005484void AudioFlinger::DirectOutputThread::flushHw_l()
5485{
Phil Burk062e67a2015-02-11 13:40:50 -08005486 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005487 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005488 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005489}
5490
Andy Hung10cbff12017-02-21 17:30:14 -08005491int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5492 // If a VolumeShaper is active, we must wake up periodically to update volume.
5493 const int64_t NS_PER_MS = 1000000;
5494 return mVolumeShaperActive ?
5495 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5496}
5497
Eric Laurent81784c32012-11-19 14:55:58 -08005498// ----------------------------------------------------------------------------
5499
Eric Laurentbfb1b832013-01-07 09:53:42 -08005500AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005501 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005502 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005503 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005504 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005505 mDrainSequence(0),
5506 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005507{
5508}
5509
5510AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5511{
5512}
5513
5514void AudioFlinger::AsyncCallbackThread::onFirstRef()
5515{
5516 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5517}
5518
5519bool AudioFlinger::AsyncCallbackThread::threadLoop()
5520{
5521 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005522 uint32_t writeAckSequence;
5523 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005524 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005525
5526 {
5527 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005528 while (!((mWriteAckSequence & 1) ||
5529 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005530 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005531 exitPending())) {
5532 mWaitWorkCV.wait(mLock);
5533 }
5534
Eric Laurentbfb1b832013-01-07 09:53:42 -08005535 if (exitPending()) {
5536 break;
5537 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005538 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5539 mWriteAckSequence, mDrainSequence);
5540 writeAckSequence = mWriteAckSequence;
5541 mWriteAckSequence &= ~1;
5542 drainSequence = mDrainSequence;
5543 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005544 asyncError = mAsyncError;
5545 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005546 }
5547 {
Eric Laurent4de95592013-09-26 15:28:21 -07005548 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5549 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005550 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005551 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005552 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005553 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005554 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005555 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005556 if (asyncError) {
5557 playbackThread->onAsyncError();
5558 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005559 }
5560 }
5561 }
5562 return false;
5563}
5564
5565void AudioFlinger::AsyncCallbackThread::exit()
5566{
5567 ALOGV("AsyncCallbackThread::exit");
5568 Mutex::Autolock _l(mLock);
5569 requestExit();
5570 mWaitWorkCV.broadcast();
5571}
5572
Eric Laurent3b4529e2013-09-05 18:09:19 -07005573void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005574{
5575 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005576 // bit 0 is cleared
5577 mWriteAckSequence = sequence << 1;
5578}
5579
5580void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5581{
5582 Mutex::Autolock _l(mLock);
5583 // ignore unexpected callbacks
5584 if (mWriteAckSequence & 2) {
5585 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005586 mWaitWorkCV.signal();
5587 }
5588}
5589
Eric Laurent3b4529e2013-09-05 18:09:19 -07005590void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005591{
5592 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005593 // bit 0 is cleared
5594 mDrainSequence = sequence << 1;
5595}
5596
5597void AudioFlinger::AsyncCallbackThread::resetDraining()
5598{
5599 Mutex::Autolock _l(mLock);
5600 // ignore unexpected callbacks
5601 if (mDrainSequence & 2) {
5602 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005603 mWaitWorkCV.signal();
5604 }
5605}
5606
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005607void AudioFlinger::AsyncCallbackThread::setAsyncError()
5608{
5609 Mutex::Autolock _l(mLock);
5610 mAsyncError = true;
5611 mWaitWorkCV.signal();
5612}
5613
Eric Laurentbfb1b832013-01-07 09:53:42 -08005614
5615// ----------------------------------------------------------------------------
5616AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005617 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5618 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005619 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5620 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005621{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005622 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005623 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005624 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005625}
5626
Eric Laurentbfb1b832013-01-07 09:53:42 -08005627void AudioFlinger::OffloadThread::threadLoop_exit()
5628{
5629 if (mFlushPending || mHwPaused) {
5630 // If a flush is pending or track was paused, just discard buffered data
5631 flushHw_l();
5632 } else {
5633 mMixerStatus = MIXER_DRAIN_ALL;
5634 threadLoop_drain();
5635 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005636 if (mUseAsyncWrite) {
5637 ALOG_ASSERT(mCallbackThread != 0);
5638 mCallbackThread->exit();
5639 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005640 PlaybackThread::threadLoop_exit();
5641}
5642
5643AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5644 Vector< sp<Track> > *tracksToRemove
5645)
5646{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005647 size_t count = mActiveTracks.size();
5648
5649 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005650 bool doHwPause = false;
5651 bool doHwResume = false;
5652
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005653 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005654
Eric Laurentbfb1b832013-01-07 09:53:42 -08005655 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005656 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005657 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005658#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005659 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005660#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005661 // Only consider last track started for volume and mixer state control.
5662 // In theory an older track could underrun and restart after the new one starts
5663 // but as we only care about the transition phase between two tracks on a
5664 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005665 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005666 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005667
Haynes Mathew George7844f672014-01-15 12:32:55 -08005668 if (track->isInvalid()) {
5669 ALOGW("An invalidated track shouldn't be in active list");
5670 tracksToRemove->add(track);
5671 continue;
5672 }
5673
5674 if (track->mState == TrackBase::IDLE) {
5675 ALOGW("An idle track shouldn't be in active list");
5676 continue;
5677 }
5678
Eric Laurentbfb1b832013-01-07 09:53:42 -08005679 if (track->isPausing()) {
5680 track->setPaused();
5681 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005682 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005683 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005684 mHwPaused = true;
5685 }
5686 // If we were part way through writing the mixbuffer to
5687 // the HAL we must save this until we resume
5688 // BUG - this will be wrong if a different track is made active,
5689 // in that case we want to discard the pending data in the
5690 // mixbuffer and tell the client to present it again when the
5691 // track is resumed
5692 mPausedWriteLength = mCurrentWriteLength;
5693 mPausedBytesRemaining = mBytesRemaining;
5694 mBytesRemaining = 0; // stop writing
5695 }
5696 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005697 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005698 if (track->isStopping_1()) {
5699 track->mRetryCount = kMaxTrackStopRetriesOffload;
5700 } else {
5701 track->mRetryCount = kMaxTrackRetriesOffload;
5702 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005703 track->flushAck();
5704 if (last) {
5705 mFlushPending = true;
5706 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005707 } else if (track->isResumePending()){
5708 track->resumeAck();
5709 if (last) {
5710 if (mPausedBytesRemaining) {
5711 // Need to continue write that was interrupted
5712 mCurrentWriteLength = mPausedWriteLength;
5713 mBytesRemaining = mPausedBytesRemaining;
5714 mPausedBytesRemaining = 0;
5715 }
5716 if (mHwPaused) {
5717 doHwResume = true;
5718 mHwPaused = false;
5719 // threadLoop_mix() will handle the case that we need to
5720 // resume an interrupted write
5721 }
5722 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005723 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005724
Eric Laurent3df841a2016-07-15 15:15:40 -07005725 mLeftVolFloat = mRightVolFloat = -1.0;
5726
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005727 // Do not handle new data in this iteration even if track->framesReady()
5728 mixerStatus = MIXER_TRACKS_ENABLED;
5729 }
5730 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005731 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005732 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005733 if (track->mFillingUpStatus == Track::FS_FILLED) {
5734 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005735 if (last) {
5736 // make sure processVolume_l() will apply new volume even if 0
5737 mLeftVolFloat = mRightVolFloat = -1.0;
5738 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005739 }
5740
5741 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005742 sp<Track> previousTrack = mPreviousTrack.promote();
5743 if (previousTrack != 0) {
5744 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005745 // Flush any data still being written from last track
5746 mBytesRemaining = 0;
5747 if (mPausedBytesRemaining) {
5748 // Last track was paused so we also need to flush saved
5749 // mixbuffer state and invalidate track so that it will
5750 // re-submit that unwritten data when it is next resumed
5751 mPausedBytesRemaining = 0;
5752 // Invalidate is a bit drastic - would be more efficient
5753 // to have a flag to tell client that some of the
5754 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005755 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005756 }
5757 // flush data already sent to the DSP if changing audio session as audio
5758 // comes from a different source. Also invalidate previous track to force a
5759 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005760 if (previousTrack->sessionId() != track->sessionId()) {
5761 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005762 }
5763 }
5764 }
5765 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005766 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005767 if (track->isStopping_1()) {
5768 track->mRetryCount = kMaxTrackStopRetriesOffload;
5769 } else {
5770 track->mRetryCount = kMaxTrackRetriesOffload;
5771 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005772 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005773 mixerStatus = MIXER_TRACKS_READY;
5774 }
5775 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005776 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005777 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005778 if (--(track->mRetryCount) <= 0) {
5779 // Hardware buffer can hold a large amount of audio so we must
5780 // wait for all current track's data to drain before we say
5781 // that the track is stopped.
5782 if (mBytesRemaining == 0) {
5783 // Only start draining when all data in mixbuffer
5784 // has been written
5785 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5786 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5787 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5788 if (last && !mStandby) {
5789 // do not modify drain sequence if we are already draining. This happens
5790 // when resuming from pause after drain.
5791 if ((mDrainSequence & 1) == 0) {
5792 mSleepTimeUs = 0;
5793 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5794 mixerStatus = MIXER_DRAIN_TRACK;
5795 mDrainSequence += 2;
5796 }
5797 if (mHwPaused) {
5798 // It is possible to move from PAUSED to STOPPING_1 without
5799 // a resume so we must ensure hardware is running
5800 doHwResume = true;
5801 mHwPaused = false;
5802 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005803 }
5804 }
Eric Laurente93cc032016-05-05 10:15:10 -07005805 } else if (last) {
5806 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5807 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005808 }
5809 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005810 // Drain has completed or we are in standby, signal presentation complete
5811 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005812 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005813 uint32_t latency = 0;
5814 status_t result = mOutput->stream->getLatency(&latency);
5815 ALOGE_IF(result != OK,
5816 "Error when retrieving output stream latency: %d", result);
5817 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005818 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005819 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005820 track->presentationComplete(framesWritten, audioHALFrames);
5821 track->reset();
5822 tracksToRemove->add(track);
5823 }
5824 } else {
5825 // No buffers for this track. Give it a few chances to
5826 // fill a buffer, then remove it from active list.
5827 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005828 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005829 uint64_t position = 0;
5830 struct timespec unused;
5831 // The running check restarts the retry counter at least once.
5832 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5833 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5834 running = true;
5835 mOffloadUnderrunPosition = position;
5836 }
5837 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005838 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5839 (long long)position, (long long)mOffloadUnderrunPosition);
5840 }
5841 if (running) { // still running, give us more time.
5842 track->mRetryCount = kMaxTrackRetriesOffload;
5843 } else {
5844 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5845 track->name());
5846 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005847 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005848 // it will then automatically call start() when data is available
5849 track->disable();
5850 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005851 } else if (last){
5852 mixerStatus = MIXER_TRACKS_ENABLED;
5853 }
5854 }
5855 }
5856 // compute volume for this track
5857 processVolume_l(track, last);
5858 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005859
Eric Laurentea0fade2013-10-04 16:23:48 -07005860 // make sure the pause/flush/resume sequence is executed in the right order.
5861 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5862 // before flush and then resume HW. This can happen in case of pause/flush/resume
5863 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005864 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005865 status_t result = mOutput->stream->pause();
5866 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005867 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005868 if (mFlushPending) {
5869 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005870 }
Eric Laurentfd477972013-10-25 18:10:40 -07005871 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005872 status_t result = mOutput->stream->resume();
5873 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005874 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005875
Eric Laurentbfb1b832013-01-07 09:53:42 -08005876 // remove all the tracks that need to be...
5877 removeTracks_l(*tracksToRemove);
5878
5879 return mixerStatus;
5880}
5881
Eric Laurentbfb1b832013-01-07 09:53:42 -08005882// must be called with thread mutex locked
5883bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5884{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005885 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5886 mWriteAckSequence, mDrainSequence);
5887 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005888 return true;
5889 }
5890 return false;
5891}
5892
Eric Laurentbfb1b832013-01-07 09:53:42 -08005893bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5894{
5895 Mutex::Autolock _l(mLock);
5896 return waitingAsyncCallback_l();
5897}
5898
5899void AudioFlinger::OffloadThread::flushHw_l()
5900{
Eric Laurente659ef42014-09-29 13:06:46 -07005901 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005902 // Flush anything still waiting in the mixbuffer
5903 mCurrentWriteLength = 0;
5904 mBytesRemaining = 0;
5905 mPausedWriteLength = 0;
5906 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005907 // reset bytes written count to reflect that DSP buffers are empty after flush.
5908 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005909 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005910
Eric Laurentbfb1b832013-01-07 09:53:42 -08005911 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005912 // discard any pending drain or write ack by incrementing sequence
5913 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5914 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005915 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005916 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5917 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005918 }
5919}
5920
Haynes Mathew George05317d22016-05-03 16:34:26 -07005921void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5922{
5923 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005924 if (PlaybackThread::invalidateTracks_l(streamType)) {
5925 mFlushPending = true;
5926 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005927}
5928
Eric Laurentbfb1b832013-01-07 09:53:42 -08005929// ----------------------------------------------------------------------------
5930
Eric Laurent81784c32012-11-19 14:55:58 -08005931AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005932 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005933 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005934 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005935 mWaitTimeMs(UINT_MAX)
5936{
5937 addOutputTrack(mainThread);
5938}
5939
5940AudioFlinger::DuplicatingThread::~DuplicatingThread()
5941{
5942 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5943 mOutputTracks[i]->destroy();
5944 }
5945}
5946
5947void AudioFlinger::DuplicatingThread::threadLoop_mix()
5948{
5949 // mix buffers...
5950 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005951 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005952 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005953 if (mMixerBufferValid) {
5954 memset(mMixerBuffer, 0, mMixerBufferSize);
5955 } else {
5956 memset(mSinkBuffer, 0, mSinkBufferSize);
5957 }
Eric Laurent81784c32012-11-19 14:55:58 -08005958 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005959 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005960 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005961 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005962 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005963}
5964
5965void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5966{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005967 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005968 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005969 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005970 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005971 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005972 }
5973 } else if (mBytesWritten != 0) {
5974 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5975 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005976 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005977 } else {
5978 // flush remaining overflow buffers in output tracks
5979 writeFrames = 0;
5980 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005981 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005982 }
5983}
5984
Eric Laurentbfb1b832013-01-07 09:53:42 -08005985ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005986{
5987 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005988 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005989 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005990 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005991 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005992}
5993
5994void AudioFlinger::DuplicatingThread::threadLoop_standby()
5995{
5996 // DuplicatingThread implements standby by stopping all tracks
5997 for (size_t i = 0; i < outputTracks.size(); i++) {
5998 outputTracks[i]->stop();
5999 }
6000}
6001
Andy Hung1bc088a2018-02-09 15:57:31 -08006002void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6003{
6004 MixerThread::dumpInternals(fd, args);
6005
6006 std::stringstream ss;
6007 const size_t numTracks = mOutputTracks.size();
6008 ss << " " << numTracks << " OutputTracks";
6009 if (numTracks > 0) {
6010 ss << ":";
6011 for (const auto &track : mOutputTracks) {
6012 const sp<ThreadBase> thread = track->thread().promote();
6013 ss << " (" << track->name() << " : ";
6014 if (thread.get() != nullptr) {
6015 ss << thread.get() << ", " << thread->id();
6016 } else {
6017 ss << "null";
6018 }
6019 ss << ")";
6020 }
6021 }
6022 ss << "\n";
6023 std::string result = ss.str();
6024 write(fd, result.c_str(), result.size());
6025}
6026
Eric Laurent81784c32012-11-19 14:55:58 -08006027void AudioFlinger::DuplicatingThread::saveOutputTracks()
6028{
6029 outputTracks = mOutputTracks;
6030}
6031
6032void AudioFlinger::DuplicatingThread::clearOutputTracks()
6033{
6034 outputTracks.clear();
6035}
6036
6037void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6038{
6039 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006040 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6041 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6042 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6043 const size_t frameCount =
6044 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6045 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6046 // from different OutputTracks and their associated MixerThreads (e.g. one may
6047 // nearly empty and the other may be dropping data).
6048
6049 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006050 this,
6051 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006052 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006053 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006054 frameCount,
6055 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006056 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6057 if (status != NO_ERROR) {
6058 ALOGE("addOutputTrack() initCheck failed %d", status);
6059 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006060 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006061 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6062 mOutputTracks.add(outputTrack);
6063 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6064 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006065}
6066
6067void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6068{
6069 Mutex::Autolock _l(mLock);
6070 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6071 if (mOutputTracks[i]->thread() == thread) {
6072 mOutputTracks[i]->destroy();
6073 mOutputTracks.removeAt(i);
6074 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006075 if (thread->getOutput() == mOutput) {
6076 mOutput = NULL;
6077 }
Eric Laurent81784c32012-11-19 14:55:58 -08006078 return;
6079 }
6080 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006081 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006082}
6083
6084// caller must hold mLock
6085void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6086{
6087 mWaitTimeMs = UINT_MAX;
6088 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6089 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6090 if (strong != 0) {
6091 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6092 if (waitTimeMs < mWaitTimeMs) {
6093 mWaitTimeMs = waitTimeMs;
6094 }
6095 }
6096 }
6097}
6098
6099
6100bool AudioFlinger::DuplicatingThread::outputsReady(
6101 const SortedVector< sp<OutputTrack> > &outputTracks)
6102{
6103 for (size_t i = 0; i < outputTracks.size(); i++) {
6104 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6105 if (thread == 0) {
6106 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6107 outputTracks[i].get());
6108 return false;
6109 }
6110 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6111 // see note at standby() declaration
6112 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6113 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6114 thread.get());
6115 return false;
6116 }
6117 }
6118 return true;
6119}
6120
6121uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6122{
6123 return (mWaitTimeMs * 1000) / 2;
6124}
6125
6126void AudioFlinger::DuplicatingThread::cacheParameters_l()
6127{
6128 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6129 updateWaitTime_l();
6130
6131 MixerThread::cacheParameters_l();
6132}
6133
Eric Laurent6acd1d42017-01-04 14:23:29 -08006134
Eric Laurent81784c32012-11-19 14:55:58 -08006135// ----------------------------------------------------------------------------
6136// Record
6137// ----------------------------------------------------------------------------
6138
6139AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6140 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006141 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006142 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006143 audio_devices_t inDevice,
6144 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006145#ifdef TEE_SINK
6146 , const sp<NBAIO_Sink>& teeSink
6147#endif
6148 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006149 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006150 mInput(input),
6151 mActiveTracks(&this->mLocalLog),
6152 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006153 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006154 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08006155#ifdef TEE_SINK
6156 , mTeeSink(teeSink)
6157#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006158 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6159 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006160 // mFastCapture below
6161 , mFastCaptureFutex(0)
6162 // mInputSource
6163 // mPipeSink
6164 // mPipeSource
6165 , mPipeFramesP2(0)
6166 // mPipeMemory
6167 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006168 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006169 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006170{
Glenn Kastend7dca052015-03-05 16:05:54 -08006171 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6172 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006173
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006174 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006175
6176 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006177 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006178 size_t numCounterOffers = 0;
6179 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006180#if !LOG_NDEBUG
6181 ssize_t index =
6182#else
6183 (void)
6184#endif
6185 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006186 ALOG_ASSERT(index == 0);
6187
6188 // initialize fast capture depending on configuration
6189 bool initFastCapture;
6190 switch (kUseFastCapture) {
6191 case FastCapture_Never:
6192 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006193 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006194 break;
6195 case FastCapture_Always:
6196 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006197 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006198 break;
6199 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006200 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006201 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6202 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6203 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006204 break;
6205 // case FastCapture_Dynamic:
6206 }
6207
6208 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006209 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006210 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006211 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6212 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006213 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006214 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006215 const sp<MemoryDealer> roHeap(readOnlyHeap());
6216 sp<IMemory> pipeMemory;
6217 if ((roHeap == 0) ||
6218 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006219 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6220 ALOGE("not enough memory for pipe buffer size=%zu; "
6221 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6222 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6223 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006224 goto failed;
6225 }
6226 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6227 memset(pipeBuffer, 0, pipeSize);
6228 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6229 const NBAIO_Format offers[1] = {format};
6230 size_t numCounterOffers = 0;
6231 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6232 ALOG_ASSERT(index == 0);
6233 mPipeSink = pipe;
6234 PipeReader *pipeReader = new PipeReader(*pipe);
6235 numCounterOffers = 0;
6236 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6237 ALOG_ASSERT(index == 0);
6238 mPipeSource = pipeReader;
6239 mPipeFramesP2 = pipeFramesP2;
6240 mPipeMemory = pipeMemory;
6241
6242 // create fast capture
6243 mFastCapture = new FastCapture();
6244 FastCaptureStateQueue *sq = mFastCapture->sq();
6245#ifdef STATE_QUEUE_DUMP
6246 // FIXME
6247#endif
6248 FastCaptureState *state = sq->begin();
6249 state->mCblk = NULL;
6250 state->mInputSource = mInputSource.get();
6251 state->mInputSourceGen++;
6252 state->mPipeSink = pipe;
6253 state->mPipeSinkGen++;
6254 state->mFrameCount = mFrameCount;
6255 state->mCommand = FastCaptureState::COLD_IDLE;
6256 // already done in constructor initialization list
6257 //mFastCaptureFutex = 0;
6258 state->mColdFutexAddr = &mFastCaptureFutex;
6259 state->mColdGen++;
6260 state->mDumpState = &mFastCaptureDumpState;
6261#ifdef TEE_SINK
6262 // FIXME
6263#endif
6264 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6265 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6266 sq->end();
6267 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6268
6269 // start the fast capture
6270 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6271 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006272 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006273 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006274#ifdef AUDIO_WATCHDOG
6275 // FIXME
6276#endif
6277
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006278 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006279 }
6280failed: ;
6281
6282 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006283}
6284
Eric Laurent81784c32012-11-19 14:55:58 -08006285AudioFlinger::RecordThread::~RecordThread()
6286{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006287 if (mFastCapture != 0) {
6288 FastCaptureStateQueue *sq = mFastCapture->sq();
6289 FastCaptureState *state = sq->begin();
6290 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6291 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6292 if (old == -1) {
6293 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6294 }
6295 }
6296 state->mCommand = FastCaptureState::EXIT;
6297 sq->end();
6298 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6299 mFastCapture->join();
6300 mFastCapture.clear();
6301 }
6302 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006303 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006304 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006305}
6306
6307void AudioFlinger::RecordThread::onFirstRef()
6308{
Glenn Kastend7dca052015-03-05 16:05:54 -08006309 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006310}
6311
Eric Laurent555530a2017-02-07 18:17:24 -08006312void AudioFlinger::RecordThread::preExit()
6313{
6314 ALOGV(" preExit()");
6315 Mutex::Autolock _l(mLock);
6316 for (size_t i = 0; i < mTracks.size(); i++) {
6317 sp<RecordTrack> track = mTracks[i];
6318 track->invalidate();
6319 }
6320 mActiveTracks.clear();
6321 mStartStopCond.broadcast();
6322}
6323
Eric Laurent81784c32012-11-19 14:55:58 -08006324bool AudioFlinger::RecordThread::threadLoop()
6325{
Eric Laurent81784c32012-11-19 14:55:58 -08006326 nsecs_t lastWarning = 0;
6327
6328 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006329
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006330reacquire_wakelock:
6331 sp<RecordTrack> activeTrack;
6332 {
6333 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006334 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006335 }
6336
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006337 // used to request a deferred sleep, to be executed later while mutex is unlocked
6338 uint32_t sleepUs = 0;
6339
6340 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006341 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006342 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006343
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006344 // activeTracks accumulates a copy of a subset of mActiveTracks
6345 Vector< sp<RecordTrack> > activeTracks;
6346
Glenn Kasten735f45f2014-08-18 15:51:59 -07006347 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006348 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006349
Glenn Kasten735f45f2014-08-18 15:51:59 -07006350 // reference to a fast track which is about to be removed
6351 sp<RecordTrack> fastTrackToRemove;
6352
Eric Laurent81784c32012-11-19 14:55:58 -08006353 { // scope for mLock
6354 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006355
Eric Laurent021cf962014-05-13 10:18:14 -07006356 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006357
Eric Laurent000a4192014-01-29 15:17:32 -08006358 // check exitPending here because checkForNewParameters_l() and
6359 // checkForNewParameters_l() can temporarily release mLock
6360 if (exitPending()) {
6361 break;
6362 }
6363
Eric Laurent5c25d562016-07-13 17:17:45 -07006364 // sleep with mutex unlocked
6365 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006366 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006367 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6368 ATRACE_END();
6369 sleepUs = 0;
6370 continue;
6371 }
6372
Glenn Kasten2b806402013-11-20 16:37:38 -08006373 // if no active track(s), then standby and release wakelock
6374 size_t size = mActiveTracks.size();
6375 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006376 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006377 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006378 releaseWakeLock_l();
6379 ALOGV("RecordThread: loop stopping");
6380 // go to sleep
6381 mWaitWorkCV.wait(mLock);
6382 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006383 goto reacquire_wakelock;
6384 }
6385
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006386 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006387 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006388 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006389
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006390 activeTrack = mActiveTracks[i];
6391 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006392 if (activeTrack->isFastTrack()) {
6393 ALOG_ASSERT(fastTrackToRemove == 0);
6394 fastTrackToRemove = activeTrack;
6395 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006396 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006397 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006398 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006399 continue;
6400 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006401
6402 TrackBase::track_state activeTrackState = activeTrack->mState;
6403 switch (activeTrackState) {
6404
6405 case TrackBase::PAUSING:
6406 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006407 doBroadcast = true;
6408 size--;
6409 continue;
6410
6411 case TrackBase::STARTING_1:
6412 sleepUs = 10000;
6413 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006414 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006415 continue;
6416
6417 case TrackBase::STARTING_2:
6418 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006419 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006420 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006421 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006422 break;
6423
6424 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006425 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006426 break;
6427
6428 case TrackBase::IDLE:
6429 i++;
6430 continue;
6431
6432 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006433 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006434 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006435
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006436 activeTracks.add(activeTrack);
6437 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006438
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006439 if (activeTrack->isFastTrack()) {
6440 ALOG_ASSERT(!mFastTrackAvail);
6441 ALOG_ASSERT(fastTrack == 0);
6442 fastTrack = activeTrack;
6443 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006444 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006445
Andy Hungdae27702016-10-31 14:01:16 -07006446 mActiveTracks.updatePowerState(this);
6447
Eric Laurent5c25d562016-07-13 17:17:45 -07006448 if (allStopped) {
6449 standbyIfNotAlreadyInStandby();
6450 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006451 if (doBroadcast) {
6452 mStartStopCond.broadcast();
6453 }
6454
6455 // sleep if there are no active tracks to process
6456 if (activeTracks.size() == 0) {
6457 if (sleepUs == 0) {
6458 sleepUs = kRecordThreadSleepUs;
6459 }
6460 continue;
6461 }
6462 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006463
Eric Laurent81784c32012-11-19 14:55:58 -08006464 lockEffectChains_l(effectChains);
6465 }
6466
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006467 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006468
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006469 size_t size = effectChains.size();
6470 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006471 // thread mutex is not locked, but effect chain is locked
6472 effectChains[i]->process_l();
6473 }
6474
Glenn Kasten735f45f2014-08-18 15:51:59 -07006475 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006476 if (mFastCapture != 0) {
6477 FastCaptureStateQueue *sq = mFastCapture->sq();
6478 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006479 bool didModify = false;
6480 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006481 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6482 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6483 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6484 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6485 if (old == -1) {
6486 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6487 }
6488 }
6489 state->mCommand = FastCaptureState::READ_WRITE;
6490#if 0 // FIXME
6491 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006492 FastThreadDumpState::kSamplingNforLowRamDevice :
6493 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006494#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006495 didModify = true;
6496 }
6497 audio_track_cblk_t *cblkOld = state->mCblk;
6498 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6499 if (cblkNew != cblkOld) {
6500 state->mCblk = cblkNew;
6501 // block until acked if removing a fast track
6502 if (cblkOld != NULL) {
6503 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6504 }
6505 didModify = true;
6506 }
6507 sq->end(didModify);
6508 if (didModify) {
6509 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006510#if 0
6511 if (kUseFastCapture == FastCapture_Dynamic) {
6512 mNormalSource = mPipeSource;
6513 }
6514#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006515 }
6516 }
6517
Glenn Kasten735f45f2014-08-18 15:51:59 -07006518 // now run the fast track destructor with thread mutex unlocked
6519 fastTrackToRemove.clear();
6520
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006521 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6522 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6523 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6524 // If destination is non-contiguous, first read past the nominal end of buffer, then
6525 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006526
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006527 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006528 ssize_t framesRead;
6529
6530 // If an NBAIO source is present, use it to read the normal capture's data
6531 if (mPipeSource != 0) {
6532 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006533 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006534 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006535 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006536 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6537 // buffer size or at least for 20ms.
6538 size_t sleepFrames = max(
6539 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6540 if (framesRead <= (ssize_t) sleepFrames) {
6541 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6542 }
6543 if (framesRead < 0) {
6544 status_t status = (status_t) framesRead;
6545 switch (status) {
6546 case OVERRUN:
6547 ALOGW("overrun on read from pipe");
6548 framesRead = 0;
6549 break;
6550 case NEGOTIATE:
6551 ALOGE("re-negotiation is needed");
6552 framesRead = -1; // Will cause an attempt to recover.
6553 break;
6554 default:
6555 ALOGE("unknown error %d on read from pipe", status);
6556 break;
6557 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006558 }
6559 // otherwise use the HAL / AudioStreamIn directly
6560 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006561 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006562 size_t bytesRead;
6563 status_t result = mInput->stream->read(
6564 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006565 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006566 if (result < 0) {
6567 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006568 } else {
6569 framesRead = bytesRead / mFrameSize;
6570 }
6571 }
6572
Andy Hung3f0c9022016-01-15 17:49:46 -08006573 // Update server timestamp with server stats
6574 // systemTime() is optional if the hardware supports timestamps.
6575 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6576 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6577
6578 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006579 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006580 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006581 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006582 if (ret == NO_ERROR) {
6583 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6584 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6585 // Note: In general record buffers should tend to be empty in
6586 // a properly running pipeline.
6587 //
6588 // Also, it is not advantageous to call get_presentation_position during the read
6589 // as the read obtains a lock, preventing the timestamp call from executing.
6590 }
6591 }
6592 // Use this to track timestamp information
6593 // ALOGD("%s", mTimestamp.toString().c_str());
6594
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006595 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006596 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006597 // Force input into standby so that it tries to recover at next read attempt
6598 inputStandBy();
6599 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006600 }
6601 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006602 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006603 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006604 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006605
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006606 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006607 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006608 }
6609 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006610 {
6611 size_t part1 = mRsmpInFramesP2 - rear;
6612 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006613 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006614 (framesRead - part1) * mFrameSize);
6615 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006616 }
6617 rear = mRsmpInRear += framesRead;
6618
6619 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006620
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006621 // loop over each active track
6622 for (size_t i = 0; i < size; i++) {
6623 activeTrack = activeTracks[i];
6624
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006625 // skip fast tracks, as those are handled directly by FastCapture
6626 if (activeTrack->isFastTrack()) {
6627 continue;
6628 }
6629
Andy Hung73c02e42015-03-29 01:13:58 -07006630 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006631 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6632
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006633 enum {
6634 OVERRUN_UNKNOWN,
6635 OVERRUN_TRUE,
6636 OVERRUN_FALSE
6637 } overrun = OVERRUN_UNKNOWN;
6638
6639 // loop over getNextBuffer to handle circular sink
6640 for (;;) {
6641
6642 activeTrack->mSink.frameCount = ~0;
6643 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6644 size_t framesOut = activeTrack->mSink.frameCount;
6645 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6646
Andy Hung73c02e42015-03-29 01:13:58 -07006647 // check available frames and handle overrun conditions
6648 // if the record track isn't draining fast enough.
6649 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006650 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006651 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6652 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006653 overrun = OVERRUN_TRUE;
6654 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006655 if (framesOut == 0 || framesIn == 0) {
6656 break;
6657 }
6658
Andy Hung6770c6f2015-04-07 13:43:36 -07006659 // Don't allow framesOut to be larger than what is possible with resampling
6660 // from framesIn.
6661 // This isn't strictly necessary but helps limit buffer resizing in
6662 // RecordBufferConverter. TODO: remove when no longer needed.
6663 framesOut = min(framesOut,
6664 destinationFramesPossible(
6665 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006666 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6667 framesOut = activeTrack->mRecordBufferConverter->convert(
6668 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006669
6670 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6671 overrun = OVERRUN_FALSE;
6672 }
6673
6674 if (activeTrack->mFramesToDrop == 0) {
6675 if (framesOut > 0) {
6676 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006677 // Sanitize before releasing if the track has no access to the source data
6678 // An idle UID receives silence from non virtual devices until active
6679 if (activeTrack->isSilenced()) {
6680 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6681 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006682 activeTrack->releaseBuffer(&activeTrack->mSink);
6683 }
6684 } else {
6685 // FIXME could do a partial drop of framesOut
6686 if (activeTrack->mFramesToDrop > 0) {
6687 activeTrack->mFramesToDrop -= framesOut;
6688 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006689 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006690 }
6691 } else {
6692 activeTrack->mFramesToDrop += framesOut;
6693 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6694 activeTrack->mSyncStartEvent->isCancelled()) {
6695 ALOGW("Synced record %s, session %d, trigger session %d",
6696 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6697 activeTrack->sessionId(),
6698 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006699 activeTrack->mSyncStartEvent->triggerSession() :
6700 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006701 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006702 }
6703 }
6704 }
6705
6706 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006707 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006708 }
6709 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006710
6711 switch (overrun) {
6712 case OVERRUN_TRUE:
6713 // client isn't retrieving buffers fast enough
6714 if (!activeTrack->setOverflow()) {
6715 nsecs_t now = systemTime();
6716 // FIXME should lastWarning per track?
6717 if ((now - lastWarning) > kWarningThrottleNs) {
6718 ALOGW("RecordThread: buffer overflow");
6719 lastWarning = now;
6720 }
6721 }
6722 break;
6723 case OVERRUN_FALSE:
6724 activeTrack->clearOverflow();
6725 break;
6726 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006727 break;
6728 }
6729
Andy Hung3f0c9022016-01-15 17:49:46 -08006730 // update frame information and push timestamp out
6731 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006732 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006733 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6734 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006735 }
6736
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006737unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006738 // enable changes in effect chain
6739 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006740 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006741 }
6742
Glenn Kasten93e471f2013-08-19 08:40:07 -07006743 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006744
6745 {
6746 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006747 for (size_t i = 0; i < mTracks.size(); i++) {
6748 sp<RecordTrack> track = mTracks[i];
6749 track->invalidate();
6750 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006751 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006752 mStartStopCond.broadcast();
6753 }
6754
6755 releaseWakeLock();
6756
6757 ALOGV("RecordThread %p exiting", this);
6758 return false;
6759}
6760
Glenn Kasten93e471f2013-08-19 08:40:07 -07006761void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006762{
6763 if (!mStandby) {
6764 inputStandBy();
6765 mStandby = true;
6766 }
6767}
6768
6769void AudioFlinger::RecordThread::inputStandBy()
6770{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006771 // Idle the fast capture if it's currently running
6772 if (mFastCapture != 0) {
6773 FastCaptureStateQueue *sq = mFastCapture->sq();
6774 FastCaptureState *state = sq->begin();
6775 if (!(state->mCommand & FastCaptureState::IDLE)) {
6776 state->mCommand = FastCaptureState::COLD_IDLE;
6777 state->mColdFutexAddr = &mFastCaptureFutex;
6778 state->mColdGen++;
6779 mFastCaptureFutex = 0;
6780 sq->end();
6781 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6782 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6783#if 0
6784 if (kUseFastCapture == FastCapture_Dynamic) {
6785 // FIXME
6786 }
6787#endif
6788#ifdef AUDIO_WATCHDOG
6789 // FIXME
6790#endif
6791 } else {
6792 sq->end(false /*didModify*/);
6793 }
6794 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006795 status_t result = mInput->stream->standby();
6796 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006797
6798 // If going into standby, flush the pipe source.
6799 if (mPipeSource.get() != nullptr) {
6800 const ssize_t flushed = mPipeSource->flush();
6801 if (flushed > 0) {
6802 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6803 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6804 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6805 }
6806 }
Eric Laurent81784c32012-11-19 14:55:58 -08006807}
6808
Glenn Kasten05997e22014-03-13 15:08:33 -07006809// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006810sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006811 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07006812 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006813 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08006814 audio_format_t format,
6815 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006816 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006817 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006818 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006819 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006820 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006821 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006822 status_t *status,
6823 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006824{
Glenn Kasten74935e42013-12-19 08:56:45 -08006825 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006826 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006827 sp<RecordTrack> track;
6828 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006829 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006830 audio_input_flags_t requestedFlags = *flags;
6831 uint32_t sampleRate;
6832
6833 lStatus = initCheck();
6834 if (lStatus != NO_ERROR) {
6835 ALOGE("createRecordTrack_l() audio driver not initialized");
6836 goto Exit;
6837 }
6838
6839 if (*pSampleRate == 0) {
6840 *pSampleRate = mSampleRate;
6841 }
6842 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07006843
6844 // special case for FAST flag considered OK if fast capture is present
6845 if (hasFastCapture()) {
6846 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6847 }
6848
Eric Laurentf14db3c2017-12-08 14:20:36 -08006849 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07006850 if ((*flags & inputFlags) != *flags) {
6851 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6852 " input flags (%08x)",
6853 *flags, inputFlags);
6854 *flags = (audio_input_flags_t)(*flags & inputFlags);
6855 }
Eric Laurent81784c32012-11-19 14:55:58 -08006856
Glenn Kasten90e58b12013-07-31 16:16:02 -07006857 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006858 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006859 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006860 // we formerly checked for a callback handler (non-0 tid),
6861 // but that is no longer required for TRANSFER_OBTAIN mode
6862 //
Glenn Kasten74105912014-07-03 12:28:53 -07006863 // frame count is not specified, or is exactly the pipe depth
6864 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006865 // PCM data
6866 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006867 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006868 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006869 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006870 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006871 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006872 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006873 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006874 hasFastCapture() &&
6875 // there are sufficient fast track slots available
6876 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006877 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006878 // check compatibility with audio effects.
6879 Mutex::Autolock _l(mLock);
6880 // Do not accept FAST flag if the session has software effects
6881 sp<EffectChain> chain = getEffectChain_l(sessionId);
6882 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006883 audio_input_flags_t old = *flags;
6884 chain->checkInputFlagCompatibility(flags);
6885 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006886 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6887 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006888 }
6889 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006890 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006891 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6892 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006893 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006894 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6895 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006896 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006897 this, frameCount, mFrameCount, mPipeFramesP2,
6898 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006899 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006900 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006901 }
6902 }
6903
Eric Laurentf14db3c2017-12-08 14:20:36 -08006904 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
6905 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
6906 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
6907 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
6908 lStatus = BAD_TYPE;
6909 goto Exit;
6910 }
6911
Glenn Kasten74105912014-07-03 12:28:53 -07006912 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006913 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006914 // fast track: frame count is exactly the pipe depth
6915 frameCount = mPipeFramesP2;
6916 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08006917 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07006918 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006919 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6920 // or 20 ms if there is a fast capture
6921 // TODO This could be a roundupRatio inline, and const
6922 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6923 * sampleRate + mSampleRate - 1) / mSampleRate;
6924 // minimum number of notification periods is at least kMinNotifications,
6925 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6926 static const size_t kMinNotifications = 3;
6927 static const uint32_t kMinMs = 30;
6928 // TODO This could be a roundupRatio inline
6929 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6930 // TODO This could be a roundupRatio inline
6931 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6932 maxNotificationFrames;
6933 const size_t minFrameCount = maxNotificationFrames *
6934 max(kMinNotifications, minNotificationsByMs);
6935 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08006936 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
6937 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006938 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006939 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006940 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006941 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006942
6943 { // scope for mLock
6944 Mutex::Autolock _l(mLock);
6945
Kevin Rocard1f564ac2018-03-29 13:53:10 -07006946 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07006947 format, channelMask, frameCount,
6948 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006949 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006950
Glenn Kasten03003332013-08-06 15:40:54 -07006951 lStatus = track->initCheck();
6952 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006953 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006954 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006955 goto Exit;
6956 }
6957 mTracks.add(track);
6958
Eric Laurent05067782016-06-01 18:27:28 -07006959 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006960 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6961 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6962 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006963 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006964 }
Eric Laurent81784c32012-11-19 14:55:58 -08006965 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006966
Eric Laurent81784c32012-11-19 14:55:58 -08006967 lStatus = NO_ERROR;
6968
6969Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006970 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006971 return track;
6972}
6973
6974status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6975 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006976 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006977{
6978 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6979 sp<ThreadBase> strongMe = this;
6980 status_t status = NO_ERROR;
6981
6982 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006983 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006984 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006985 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006986 triggerSession,
6987 recordTrack->sessionId(),
6988 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006989 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006990 // Sync event can be cancelled by the trigger session if the track is not in a
6991 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006992 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006993 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006994 } else {
6995 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08006996 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006997 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006998 }
6999 }
7000
7001 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007002 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007003 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007004 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7005 if (recordTrack->mState == TrackBase::PAUSING) {
7006 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007007 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007008 } else {
7009 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007010 }
7011 return status;
7012 }
7013
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007014 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7015 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7016 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007017 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007018 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007019 status_t status = NO_ERROR;
7020 if (recordTrack->isExternalTrack()) {
7021 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007022 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007023 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007024 mLock.lock();
7025 // FIXME should verify that recordTrack is still in mActiveTracks
7026 if (status != NO_ERROR) {
7027 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007028 recordTrack->clearSyncStartEvent();
7029 ALOGV("RecordThread::start error %d", status);
7030 return status;
7031 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007032 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007033 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007034 // Catch up with current buffer indices if thread is already running.
7035 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7036 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7037 // see previously buffered data before it called start(), but with greater risk of overrun.
7038
Andy Hung73c02e42015-03-29 01:13:58 -07007039 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07007040 // clear any converter state as new data will be discontinuous
7041 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007042 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007043 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007044 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007045 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007046 ALOGV("Record failed to start");
7047 status = BAD_VALUE;
7048 goto startError;
7049 }
Eric Laurent81784c32012-11-19 14:55:58 -08007050 return status;
7051 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007052
Eric Laurent81784c32012-11-19 14:55:58 -08007053startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007054 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007055 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007056 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007057 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007058 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007059 return status;
7060}
7061
Eric Laurent81784c32012-11-19 14:55:58 -08007062void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7063{
7064 sp<SyncEvent> strongEvent = event.promote();
7065
7066 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007067 sp<RefBase> ptr = strongEvent->cookie().promote();
7068 if (ptr != 0) {
7069 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7070 recordTrack->handleSyncStartEvent(strongEvent);
7071 }
Eric Laurent81784c32012-11-19 14:55:58 -08007072 }
7073}
7074
Glenn Kastena8356f62013-07-25 14:37:52 -07007075bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007076 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007077 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007078 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007079 return false;
7080 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007081 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007082 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007083 // signal thread to stop
7084 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007085 // do not wait for mStartStopCond if exiting
7086 if (exitPending()) {
7087 return true;
7088 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007089 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007090 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007091 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007092 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007093 ALOGV("Record stopped OK");
7094 return true;
7095 }
7096 return false;
7097}
7098
Glenn Kasten0f11b512014-01-31 16:18:54 -08007099bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007100{
7101 return false;
7102}
7103
Glenn Kasten0f11b512014-01-31 16:18:54 -08007104status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007105{
7106#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7107 if (!isValidSyncEvent(event)) {
7108 return BAD_VALUE;
7109 }
7110
Glenn Kastend848eb42016-03-08 13:42:11 -08007111 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007112 status_t ret = NAME_NOT_FOUND;
7113
7114 Mutex::Autolock _l(mLock);
7115
7116 for (size_t i = 0; i < mTracks.size(); i++) {
7117 sp<RecordTrack> track = mTracks[i];
7118 if (eventSession == track->sessionId()) {
7119 (void) track->setSyncEvent(event);
7120 ret = NO_ERROR;
7121 }
7122 }
7123 return ret;
7124#else
7125 return BAD_VALUE;
7126#endif
7127}
7128
jiabin653cc0a2018-01-17 17:54:10 -08007129status_t AudioFlinger::RecordThread::getActiveMicrophones(
7130 std::vector<media::MicrophoneInfo>* activeMicrophones)
7131{
7132 ALOGV("RecordThread::getActiveMicrophones");
7133 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007134 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7135 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007136}
7137
Eric Laurent81784c32012-11-19 14:55:58 -08007138// destroyTrack_l() must be called with ThreadBase::mLock held
7139void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7140{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007141 track->terminate();
7142 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007143 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007144 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007145 removeTrack_l(track);
7146 }
7147}
7148
7149void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7150{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007151 String8 result;
7152 track->appendDump(result, false /* active */);
7153 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7154
Eric Laurent81784c32012-11-19 14:55:58 -08007155 mTracks.remove(track);
7156 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007157 if (track->isFastTrack()) {
7158 ALOG_ASSERT(!mFastTrackAvail);
7159 mFastTrackAvail = true;
7160 }
Eric Laurent81784c32012-11-19 14:55:58 -08007161}
7162
7163void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7164{
7165 dumpInternals(fd, args);
7166 dumpTracks(fd, args);
7167 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007168 dprintf(fd, " Local log:\n");
7169 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007170}
7171
7172void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7173{
Glenn Kasten44182c22015-03-05 17:12:23 -08007174 dumpBase(fd, args);
7175
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007176 AudioStreamIn *input = mInput;
7177 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7178 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7179 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007180 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007181 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007182 }
Andy Hungbfa64962017-06-12 14:43:19 -07007183
7184 if (input != nullptr) {
7185 dprintf(fd, " Hal stream dump:\n");
7186 (void)input->stream->dump(fd);
7187 }
7188
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007189 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007190 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007191
Glenn Kasten2f90c512015-12-02 11:40:09 -08007192 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7193 // while we are dumping it. It may be inconsistent, but it won't mutate!
7194 // This is a large object so we place it on the heap.
7195 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7196 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7197 copy->dump(fd);
7198 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007199}
7200
Glenn Kasten0f11b512014-01-31 16:18:54 -08007201void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007202{
Eric Laurent81784c32012-11-19 14:55:58 -08007203 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007204 size_t numtracks = mTracks.size();
7205 size_t numactive = mActiveTracks.size();
7206 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007207 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007208 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007209 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007210 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007211 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08007212 RecordTrack::appendDumpHeader(result);
7213 for (size_t i = 0; i < numtracks ; ++i) {
7214 sp<RecordTrack> track = mTracks[i];
7215 if (track != 0) {
7216 bool active = mActiveTracks.indexOf(track) >= 0;
7217 if (active) {
7218 numactiveseen++;
7219 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007220 result.append(prefix);
7221 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007222 }
Eric Laurent81784c32012-11-19 14:55:58 -08007223 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007224 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007225 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007226 }
7227
Marco Nelissenb2208842014-02-07 14:00:50 -08007228 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007229 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007230 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007231 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08007232 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007233 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007234 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007235 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007236 result.append(prefix);
7237 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007238 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007239 }
Eric Laurent81784c32012-11-19 14:55:58 -08007240
7241 }
7242 write(fd, result.string(), result.size());
7243}
7244
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007245void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7246{
7247 Mutex::Autolock _l(mLock);
7248 for (size_t i = 0; i < mTracks.size() ; i++) {
7249 sp<RecordTrack> track = mTracks[i];
7250 if (track != 0 && track->uid() == uid) {
7251 track->setSilenced(silenced);
7252 }
7253 }
7254}
Andy Hung73c02e42015-03-29 01:13:58 -07007255
7256void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7257{
7258 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7259 RecordThread *recordThread = (RecordThread *) threadBase.get();
7260 mRsmpInFront = recordThread->mRsmpInRear;
7261 mRsmpInUnrel = 0;
7262}
7263
7264void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7265 size_t *framesAvailable, bool *hasOverrun)
7266{
7267 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7268 RecordThread *recordThread = (RecordThread *) threadBase.get();
7269 const int32_t rear = recordThread->mRsmpInRear;
7270 const int32_t front = mRsmpInFront;
7271 const ssize_t filled = rear - front;
7272
7273 size_t framesIn;
7274 bool overrun = false;
7275 if (filled < 0) {
7276 // should not happen, but treat like a massive overrun and re-sync
7277 framesIn = 0;
7278 mRsmpInFront = rear;
7279 overrun = true;
7280 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7281 framesIn = (size_t) filled;
7282 } else {
7283 // client is not keeping up with server, but give it latest data
7284 framesIn = recordThread->mRsmpInFrames;
7285 mRsmpInFront = /* front = */ rear - framesIn;
7286 overrun = true;
7287 }
7288 if (framesAvailable != NULL) {
7289 *framesAvailable = framesIn;
7290 }
7291 if (hasOverrun != NULL) {
7292 *hasOverrun = overrun;
7293 }
7294}
7295
Eric Laurent81784c32012-11-19 14:55:58 -08007296// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007297status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007298 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007299{
Andy Hung73c02e42015-03-29 01:13:58 -07007300 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007301 if (threadBase == 0) {
7302 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007303 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007304 return NOT_ENOUGH_DATA;
7305 }
7306 RecordThread *recordThread = (RecordThread *) threadBase.get();
7307 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007308 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007309 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007310 // FIXME should not be P2 (don't want to increase latency)
7311 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007312 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007313 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007314 front &= recordThread->mRsmpInFramesP2 - 1;
7315 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007316 if (part1 > (size_t) filled) {
7317 part1 = filled;
7318 }
7319 size_t ask = buffer->frameCount;
7320 ALOG_ASSERT(ask > 0);
7321 if (part1 > ask) {
7322 part1 = ask;
7323 }
7324 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007325 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007326 buffer->raw = NULL;
7327 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007328 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007329 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007330 }
7331
Andy Hung57446612015-04-19 23:56:46 -07007332 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007333 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007334 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007335 return NO_ERROR;
7336}
7337
7338// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007339void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7340 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007341{
Glenn Kasten85948432013-08-19 12:09:05 -07007342 size_t stepCount = buffer->frameCount;
7343 if (stepCount == 0) {
7344 return;
7345 }
Andy Hung73c02e42015-03-29 01:13:58 -07007346 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7347 mRsmpInUnrel -= stepCount;
7348 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007349 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007350 buffer->frameCount = 0;
7351}
7352
Eric Laurentd8365c52017-07-16 15:27:05 -07007353void AudioFlinger::RecordThread::checkBtNrec()
7354{
7355 Mutex::Autolock _l(mLock);
7356 checkBtNrec_l();
7357}
7358
7359void AudioFlinger::RecordThread::checkBtNrec_l()
7360{
7361 // disable AEC and NS if the device is a BT SCO headset supporting those
7362 // pre processings
7363 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7364 mAudioFlinger->btNrecIsOff();
7365 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7366 for (size_t i = 0; i < mEffectChains.size(); i++) {
7367 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7368 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7369 }
7370 }
7371}
7372
Andy Hung97a893e2015-03-29 01:03:07 -07007373
Eric Laurent10351942014-05-08 18:49:52 -07007374bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7375 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007376{
7377 bool reconfig = false;
7378
Eric Laurent10351942014-05-08 18:49:52 -07007379 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007380
Eric Laurent10351942014-05-08 18:49:52 -07007381 audio_format_t reqFormat = mFormat;
7382 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007383 // 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 -07007384 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7385
7386 AudioParameter param = AudioParameter(keyValuePair);
7387 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007388
7389 // scope for AutoPark extends to end of method
7390 AutoPark<FastCapture> park(mFastCapture);
7391
Eric Laurent10351942014-05-08 18:49:52 -07007392 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7393 // channel count change can be requested. Do we mandate the first client defines the
7394 // HAL sampling rate and channel count or do we allow changes on the fly?
7395 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7396 samplingRate = value;
7397 reconfig = true;
7398 }
7399 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007400 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007401 status = BAD_VALUE;
7402 } else {
7403 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007404 reconfig = true;
7405 }
Eric Laurent10351942014-05-08 18:49:52 -07007406 }
7407 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7408 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007409 if (!audio_is_input_channel(mask) ||
7410 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007411 status = BAD_VALUE;
7412 } else {
7413 channelMask = mask;
7414 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007415 }
Eric Laurent10351942014-05-08 18:49:52 -07007416 }
7417 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7418 // do not accept frame count changes if tracks are open as the track buffer
7419 // size depends on frame count and correct behavior would not be guaranteed
7420 // if frame count is changed after track creation
7421 if (mActiveTracks.size() > 0) {
7422 status = INVALID_OPERATION;
7423 } else {
7424 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007425 }
Eric Laurent10351942014-05-08 18:49:52 -07007426 }
7427 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7428 // forward device change to effects that have requested to be
7429 // aware of attached audio device.
7430 for (size_t i = 0; i < mEffectChains.size(); i++) {
7431 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007432 }
Eric Laurent81784c32012-11-19 14:55:58 -08007433
Eric Laurent10351942014-05-08 18:49:52 -07007434 // store input device and output device but do not forward output device to audio HAL.
7435 // Note that status is ignored by the caller for output device
7436 // (see AudioFlinger::setParameters()
7437 if (audio_is_output_devices(value)) {
7438 mOutDevice = value;
7439 status = BAD_VALUE;
7440 } else {
7441 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007442 if (value != AUDIO_DEVICE_NONE) {
7443 mPrevInDevice = value;
7444 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007445 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007446 }
Eric Laurent10351942014-05-08 18:49:52 -07007447 }
7448 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7449 mAudioSource != (audio_source_t)value) {
7450 // forward device change to effects that have requested to be
7451 // aware of attached audio device.
7452 for (size_t i = 0; i < mEffectChains.size(); i++) {
7453 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007454 }
Eric Laurent10351942014-05-08 18:49:52 -07007455 mAudioSource = (audio_source_t)value;
7456 }
Glenn Kastene198c362013-08-13 09:13:36 -07007457
Eric Laurent10351942014-05-08 18:49:52 -07007458 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007459 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007460 if (status == INVALID_OPERATION) {
7461 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007462 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007463 }
7464 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007465 if (status == BAD_VALUE) {
7466 uint32_t sRate;
7467 audio_channel_mask_t channelMask;
7468 audio_format_t format;
7469 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7470 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7471 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7472 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7473 status = NO_ERROR;
7474 }
Eric Laurent81784c32012-11-19 14:55:58 -08007475 }
Eric Laurent10351942014-05-08 18:49:52 -07007476 if (status == NO_ERROR) {
7477 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007478 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007479 }
7480 }
Eric Laurent81784c32012-11-19 14:55:58 -08007481 }
Eric Laurent10351942014-05-08 18:49:52 -07007482
Eric Laurent81784c32012-11-19 14:55:58 -08007483 return reconfig;
7484}
7485
7486String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7487{
Eric Laurent81784c32012-11-19 14:55:58 -08007488 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007489 if (initCheck() == NO_ERROR) {
7490 String8 out_s8;
7491 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7492 return out_s8;
7493 }
Eric Laurent81784c32012-11-19 14:55:58 -08007494 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007495 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007496}
7497
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007498void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007499 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7500
7501 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007502
7503 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007504 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007505 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007506 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007507 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007508 desc->mChannelMask = mChannelMask;
7509 desc->mSamplingRate = mSampleRate;
7510 desc->mFormat = mFormat;
7511 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007512 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007513 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007514 break;
7515
Eric Laurent73e26b62015-04-27 16:55:58 -07007516 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007517 default:
7518 break;
7519 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007520 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007521}
7522
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007523void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007524{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007525 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7526 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007527 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007528 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007529 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007530 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7531 result = mInput->stream->getFrameSize(&mFrameSize);
7532 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7533 result = mInput->stream->getBufferSize(&mBufferSize);
7534 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007535 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007536 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7537 "mBufferSize=%lld, mFrameCount=%lld",
7538 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7539 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007540 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007541 // 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 -07007542 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007543 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007544 // A larger value should allow more old data to be read after a track calls start(),
7545 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007546 //
7547 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007548 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007549 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007550 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007551 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007552
7553 // TODO optimize audio capture buffer sizes ...
7554 // Here we calculate the size of the sliding buffer used as a source
7555 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7556 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7557 // be better to have it derived from the pipe depth in the long term.
7558 // The current value is higher than necessary. However it should not add to latency.
7559
Glenn Kasten85948432013-08-19 12:09:05 -07007560 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007561 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7562 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007563 // if posix_memalign fails, will segv here.
7564 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007565
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007566 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7567 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007568}
7569
Glenn Kasten5f972c02014-01-13 09:59:31 -08007570uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007571{
7572 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007573 uint32_t result;
7574 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7575 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007576 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007577 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007578}
7579
Eric Laurent4c415062016-06-17 16:14:16 -07007580// hasAudioSession_l() must be called with ThreadBase::mLock held
7581uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007582{
Eric Laurent81784c32012-11-19 14:55:58 -08007583 uint32_t result = 0;
7584 if (getEffectChain_l(sessionId) != 0) {
7585 result = EFFECT_SESSION;
7586 }
7587
7588 for (size_t i = 0; i < mTracks.size(); ++i) {
7589 if (sessionId == mTracks[i]->sessionId()) {
7590 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007591 if (mTracks[i]->isFastTrack()) {
7592 result |= FAST_SESSION;
7593 }
Eric Laurent81784c32012-11-19 14:55:58 -08007594 break;
7595 }
7596 }
7597
7598 return result;
7599}
7600
Glenn Kastend848eb42016-03-08 13:42:11 -08007601KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007602{
Glenn Kastend848eb42016-03-08 13:42:11 -08007603 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007604 Mutex::Autolock _l(mLock);
7605 for (size_t j = 0; j < mTracks.size(); ++j) {
7606 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007607 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007608 if (ids.indexOfKey(sessionId) < 0) {
7609 ids.add(sessionId, true);
7610 }
7611 }
7612 return ids;
7613}
7614
7615AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7616{
7617 Mutex::Autolock _l(mLock);
7618 AudioStreamIn *input = mInput;
7619 mInput = NULL;
7620 return input;
7621}
7622
7623// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007624sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007625{
7626 if (mInput == NULL) {
7627 return NULL;
7628 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007629 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007630}
7631
7632status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7633{
7634 // only one chain per input thread
7635 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007636 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007637 return INVALID_OPERATION;
7638 }
7639 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007640 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007641 chain->setInBuffer(NULL);
7642 chain->setOutBuffer(NULL);
7643
7644 checkSuspendOnAddEffectChain_l(chain);
7645
Eric Laurent1b928682014-10-02 19:41:47 -07007646 // make sure enabled pre processing effects state is communicated to the HAL as we
7647 // just moved them to a new input stream.
7648 chain->syncHalEffectsState();
7649
Eric Laurent81784c32012-11-19 14:55:58 -08007650 mEffectChains.add(chain);
7651
7652 return NO_ERROR;
7653}
7654
7655size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7656{
7657 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7658 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007659 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007660 chain.get(), mEffectChains.size(), this);
7661 if (mEffectChains.size() == 1) {
7662 mEffectChains.removeAt(0);
7663 }
7664 return 0;
7665}
7666
Eric Laurent1c333e22014-05-20 10:48:17 -07007667status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7668 audio_patch_handle_t *handle)
7669{
7670 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007671
7672 // store new device and send to effects
7673 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007674 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007675 for (size_t i = 0; i < mEffectChains.size(); i++) {
7676 mEffectChains[i]->setDevice_l(mInDevice);
7677 }
7678
Eric Laurentd8365c52017-07-16 15:27:05 -07007679 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007680
7681 // store new source and send to effects
7682 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7683 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007684 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007685 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007686 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007687 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007688
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007689 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007690 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7691 status = hwDevice->createAudioPatch(patch->num_sources,
7692 patch->sources,
7693 patch->num_sinks,
7694 patch->sinks,
7695 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007696 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007697 char *address;
7698 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7699 address = audio_device_address_to_parameter(
7700 patch->sources[0].ext.device.type,
7701 patch->sources[0].ext.device.address);
7702 } else {
7703 address = (char *)calloc(1, 1);
7704 }
7705 AudioParameter param = AudioParameter(String8(address));
7706 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007707 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007708 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007709 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007710 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007711 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007712 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007713 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007714
Eric Laurente8726fe2015-06-26 09:39:24 -07007715 if (mInDevice != mPrevInDevice) {
7716 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7717 mPrevInDevice = mInDevice;
7718 }
Eric Laurent296fb132015-05-01 11:38:42 -07007719
Eric Laurent1c333e22014-05-20 10:48:17 -07007720 return status;
7721}
7722
7723status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7724{
7725 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007726
7727 mInDevice = AUDIO_DEVICE_NONE;
7728
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007729 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007730 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7731 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007732 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007733 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007734 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007735 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007736 }
7737 return status;
7738}
7739
Eric Laurent83b88082014-06-20 18:31:16 -07007740void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7741{
7742 Mutex::Autolock _l(mLock);
7743 mTracks.add(record);
7744}
7745
7746void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7747{
7748 Mutex::Autolock _l(mLock);
7749 destroyTrack_l(record);
7750}
7751
7752void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7753{
7754 ThreadBase::getAudioPortConfig(config);
7755 config->role = AUDIO_PORT_ROLE_SINK;
7756 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7757 config->ext.mix.usecase.source = mAudioSource;
7758}
Eric Laurent1c333e22014-05-20 10:48:17 -07007759
Eric Laurent6acd1d42017-01-04 14:23:29 -08007760// ----------------------------------------------------------------------------
7761// Mmap
7762// ----------------------------------------------------------------------------
7763
7764AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7765 : mThread(thread)
7766{
Phil Burk9fabbf82017-08-03 12:02:00 -07007767 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007768}
7769
7770AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7771{
Phil Burk9fabbf82017-08-03 12:02:00 -07007772 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007773}
7774
7775status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7776 struct audio_mmap_buffer_info *info)
7777{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007778 return mThread->createMmapBuffer(minSizeFrames, info);
7779}
7780
7781status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7782{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007783 return mThread->getMmapPosition(position);
7784}
7785
Eric Laurenta54f1282017-07-01 19:39:32 -07007786status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007787 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007788
7789{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007790 return mThread->start(client, handle);
7791}
7792
7793status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7794{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007795 return mThread->stop(handle);
7796}
7797
Eric Laurent18b57012017-02-13 16:23:52 -08007798status_t AudioFlinger::MmapThreadHandle::standby()
7799{
Eric Laurent18b57012017-02-13 16:23:52 -08007800 return mThread->standby();
7801}
7802
Eric Laurent6acd1d42017-01-04 14:23:29 -08007803
7804AudioFlinger::MmapThread::MmapThread(
7805 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7806 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7807 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7808 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007809 mSessionId(AUDIO_SESSION_NONE),
7810 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007811 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
7812 mActiveTracks(&this->mLocalLog)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007813{
Eric Laurent18b57012017-02-13 16:23:52 -08007814 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007815 readHalParameters_l();
7816}
7817
7818AudioFlinger::MmapThread::~MmapThread()
7819{
Eric Laurent18b57012017-02-13 16:23:52 -08007820 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007821}
7822
7823void AudioFlinger::MmapThread::onFirstRef()
7824{
7825 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7826}
7827
7828void AudioFlinger::MmapThread::disconnect()
7829{
7830 for (const sp<MmapTrack> &t : mActiveTracks) {
7831 stop(t->portId());
7832 }
Phil Burk9fabbf82017-08-03 12:02:00 -07007833 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08007834 if (isOutput()) {
7835 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7836 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08007837 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007838 }
7839}
7840
7841
7842void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7843 audio_stream_type_t streamType __unused,
7844 audio_session_t sessionId,
7845 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007846 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007847 audio_port_handle_t portId)
7848{
7849 mAttr = *attr;
7850 mSessionId = sessionId;
7851 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007852 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007853 mPortId = portId;
7854}
7855
7856status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7857 struct audio_mmap_buffer_info *info)
7858{
7859 if (mHalStream == 0) {
7860 return NO_INIT;
7861 }
Eric Laurent18b57012017-02-13 16:23:52 -08007862 mStandby = true;
7863 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007864 return mHalStream->createMmapBuffer(minSizeFrames, info);
7865}
7866
7867status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7868{
7869 if (mHalStream == 0) {
7870 return NO_INIT;
7871 }
7872 return mHalStream->getMmapPosition(position);
7873}
7874
Eric Laurenta54f1282017-07-01 19:39:32 -07007875status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007876 audio_port_handle_t *handle)
7877{
Eric Laurenta54f1282017-07-01 19:39:32 -07007878 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7879 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007880 if (mHalStream == 0) {
7881 return NO_INIT;
7882 }
7883
7884 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007885
Eric Laurenta54f1282017-07-01 19:39:32 -07007886 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007887 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007888 ret = mHalStream->start();
7889 if (ret != NO_ERROR) {
7890 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7891 return ret;
7892 }
Eric Laurent18b57012017-02-13 16:23:52 -08007893 mStandby = false;
Eric Laurenta54f1282017-07-01 19:39:32 -07007894 return NO_ERROR;
7895 }
7896
7897 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7898
7899 audio_io_handle_t io = mId;
7900 if (isOutput()) {
7901 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7902 config.sample_rate = mSampleRate;
7903 config.channel_mask = mChannelMask;
7904 config.format = mFormat;
7905 audio_stream_type_t stream = streamType();
7906 audio_output_flags_t flags =
7907 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007908 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007909 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7910 mSessionId,
7911 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02007912 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07007913 client.clientUid,
7914 &config,
7915 flags,
7916 &deviceId,
7917 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007918 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007919 audio_config_base_t config;
7920 config.sample_rate = mSampleRate;
7921 config.channel_mask = mChannelMask;
7922 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007923 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007924 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7925 mSessionId,
7926 client.clientPid,
7927 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08007928 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07007929 &config,
7930 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7931 &deviceId,
7932 &portId);
7933 }
7934 // APM should not chose a different input or output stream for the same set of attributes
7935 // and audo configuration
7936 if (ret != NO_ERROR || io != mId) {
7937 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7938 __FUNCTION__, ret, io, mId);
7939 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007940 }
7941
7942 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007943 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007944 } else {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007945 // TODO: Block recording for idle UIDs (b/72134552)
7946 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007947 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007948 }
7949
7950 // abort if start is rejected by audio policy manager
7951 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007952 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007953 if (mActiveTracks.size() != 0) {
7954 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007955 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007956 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08007957 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007958 }
Eric Laurent18b57012017-02-13 16:23:52 -08007959 } else {
7960 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007961 }
7962 return PERMISSION_DENIED;
7963 }
7964
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007965 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
7966 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -07007967 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007968
7969 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07007970 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007971 if (chain != 0) {
7972 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7973 chain->incTrackCnt();
7974 chain->incActiveTrackCnt();
7975 }
7976
7977 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007978 broadcast_l();
7979
Eric Laurenta54f1282017-07-01 19:39:32 -07007980 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007981
7982 return NO_ERROR;
7983}
7984
7985status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7986{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007987 ALOGV("%s handle %d", __FUNCTION__, handle);
7988
7989 if (mHalStream == 0) {
7990 return NO_INIT;
7991 }
7992
Eric Laurenta54f1282017-07-01 19:39:32 -07007993 if (handle == mPortId) {
7994 mHalStream->stop();
7995 return NO_ERROR;
7996 }
7997
Eric Laurent6acd1d42017-01-04 14:23:29 -08007998 sp<MmapTrack> track;
7999 for (const sp<MmapTrack> &t : mActiveTracks) {
8000 if (handle == t->portId()) {
8001 track = t;
8002 break;
8003 }
8004 }
8005 if (track == 0) {
8006 return BAD_VALUE;
8007 }
8008
8009 mActiveTracks.remove(track);
8010
8011 if (isOutput()) {
8012 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07008013 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008014 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008015 AudioSystem::stopInput(track->portId());
8016 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008017 }
8018
8019 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8020 if (chain != 0) {
8021 chain->decActiveTrackCnt();
8022 chain->decTrackCnt();
8023 }
8024
8025 broadcast_l();
8026
Eric Laurent6acd1d42017-01-04 14:23:29 -08008027 return NO_ERROR;
8028}
8029
Eric Laurent18b57012017-02-13 16:23:52 -08008030status_t AudioFlinger::MmapThread::standby()
8031{
8032 ALOGV("%s", __FUNCTION__);
8033
8034 if (mHalStream == 0) {
8035 return NO_INIT;
8036 }
8037 if (mActiveTracks.size() != 0) {
8038 return INVALID_OPERATION;
8039 }
8040 mHalStream->standby();
8041 mStandby = true;
8042 releaseWakeLock();
8043 return NO_ERROR;
8044}
8045
Eric Laurent6acd1d42017-01-04 14:23:29 -08008046
8047void AudioFlinger::MmapThread::readHalParameters_l()
8048{
8049 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8050 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8051 mFormat = mHALFormat;
8052 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8053 result = mHalStream->getFrameSize(&mFrameSize);
8054 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8055 result = mHalStream->getBufferSize(&mBufferSize);
8056 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8057 mFrameCount = mBufferSize / mFrameSize;
8058}
8059
8060bool AudioFlinger::MmapThread::threadLoop()
8061{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008062 checkSilentMode_l();
8063
8064 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8065
8066 while (!exitPending())
8067 {
8068 Mutex::Autolock _l(mLock);
8069 Vector< sp<EffectChain> > effectChains;
8070
8071 if (mSignalPending) {
8072 // A signal was raised while we were unlocked
8073 mSignalPending = false;
8074 } else {
8075 if (mConfigEvents.isEmpty()) {
8076 // we're about to wait, flush the binder command buffer
8077 IPCThreadState::self()->flushCommands();
8078
8079 if (exitPending()) {
8080 break;
8081 }
8082
Eric Laurent6acd1d42017-01-04 14:23:29 -08008083 // wait until we have something to do...
8084 ALOGV("%s going to sleep", myName.string());
8085 mWaitWorkCV.wait(mLock);
8086 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008087
8088 checkSilentMode_l();
8089
8090 continue;
8091 }
8092 }
8093
8094 processConfigEvents_l();
8095
8096 processVolume_l();
8097
8098 checkInvalidTracks_l();
8099
8100 mActiveTracks.updatePowerState(this);
8101
8102 lockEffectChains_l(effectChains);
8103 for (size_t i = 0; i < effectChains.size(); i ++) {
8104 effectChains[i]->process_l();
8105 }
8106 // enable changes in effect chain
8107 unlockEffectChains(effectChains);
8108 // Effect chains will be actually deleted here if they were removed from
8109 // mEffectChains list during mixing or effects processing
8110 }
8111
8112 threadLoop_exit();
8113
8114 if (!mStandby) {
8115 threadLoop_standby();
8116 mStandby = true;
8117 }
8118
Eric Laurent6acd1d42017-01-04 14:23:29 -08008119 ALOGV("Thread %p type %d exiting", this, mType);
8120 return false;
8121}
8122
8123// checkForNewParameter_l() must be called with ThreadBase::mLock held
8124bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8125 status_t& status)
8126{
8127 AudioParameter param = AudioParameter(keyValuePair);
8128 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008129 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008130 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008131 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008132 // forward device change to effects that have requested to be
8133 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008134 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008135 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008136 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008137 }
8138 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008139 if (audio_is_output_devices(device)) {
8140 mOutDevice = device;
8141 if (!isOutput()) {
8142 sendToHal = false;
8143 }
8144 } else {
8145 mInDevice = device;
8146 if (device != AUDIO_DEVICE_NONE) {
8147 mPrevInDevice = value;
8148 }
8149 // TODO: implement and call checkBtNrec_l();
8150 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008151 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008152 if (sendToHal) {
8153 status = mHalStream->setParameters(keyValuePair);
8154 } else {
8155 status = NO_ERROR;
8156 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008157
8158 return false;
8159}
8160
8161String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8162{
8163 Mutex::Autolock _l(mLock);
8164 String8 out_s8;
8165 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8166 return out_s8;
8167 }
8168 return String8();
8169}
8170
8171void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8172 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8173
8174 desc->mIoHandle = mId;
8175
8176 switch (event) {
8177 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008178 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008179 case AUDIO_INPUT_CONFIG_CHANGED:
8180 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008181 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008182 case AUDIO_OUTPUT_CONFIG_CHANGED:
8183 desc->mPatch = mPatch;
8184 desc->mChannelMask = mChannelMask;
8185 desc->mSamplingRate = mSampleRate;
8186 desc->mFormat = mFormat;
8187 desc->mFrameCount = mFrameCount;
8188 desc->mFrameCountHAL = mFrameCount;
8189 desc->mLatency = 0;
8190 break;
8191
8192 case AUDIO_INPUT_CLOSED:
8193 case AUDIO_OUTPUT_CLOSED:
8194 default:
8195 break;
8196 }
8197 mAudioFlinger->ioConfigChanged(event, desc, pid);
8198}
8199
8200status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8201 audio_patch_handle_t *handle)
8202{
8203 status_t status = NO_ERROR;
8204
8205 // store new device and send to effects
8206 audio_devices_t type = AUDIO_DEVICE_NONE;
8207 audio_port_handle_t deviceId;
8208 if (isOutput()) {
8209 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8210 type |= patch->sinks[i].ext.device.type;
8211 }
8212 deviceId = patch->sinks[0].id;
8213 } else {
8214 type = patch->sources[0].ext.device.type;
8215 deviceId = patch->sources[0].id;
8216 }
8217
8218 for (size_t i = 0; i < mEffectChains.size(); i++) {
8219 mEffectChains[i]->setDevice_l(type);
8220 }
8221
8222 if (isOutput()) {
8223 mOutDevice = type;
8224 } else {
8225 mInDevice = type;
8226 // store new source and send to effects
8227 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8228 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8229 for (size_t i = 0; i < mEffectChains.size(); i++) {
8230 mEffectChains[i]->setAudioSource_l(mAudioSource);
8231 }
8232 }
8233 }
8234
8235 if (mAudioHwDev->supportsAudioPatches()) {
8236 status = mHalDevice->createAudioPatch(patch->num_sources,
8237 patch->sources,
8238 patch->num_sinks,
8239 patch->sinks,
8240 handle);
8241 } else {
8242 char *address;
8243 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8244 //FIXME: we only support address on first sink with HAL version < 3.0
8245 address = audio_device_address_to_parameter(
8246 patch->sinks[0].ext.device.type,
8247 patch->sinks[0].ext.device.address);
8248 } else {
8249 address = (char *)calloc(1, 1);
8250 }
8251 AudioParameter param = AudioParameter(String8(address));
8252 free(address);
8253 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8254 if (!isOutput()) {
8255 param.addInt(String8(AudioParameter::keyInputSource),
8256 (int)patch->sinks[0].ext.mix.usecase.source);
8257 }
8258 status = mHalStream->setParameters(param.toString());
8259 *handle = AUDIO_PATCH_HANDLE_NONE;
8260 }
8261
8262 if (isOutput() && mPrevOutDevice != mOutDevice) {
8263 mPrevOutDevice = type;
8264 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008265 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008266 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008267 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008268 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008269 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008270 }
8271 if (!isOutput() && mPrevInDevice != mInDevice) {
8272 mPrevInDevice = type;
8273 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008274 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008275 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008276 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008277 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008278 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008279 }
8280 return status;
8281}
8282
8283status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8284{
8285 status_t status = NO_ERROR;
8286
8287 mInDevice = AUDIO_DEVICE_NONE;
8288
8289 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8290 supportsAudioPatches : false;
8291
8292 if (supportsAudioPatches) {
8293 status = mHalDevice->releaseAudioPatch(handle);
8294 } else {
8295 AudioParameter param;
8296 param.addInt(String8(AudioParameter::keyRouting), 0);
8297 status = mHalStream->setParameters(param.toString());
8298 }
8299 return status;
8300}
8301
8302void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8303{
8304 ThreadBase::getAudioPortConfig(config);
8305 if (isOutput()) {
8306 config->role = AUDIO_PORT_ROLE_SOURCE;
8307 config->ext.mix.hw_module = mAudioHwDev->handle();
8308 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8309 } else {
8310 config->role = AUDIO_PORT_ROLE_SINK;
8311 config->ext.mix.hw_module = mAudioHwDev->handle();
8312 config->ext.mix.usecase.source = mAudioSource;
8313 }
8314}
8315
8316status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8317{
8318 audio_session_t session = chain->sessionId();
8319
8320 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8321 // Attach all tracks with same session ID to this chain.
8322 // indicate all active tracks in the chain
8323 for (const sp<MmapTrack> &track : mActiveTracks) {
8324 if (session == track->sessionId()) {
8325 chain->incTrackCnt();
8326 chain->incActiveTrackCnt();
8327 }
8328 }
8329
8330 chain->setThread(this);
8331 chain->setInBuffer(nullptr);
8332 chain->setOutBuffer(nullptr);
8333 chain->syncHalEffectsState();
8334
8335 mEffectChains.add(chain);
8336 checkSuspendOnAddEffectChain_l(chain);
8337 return NO_ERROR;
8338}
8339
8340size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8341{
8342 audio_session_t session = chain->sessionId();
8343
8344 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8345
8346 for (size_t i = 0; i < mEffectChains.size(); i++) {
8347 if (chain == mEffectChains[i]) {
8348 mEffectChains.removeAt(i);
8349 // detach all active tracks from the chain
8350 // detach all tracks with same session ID from this chain
8351 for (const sp<MmapTrack> &track : mActiveTracks) {
8352 if (session == track->sessionId()) {
8353 chain->decActiveTrackCnt();
8354 chain->decTrackCnt();
8355 }
8356 }
8357 break;
8358 }
8359 }
8360 return mEffectChains.size();
8361}
8362
8363// hasAudioSession_l() must be called with ThreadBase::mLock held
8364uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8365{
8366 uint32_t result = 0;
8367 if (getEffectChain_l(sessionId) != 0) {
8368 result = EFFECT_SESSION;
8369 }
8370
8371 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8372 sp<MmapTrack> track = mActiveTracks[i];
8373 if (sessionId == track->sessionId()) {
8374 result |= TRACK_SESSION;
8375 if (track->isFastTrack()) {
8376 result |= FAST_SESSION;
8377 }
8378 break;
8379 }
8380 }
8381
8382 return result;
8383}
8384
8385void AudioFlinger::MmapThread::threadLoop_standby()
8386{
8387 mHalStream->standby();
8388}
8389
8390void AudioFlinger::MmapThread::threadLoop_exit()
8391{
Phil Burk7dce7282017-09-27 13:51:41 -07008392 // Do not call callback->onTearDown() because it is redundant for thread exit
8393 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008394}
8395
8396status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8397{
8398 return BAD_VALUE;
8399}
8400
8401bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8402{
8403 return false;
8404}
8405
8406status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8407 const effect_descriptor_t *desc, audio_session_t sessionId)
8408{
8409 // No global effect sessions on mmap threads
8410 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8411 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8412 desc->name, mThreadName);
8413 return BAD_VALUE;
8414 }
8415
8416 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8417 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8418 desc->name);
8419 return BAD_VALUE;
8420 }
8421 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008422 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8423 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008424 return BAD_VALUE;
8425 }
8426
8427 // Only allow effects without processing load or latency
8428 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8429 return BAD_VALUE;
8430 }
8431
8432 return NO_ERROR;
8433
8434}
8435
8436void AudioFlinger::MmapThread::checkInvalidTracks_l()
8437{
8438 for (const sp<MmapTrack> &track : mActiveTracks) {
8439 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008440 sp<MmapStreamCallback> callback = mCallback.promote();
8441 if (callback != 0) {
8442 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008443 }
8444 break;
8445 }
8446 }
8447}
8448
8449void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8450{
8451 dumpInternals(fd, args);
8452 dumpTracks(fd, args);
8453 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008454 dprintf(fd, " Local log:\n");
8455 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008456}
8457
8458void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8459{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008460 dumpBase(fd, args);
8461
8462 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8463 mAttr.content_type, mAttr.usage, mAttr.source);
8464 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8465 if (mActiveTracks.size() == 0) {
8466 dprintf(fd, " No active clients\n");
8467 }
8468}
8469
8470void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8471{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008472 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008473 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008474 dprintf(fd, " %zu Tracks\n", numtracks);
8475 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008476 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008477 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008478 MmapTrack::appendDumpHeader(result);
8479 for (size_t i = 0; i < numtracks ; ++i) {
8480 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008481 result.append(prefix);
8482 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008483 }
8484 } else {
8485 dprintf(fd, "\n");
8486 }
8487 write(fd, result.string(), result.size());
8488}
8489
8490AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8491 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8492 AudioHwDevice *hwDev, AudioStreamOut *output,
8493 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8494 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8495 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008496 mStreamVolume(1.0),
8497 mStreamMute(false),
8498 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8499 mNoCallbackWarningCount(0),
8500 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008501{
8502 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8503 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8504 mMasterVolume = audioFlinger->masterVolume_l();
8505 mMasterMute = audioFlinger->masterMute_l();
8506 if (mAudioHwDev) {
8507 if (mAudioHwDev->canSetMasterVolume()) {
8508 mMasterVolume = 1.0;
8509 }
8510
8511 if (mAudioHwDev->canSetMasterMute()) {
8512 mMasterMute = false;
8513 }
8514 }
8515}
8516
8517void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8518 audio_stream_type_t streamType,
8519 audio_session_t sessionId,
8520 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008521 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008522 audio_port_handle_t portId)
8523{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008524 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008525 mStreamType = streamType;
8526}
8527
8528AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8529{
8530 Mutex::Autolock _l(mLock);
8531 AudioStreamOut *output = mOutput;
8532 mOutput = NULL;
8533 return output;
8534}
8535
8536void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8537{
8538 Mutex::Autolock _l(mLock);
8539 // Don't apply master volume in SW if our HAL can do it for us.
8540 if (mAudioHwDev &&
8541 mAudioHwDev->canSetMasterVolume()) {
8542 mMasterVolume = 1.0;
8543 } else {
8544 mMasterVolume = value;
8545 }
8546}
8547
8548void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8549{
8550 Mutex::Autolock _l(mLock);
8551 // Don't apply master mute in SW if our HAL can do it for us.
8552 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8553 mMasterMute = false;
8554 } else {
8555 mMasterMute = muted;
8556 }
8557}
8558
8559void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8560{
8561 Mutex::Autolock _l(mLock);
8562 if (stream == mStreamType) {
8563 mStreamVolume = value;
8564 broadcast_l();
8565 }
8566}
8567
8568float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8569{
8570 Mutex::Autolock _l(mLock);
8571 if (stream == mStreamType) {
8572 return mStreamVolume;
8573 }
8574 return 0.0f;
8575}
8576
8577void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8578{
8579 Mutex::Autolock _l(mLock);
8580 if (stream == mStreamType) {
8581 mStreamMute= muted;
8582 broadcast_l();
8583 }
8584}
8585
8586void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8587{
8588 Mutex::Autolock _l(mLock);
8589 if (streamType == mStreamType) {
8590 for (const sp<MmapTrack> &track : mActiveTracks) {
8591 track->invalidate();
8592 }
8593 broadcast_l();
8594 }
8595}
8596
8597void AudioFlinger::MmapPlaybackThread::processVolume_l()
8598{
8599 float volume;
8600
8601 if (mMasterMute || mStreamMute) {
8602 volume = 0;
8603 } else {
8604 volume = mMasterVolume * mStreamVolume;
8605 }
8606
8607 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008608
8609 // Convert volumes from float to 8.24
8610 uint32_t vol = (uint32_t)(volume * (1 << 24));
8611
8612 // Delegate volume control to effect in track effect chain if needed
8613 // only one effect chain can be present on DirectOutputThread, so if
8614 // there is one, the track is connected to it
8615 if (!mEffectChains.isEmpty()) {
8616 mEffectChains[0]->setVolume_l(&vol, &vol);
8617 volume = (float)vol / (1 << 24);
8618 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008619 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008620 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8621 mHalVolFloat = volume; // HW volume control worked, so update value.
8622 mNoCallbackWarningCount = 0;
8623 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008624 sp<MmapStreamCallback> callback = mCallback.promote();
8625 if (callback != 0) {
8626 int channelCount;
8627 if (isOutput()) {
8628 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8629 } else {
8630 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8631 }
8632 Vector<float> values;
8633 for (int i = 0; i < channelCount; i++) {
8634 values.add(volume);
8635 }
8636 callback->onVolumeChanged(mChannelMask, values);
Phil Burk56ecf3e2018-03-12 15:38:17 -07008637 mHalVolFloat = volume; // SW volume control worked, so update value.
8638 mNoCallbackWarningCount = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008639 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008640 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8641 ALOGW("Could not set MMAP stream volume: no volume callback!");
8642 mNoCallbackWarningCount++;
8643 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008644 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008645 }
8646 }
8647}
8648
8649void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8650{
8651 if (!mMasterMute) {
8652 char value[PROPERTY_VALUE_MAX];
8653 if (property_get("ro.audio.silent", value, "0") > 0) {
8654 char *endptr;
8655 unsigned long ul = strtoul(value, &endptr, 0);
8656 if (*endptr == '\0' && ul != 0) {
8657 ALOGD("Silence is golden");
8658 // The setprop command will not allow a property to be changed after
8659 // the first time it is set, so we don't have to worry about un-muting.
8660 setMasterMute_l(true);
8661 }
8662 }
8663 }
8664}
8665
8666void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8667{
8668 MmapThread::dumpInternals(fd, args);
8669
Glenn Kastend3bb6452016-12-05 18:14:37 -08008670 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8671 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008672 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8673}
8674
8675AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8676 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8677 AudioHwDevice *hwDev, AudioStreamIn *input,
8678 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8679 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8680 mInput(input)
8681{
8682 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8683 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8684}
8685
8686AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8687{
8688 Mutex::Autolock _l(mLock);
8689 AudioStreamIn *input = mInput;
8690 mInput = NULL;
8691 return input;
8692}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008693} // namespace android