blob: 85d2335f9f9bb5f30a55f370d3615b14351f517b [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>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070032#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080034#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080035
36#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070037#include <private/android_filesystem_config.h>
Andy Hung2ddee192015-12-18 17:34:44 -080038#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080039#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070042#include <system/audio_effects/effect_ns.h>
43#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045
46// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070047#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080048#include <media/nbaio/AudioStreamOutSink.h>
49#include <media/nbaio/MonoPipe.h>
50#include <media/nbaio/MonoPipeReader.h>
51#include <media/nbaio/Pipe.h>
52#include <media/nbaio/PipeReader.h>
53#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080054#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080055
56#include <powermanager/PowerManager.h>
57
Eric Laurent81784c32012-11-19 14:55:58 -080058#include "AudioFlinger.h"
59#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070060#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070064#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080065
Eric Laurent81784c32012-11-19 14:55:58 -080066#ifdef ADD_BATTERY_DATA
67#include <media/IMediaPlayerService.h>
68#include <media/IMediaDeathNotifier.h>
69#endif
70
Eric Laurent81784c32012-11-19 14:55:58 -080071#ifdef DEBUG_CPU_USAGE
72#include <cpustats/CentralTendencyStatistics.h>
73#include <cpustats/ThreadCpuUsage.h>
74#endif
75
Glenn Kastenc05b8d72016-03-24 09:48:17 -070076#include "AutoPark.h"
77
Eric Laurent81784c32012-11-19 14:55:58 -080078// ----------------------------------------------------------------------------
79
80// Note: the following macro is used for extremely verbose logging message. In
81// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
82// 0; but one side effect of this is to turn all LOGV's as well. Some messages
83// are so verbose that we want to suppress them even when we have ALOG_ASSERT
84// turned on. Do not uncomment the #def below unless you really know what you
85// are doing and want to see all of the extremely verbose messages.
86//#define VERY_VERY_VERBOSE_LOGGING
87#ifdef VERY_VERY_VERBOSE_LOGGING
88#define ALOGVV ALOGV
89#else
90#define ALOGVV(a...) do { } while(0)
91#endif
92
Andy Hung6770c6f2015-04-07 13:43:36 -070093// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070094#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070095template <typename T>
96static inline T min(const T& a, const T& b)
97{
98 return a < b ? a : b;
99}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700100
Andy Hungd330ee42015-04-20 13:23:41 -0700101#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700102#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700103#endif
104
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 Kasten9f81de32014-07-27 15:02:23 -0700202static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
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";
448 default:
449 return "unknown";
450 }
451}
452
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700453std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 }
461 return result;
462}
463
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 std::string result;
467 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475 return result;
476}
477
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800478const char *sourceToString(audio_source_t source)
479{
480 switch (source) {
481 case AUDIO_SOURCE_DEFAULT: return "default";
482 case AUDIO_SOURCE_MIC: return "mic";
483 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
484 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
485 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
486 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
487 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
488 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
489 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800490 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800491 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
492 case AUDIO_SOURCE_HOTWORD: return "hotword";
493 default: return "unknown";
494 }
495}
496
Eric Laurent81784c32012-11-19 14:55:58 -0800497AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700498 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800499 : Thread(false /*canCallJava*/),
500 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700501 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700502 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800503 // are set by PlaybackThread::readOutputParameters_l() or
504 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700505 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800506 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700507 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
508 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800509 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700510 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent9cab7462016-11-10 13:05:20 -0800511 mSystemReady(systemReady),
512 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800513{
Eric Laurent296fb132015-05-01 11:38:42 -0700514 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
517AudioFlinger::ThreadBase::~ThreadBase()
518{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 mConfigEvents.clear();
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522 // do not lock the mutex in destructor
523 releaseWakeLock_l();
524 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800525 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800526 binder->unlinkToDeath(mDeathRecipient);
527 }
528}
529
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700530status_t AudioFlinger::ThreadBase::readyToRun()
531{
532 status_t status = initCheck();
533 if (status == NO_ERROR) {
534 ALOGI("AudioFlinger's thread %p ready to run", this);
535 } else {
536 ALOGE("No working audio driver found.");
537 }
538 return status;
539}
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541void AudioFlinger::ThreadBase::exit()
542{
543 ALOGV("ThreadBase::exit");
544 // do any cleanup required for exit to succeed
545 preExit();
546 {
547 // This lock prevents the following race in thread (uniprocessor for illustration):
548 // if (!exitPending()) {
549 // // context switch from here to exit()
550 // // exit() calls requestExit(), what exitPending() observes
551 // // exit() calls signal(), which is dropped since no waiters
552 // // context switch back from exit() to here
553 // mWaitWorkCV.wait(...);
554 // // now thread is hung
555 // }
556 AutoMutex lock(mLock);
557 requestExit();
558 mWaitWorkCV.broadcast();
559 }
560 // When Thread::requestExitAndWait is made virtual and this method is renamed to
561 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
562 requestExitAndWait();
563}
564
565status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
566{
Eric Laurent81784c32012-11-19 14:55:58 -0800567 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
568 Mutex::Autolock _l(mLock);
569
Eric Laurent10351942014-05-08 18:49:52 -0700570 return sendSetParameterConfigEvent_l(keyValuePairs);
571}
572
573// sendConfigEvent_l() must be called with ThreadBase::mLock held
574// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
575status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
576{
577 status_t status = NO_ERROR;
578
Eric Laurent72e3f392015-05-20 14:43:50 -0700579 if (event->mRequiresSystemReady && !mSystemReady) {
580 event->mWaitStatus = false;
581 mPendingConfigEvents.add(event);
582 return status;
583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700585 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800586 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700587 mLock.unlock();
588 {
589 Mutex::Autolock _l(event->mLock);
590 while (event->mWaitStatus) {
591 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
592 event->mStatus = TIMED_OUT;
593 event->mWaitStatus = false;
594 }
595 }
596 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800597 }
Eric Laurent10351942014-05-08 18:49:52 -0700598 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800599 return status;
600}
601
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700602void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
604 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
608// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700612 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800613}
614
Eric Laurent72e3f392015-05-20 14:43:50 -0700615void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
616{
617 Mutex::Autolock _l(mLock);
618 sendPrioConfigEvent_l(pid, tid, prio);
619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
622void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
623{
Eric Laurent10351942014-05-08 18:49:52 -0700624 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
625 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800626}
627
Eric Laurent10351942014-05-08 18:49:52 -0700628// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
629status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800630{
Andy Hung2ddee192015-12-18 17:34:44 -0800631 sp<ConfigEvent> configEvent;
632 AudioParameter param(keyValuePair);
633 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700634 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800635 setMasterMono_l(value != 0);
636 if (param.size() == 1) {
637 return NO_ERROR; // should be a solo parameter - we don't pass down
638 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700639 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800640 configEvent = new SetParameterConfigEvent(param.toString());
641 } else {
642 configEvent = new SetParameterConfigEvent(keyValuePair);
643 }
Eric Laurent10351942014-05-08 18:49:52 -0700644 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700645}
646
Eric Laurent1c333e22014-05-20 10:48:17 -0700647status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
648 const struct audio_patch *patch,
649 audio_patch_handle_t *handle)
650{
651 Mutex::Autolock _l(mLock);
652 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
653 status_t status = sendConfigEvent_l(configEvent);
654 if (status == NO_ERROR) {
655 CreateAudioPatchConfigEventData *data =
656 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
657 *handle = data->mHandle;
658 }
659 return status;
660}
661
662status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
663 const audio_patch_handle_t handle)
664{
665 Mutex::Autolock _l(mLock);
666 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
667 return sendConfigEvent_l(configEvent);
668}
669
670
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700671// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700672void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700673{
Eric Laurent10351942014-05-08 18:49:52 -0700674 bool configChanged = false;
675
Eric Laurent81784c32012-11-19 14:55:58 -0800676 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700677 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700678 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800679 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700680 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700681 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700682 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
683 // FIXME Need to understand why this has to be done asynchronously
684 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700685 true /*asynchronous*/);
686 if (err != 0) {
687 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700688 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700689 }
690 } break;
691 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700692 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700693 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700694 } break;
695 case CFG_EVENT_SET_PARAMETER: {
696 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
697 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
698 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700699 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700700 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700701 case CFG_EVENT_CREATE_AUDIO_PATCH: {
702 CreateAudioPatchConfigEventData *data =
703 (CreateAudioPatchConfigEventData *)event->mData.get();
704 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
705 } break;
706 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
707 ReleaseAudioPatchConfigEventData *data =
708 (ReleaseAudioPatchConfigEventData *)event->mData.get();
709 event->mStatus = releaseAudioPatch_l(data->mHandle);
710 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700711 default:
Eric Laurent10351942014-05-08 18:49:52 -0700712 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700713 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800714 }
Eric Laurent10351942014-05-08 18:49:52 -0700715 {
716 Mutex::Autolock _l(event->mLock);
717 if (event->mWaitStatus) {
718 event->mWaitStatus = false;
719 event->mCond.signal();
720 }
721 }
722 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
723 }
724
725 if (configChanged) {
726 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800727 }
Eric Laurent81784c32012-11-19 14:55:58 -0800728}
729
Marco Nelissenb2208842014-02-07 14:00:50 -0800730String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
731 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700732 const audio_channel_representation_t representation =
733 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700734
735 switch (representation) {
736 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
737 if (output) {
738 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
739 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
740 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
741 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
742 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
743 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
744 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
745 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
746 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
747 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
748 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
749 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
750 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
751 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
753 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
754 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
755 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
756 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
757 } else {
758 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
759 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
760 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
761 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
762 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
763 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
764 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
765 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
766 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
767 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
768 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
769 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
770 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
771 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
772 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
773 }
774 const int len = s.length();
775 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700776 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700777 s.unlockBuffer(len - 2); // remove trailing ", "
778 }
779 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800780 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700781 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
782 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
783 return s;
784 default:
785 s.appendFormat("unknown mask, representation:%d bits:%#x",
786 representation, audio_channel_mask_get_bits(mask));
787 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800788 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800789}
790
Glenn Kasten0f11b512014-01-31 16:18:54 -0800791void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800792{
793 const size_t SIZE = 256;
794 char buffer[SIZE];
795 String8 result;
796
797 bool locked = AudioFlinger::dumpTryLock(mLock);
798 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700799 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800800 }
801
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800802 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700803 dprintf(fd, " I/O handle: %d\n", mId);
804 dprintf(fd, " TID: %d\n", getTid());
805 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700806 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700807 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700808 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700809 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700810 dprintf(fd, " Channel count: %u\n", mChannelCount);
811 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800812 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700813 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700814 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700815 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800816 size_t numConfig = mConfigEvents.size();
817 if (numConfig) {
818 for (size_t i = 0; i < numConfig; i++) {
819 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700820 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800821 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700822 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800823 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700824 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800825 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700826 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
827 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800828 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800829
830 if (locked) {
831 mLock.unlock();
832 }
833}
834
835void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
836{
837 const size_t SIZE = 256;
838 char buffer[SIZE];
839 String8 result;
840
Marco Nelissenb2208842014-02-07 14:00:50 -0800841 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000842 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800843 write(fd, buffer, strlen(buffer));
844
Marco Nelissenb2208842014-02-07 14:00:50 -0800845 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800846 sp<EffectChain> chain = mEffectChains[i];
847 if (chain != 0) {
848 chain->dump(fd, args);
849 }
850 }
851}
852
Eric Laurent9cab7462016-11-10 13:05:20 -0800853void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800854{
855 Mutex::Autolock _l(mLock);
Eric Laurent9cab7462016-11-10 13:05:20 -0800856 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800857}
858
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100859String16 AudioFlinger::ThreadBase::getWakeLockTag()
860{
861 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800862 case MIXER:
863 return String16("AudioMix");
864 case DIRECT:
865 return String16("AudioDirectOut");
866 case DUPLICATING:
867 return String16("AudioDup");
868 case RECORD:
869 return String16("AudioIn");
870 case OFFLOAD:
871 return String16("AudioOffload");
872 default:
873 ALOG_ASSERT(false);
874 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100875 }
876}
877
Eric Laurent9cab7462016-11-10 13:05:20 -0800878void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800879{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800880 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800881 if (mPowerManager != 0) {
882 sp<IBinder> binder = new BBinder();
Eric Laurent9cab7462016-11-10 13:05:20 -0800883 status_t status;
884 if (uid >= 0) {
885 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
886 binder,
887 getWakeLockTag(),
888 String16("audioserver"),
889 uid,
890 true /* FIXME force oneway contrary to .aidl */);
891 } else {
892 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700893 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100894 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700895 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700896 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent9cab7462016-11-10 13:05:20 -0800897 }
Eric Laurent81784c32012-11-19 14:55:58 -0800898 if (status == NO_ERROR) {
899 mWakeLockToken = binder;
900 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800901 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800902 }
Wei Jia3f273d12015-11-24 09:06:49 -0800903
Eric Laurent9cab7462016-11-10 13:05:20 -0800904 if (!mNotifiedBatteryStart) {
905 // TODO: call this function for each track when it becomes active.
906 BatteryNotifier::getInstance().noteStartAudio(AID_AUDIOSERVER);
907 mNotifiedBatteryStart = true;
908 }
Andy Hung3f0c9022016-01-15 17:49:46 -0800909 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800910 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
911 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800912}
913
914void AudioFlinger::ThreadBase::releaseWakeLock()
915{
916 Mutex::Autolock _l(mLock);
917 releaseWakeLock_l();
918}
919
920void AudioFlinger::ThreadBase::releaseWakeLock_l()
921{
Andy Hung3f0c9022016-01-15 17:49:46 -0800922 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800923 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800924 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800925 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700926 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
927 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 }
929 mWakeLockToken.clear();
930 }
Eric Laurent9cab7462016-11-10 13:05:20 -0800931
932 if (mNotifiedBatteryStart) {
933 // TODO: call this function for each track when it becomes inactive.
934 BatteryNotifier::getInstance().noteStopAudio(AID_AUDIOSERVER);
935 mNotifiedBatteryStart = false;
936 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800937}
938
939void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700940 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800941 // use checkService() to avoid blocking if power service is not up yet
942 sp<IBinder> binder =
943 defaultServiceManager()->checkService(String16("power"));
944 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800945 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800946 } else {
947 mPowerManager = interface_cast<IPowerManager>(binder);
948 binder->linkToDeath(mDeathRecipient);
949 }
950 }
951}
952
Eric Laurent9cab7462016-11-10 13:05:20 -0800953void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800954 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -0800955 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
956 if (mSystemReady) {
957 ALOGE("no wake lock to update, but system ready!");
958 } else {
959 ALOGW("no wake lock to update, system not ready yet");
960 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800961 return;
962 }
963 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800964 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
965 status_t status = mPowerManager->updateWakeLockUids(
966 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
967 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800968 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800969 }
970}
971
Eric Laurent81784c32012-11-19 14:55:58 -0800972void AudioFlinger::ThreadBase::clearPowerManager()
973{
974 Mutex::Autolock _l(mLock);
975 releaseWakeLock_l();
976 mPowerManager.clear();
977}
978
Glenn Kasten0f11b512014-01-31 16:18:54 -0800979void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800980{
981 sp<ThreadBase> thread = mThread.promote();
982 if (thread != 0) {
983 thread->clearPowerManager();
984 }
985 ALOGW("power manager service died !!!");
986}
987
988void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800989 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800990{
991 Mutex::Autolock _l(mLock);
992 setEffectSuspended_l(type, suspend, sessionId);
993}
994
995void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800996 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800997{
998 sp<EffectChain> chain = getEffectChain_l(sessionId);
999 if (chain != 0) {
1000 if (type != NULL) {
1001 chain->setEffectSuspended_l(type, suspend);
1002 } else {
1003 chain->setEffectSuspendedAll_l(suspend);
1004 }
1005 }
1006
1007 updateSuspendedSessions_l(type, suspend, sessionId);
1008}
1009
1010void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1011{
1012 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1013 if (index < 0) {
1014 return;
1015 }
1016
1017 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1018 mSuspendedSessions.valueAt(index);
1019
1020 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001021 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001022 for (int j = 0; j < desc->mRefCount; j++) {
1023 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1024 chain->setEffectSuspendedAll_l(true);
1025 } else {
1026 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1027 desc->mType.timeLow);
1028 chain->setEffectSuspended_l(&desc->mType, true);
1029 }
1030 }
1031 }
1032}
1033
1034void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1035 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001036 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001037{
1038 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1039
1040 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1041
1042 if (suspend) {
1043 if (index >= 0) {
1044 sessionEffects = mSuspendedSessions.valueAt(index);
1045 } else {
1046 mSuspendedSessions.add(sessionId, sessionEffects);
1047 }
1048 } else {
1049 if (index < 0) {
1050 return;
1051 }
1052 sessionEffects = mSuspendedSessions.valueAt(index);
1053 }
1054
1055
1056 int key = EffectChain::kKeyForSuspendAll;
1057 if (type != NULL) {
1058 key = type->timeLow;
1059 }
1060 index = sessionEffects.indexOfKey(key);
1061
1062 sp<SuspendedSessionDesc> desc;
1063 if (suspend) {
1064 if (index >= 0) {
1065 desc = sessionEffects.valueAt(index);
1066 } else {
1067 desc = new SuspendedSessionDesc();
1068 if (type != NULL) {
1069 desc->mType = *type;
1070 }
1071 sessionEffects.add(key, desc);
1072 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1073 }
1074 desc->mRefCount++;
1075 } else {
1076 if (index < 0) {
1077 return;
1078 }
1079 desc = sessionEffects.valueAt(index);
1080 if (--desc->mRefCount == 0) {
1081 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1082 sessionEffects.removeItemsAt(index);
1083 if (sessionEffects.isEmpty()) {
1084 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1085 sessionId);
1086 mSuspendedSessions.removeItem(sessionId);
1087 }
1088 }
1089 }
1090 if (!sessionEffects.isEmpty()) {
1091 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1092 }
1093}
1094
1095void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1096 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001097 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001098{
1099 Mutex::Autolock _l(mLock);
1100 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1101}
1102
1103void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1104 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001105 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001106{
1107 if (mType != RECORD) {
1108 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1109 // another session. This gives the priority to well behaved effect control panels
1110 // and applications not using global effects.
1111 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1112 // global effects
1113 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1114 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1115 }
1116 }
1117
1118 sp<EffectChain> chain = getEffectChain_l(sessionId);
1119 if (chain != 0) {
1120 chain->checkSuspendOnEffectEnabled(effect, enabled);
1121 }
1122}
1123
Eric Laurent4c415062016-06-17 16:14:16 -07001124// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1125status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1126 const effect_descriptor_t *desc, audio_session_t sessionId)
1127{
1128 // No global effect sessions on record threads
1129 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1130 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1131 desc->name, mThreadName);
1132 return BAD_VALUE;
1133 }
1134 // only pre processing effects on record thread
1135 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1136 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1137 desc->name, mThreadName);
1138 return BAD_VALUE;
1139 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001140
1141 // always allow effects without processing load or latency
1142 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1143 return NO_ERROR;
1144 }
1145
Eric Laurent4c415062016-06-17 16:14:16 -07001146 audio_input_flags_t flags = mInput->flags;
1147 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1148 if (flags & AUDIO_INPUT_FLAG_RAW) {
1149 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1150 desc->name, mThreadName);
1151 return BAD_VALUE;
1152 }
1153 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1154 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1155 desc->name, mThreadName);
1156 return BAD_VALUE;
1157 }
1158 }
1159 return NO_ERROR;
1160}
1161
1162// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1163status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1164 const effect_descriptor_t *desc, audio_session_t sessionId)
1165{
1166 // no preprocessing on playback threads
1167 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1168 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1169 " thread %s", desc->name, mThreadName);
1170 return BAD_VALUE;
1171 }
1172
1173 switch (mType) {
1174 case MIXER: {
1175 // Reject any effect on mixer multichannel sinks.
1176 // TODO: fix both format and multichannel issues with effects.
1177 if (mChannelCount != FCC_2) {
1178 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1179 " thread %s", desc->name, mChannelCount, mThreadName);
1180 return BAD_VALUE;
1181 }
1182 audio_output_flags_t flags = mOutput->flags;
1183 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1184 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1185 // global effects are applied only to non fast tracks if they are SW
1186 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1187 break;
1188 }
1189 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1190 // only post processing on output stage session
1191 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1192 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1193 " on output stage session", desc->name);
1194 return BAD_VALUE;
1195 }
1196 } else {
1197 // no restriction on effects applied on non fast tracks
1198 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1199 break;
1200 }
1201 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001202
1203 // always allow effects without processing load or latency
1204 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1205 break;
1206 }
Eric Laurent4c415062016-06-17 16:14:16 -07001207 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1208 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1209 desc->name);
1210 return BAD_VALUE;
1211 }
1212 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1213 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1214 " in fast mode", desc->name);
1215 return BAD_VALUE;
1216 }
1217 }
1218 } break;
1219 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001220 // nothing actionable on offload threads, if the effect:
1221 // - is offloadable: the effect can be created
1222 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1223 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001224 break;
1225 case DIRECT:
1226 // Reject any effect on Direct output threads for now, since the format of
1227 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1228 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1229 desc->name, mThreadName);
1230 return BAD_VALUE;
1231 case DUPLICATING:
1232 // Reject any effect on mixer multichannel sinks.
1233 // TODO: fix both format and multichannel issues with effects.
1234 if (mChannelCount != FCC_2) {
1235 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1236 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1237 return BAD_VALUE;
1238 }
1239 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1240 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1241 " thread %s", desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1245 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1246 " DUPLICATING thread %s", desc->name, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1250 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1251 " DUPLICATING thread %s", desc->name, mThreadName);
1252 return BAD_VALUE;
1253 }
1254 break;
1255 default:
1256 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1257 }
1258
1259 return NO_ERROR;
1260}
1261
Eric Laurent81784c32012-11-19 14:55:58 -08001262// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1263sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1264 const sp<AudioFlinger::Client>& client,
1265 const sp<IEffectClient>& effectClient,
1266 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001267 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001268 effect_descriptor_t *desc,
1269 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001270 status_t *status,
1271 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001272{
1273 sp<EffectModule> effect;
1274 sp<EffectHandle> handle;
1275 status_t lStatus;
1276 sp<EffectChain> chain;
1277 bool chainCreated = false;
1278 bool effectCreated = false;
1279 bool effectRegistered = false;
1280
1281 lStatus = initCheck();
1282 if (lStatus != NO_ERROR) {
1283 ALOGW("createEffect_l() Audio driver not initialized.");
1284 goto Exit;
1285 }
1286
Eric Laurent81784c32012-11-19 14:55:58 -08001287 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1288
1289 { // scope for mLock
1290 Mutex::Autolock _l(mLock);
1291
Eric Laurent4c415062016-06-17 16:14:16 -07001292 lStatus = checkEffectCompatibility_l(desc, sessionId);
1293 if (lStatus != NO_ERROR) {
1294 goto Exit;
1295 }
1296
Eric Laurent81784c32012-11-19 14:55:58 -08001297 // check for existing effect chain with the requested audio session
1298 chain = getEffectChain_l(sessionId);
1299 if (chain == 0) {
1300 // create a new chain for this session
1301 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1302 chain = new EffectChain(this, sessionId);
1303 addEffectChain_l(chain);
1304 chain->setStrategy(getStrategyForSession_l(sessionId));
1305 chainCreated = true;
1306 } else {
1307 effect = chain->getEffectFromDesc_l(desc);
1308 }
1309
1310 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1311
1312 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001313 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001314 // Check CPU and memory usage
1315 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1316 if (lStatus != NO_ERROR) {
1317 goto Exit;
1318 }
1319 effectRegistered = true;
1320 // create a new effect module if none present in the chain
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001321 lStatus = chain->createEffect_l(effect, this, desc, id, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001322 if (lStatus != NO_ERROR) {
1323 goto Exit;
1324 }
1325 effectCreated = true;
1326
1327 effect->setDevice(mOutDevice);
1328 effect->setDevice(mInDevice);
1329 effect->setMode(mAudioFlinger->getMode());
1330 effect->setAudioSource(mAudioSource);
1331 }
1332 // create effect handle and connect it to effect module
1333 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001334 lStatus = handle->initCheck();
1335 if (lStatus == OK) {
1336 lStatus = effect->addHandle(handle.get());
1337 }
Eric Laurent81784c32012-11-19 14:55:58 -08001338 if (enabled != NULL) {
1339 *enabled = (int)effect->isEnabled();
1340 }
1341 }
1342
1343Exit:
1344 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1345 Mutex::Autolock _l(mLock);
1346 if (effectCreated) {
1347 chain->removeEffect_l(effect);
1348 }
1349 if (effectRegistered) {
1350 AudioSystem::unregisterEffect(effect->id());
1351 }
1352 if (chainCreated) {
1353 removeEffectChain_l(chain);
1354 }
1355 handle.clear();
1356 }
1357
Glenn Kasten9156ef32013-08-06 15:39:08 -07001358 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001359 return handle;
1360}
1361
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001362void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1363 bool unpinIfLast)
1364{
1365 bool remove = false;
1366 sp<EffectModule> effect;
1367 {
1368 Mutex::Autolock _l(mLock);
1369
1370 effect = handle->effect().promote();
1371 if (effect == 0) {
1372 return;
1373 }
1374 // restore suspended effects if the disconnected handle was enabled and the last one.
1375 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1376 if (remove) {
1377 removeEffect_l(effect, true);
1378 }
1379 }
1380 if (remove) {
1381 mAudioFlinger->updateOrphanEffectChains(effect);
1382 AudioSystem::unregisterEffect(effect->id());
1383 if (handle->enabled()) {
1384 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1385 }
1386 }
1387}
1388
Glenn Kastend848eb42016-03-08 13:42:11 -08001389sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1390 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001391{
1392 Mutex::Autolock _l(mLock);
1393 return getEffect_l(sessionId, effectId);
1394}
1395
Glenn Kastend848eb42016-03-08 13:42:11 -08001396sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1397 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001398{
1399 sp<EffectChain> chain = getEffectChain_l(sessionId);
1400 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1401}
1402
1403// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1404// PlaybackThread::mLock held
1405status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1406{
1407 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001408 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001409 sp<EffectChain> chain = getEffectChain_l(sessionId);
1410 bool chainCreated = false;
1411
Eric Laurent5baf2af2013-09-12 17:37:00 -07001412 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1413 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1414 this, effect->desc().name, effect->desc().flags);
1415
Eric Laurent81784c32012-11-19 14:55:58 -08001416 if (chain == 0) {
1417 // create a new chain for this session
1418 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1419 chain = new EffectChain(this, sessionId);
1420 addEffectChain_l(chain);
1421 chain->setStrategy(getStrategyForSession_l(sessionId));
1422 chainCreated = true;
1423 }
1424 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1425
1426 if (chain->getEffectFromId_l(effect->id()) != 0) {
1427 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1428 this, effect->desc().name, chain.get());
1429 return BAD_VALUE;
1430 }
1431
Eric Laurent5baf2af2013-09-12 17:37:00 -07001432 effect->setOffloaded(mType == OFFLOAD, mId);
1433
Eric Laurent81784c32012-11-19 14:55:58 -08001434 status_t status = chain->addEffect_l(effect);
1435 if (status != NO_ERROR) {
1436 if (chainCreated) {
1437 removeEffectChain_l(chain);
1438 }
1439 return status;
1440 }
1441
1442 effect->setDevice(mOutDevice);
1443 effect->setDevice(mInDevice);
1444 effect->setMode(mAudioFlinger->getMode());
1445 effect->setAudioSource(mAudioSource);
1446 return NO_ERROR;
1447}
1448
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001449void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001450
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001451 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001452 effect_descriptor_t desc = effect->desc();
1453 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1454 detachAuxEffect_l(effect->id());
1455 }
1456
1457 sp<EffectChain> chain = effect->chain().promote();
1458 if (chain != 0) {
1459 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001460 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001461 removeEffectChain_l(chain);
1462 }
1463 } else {
1464 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1465 }
1466}
1467
1468void AudioFlinger::ThreadBase::lockEffectChains_l(
1469 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1470{
1471 effectChains = mEffectChains;
1472 for (size_t i = 0; i < mEffectChains.size(); i++) {
1473 mEffectChains[i]->lock();
1474 }
1475}
1476
1477void AudioFlinger::ThreadBase::unlockEffectChains(
1478 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1479{
1480 for (size_t i = 0; i < effectChains.size(); i++) {
1481 effectChains[i]->unlock();
1482 }
1483}
1484
Glenn Kastend848eb42016-03-08 13:42:11 -08001485sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001486{
1487 Mutex::Autolock _l(mLock);
1488 return getEffectChain_l(sessionId);
1489}
1490
Glenn Kastend848eb42016-03-08 13:42:11 -08001491sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1492 const
Eric Laurent81784c32012-11-19 14:55:58 -08001493{
1494 size_t size = mEffectChains.size();
1495 for (size_t i = 0; i < size; i++) {
1496 if (mEffectChains[i]->sessionId() == sessionId) {
1497 return mEffectChains[i];
1498 }
1499 }
1500 return 0;
1501}
1502
1503void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1504{
1505 Mutex::Autolock _l(mLock);
1506 size_t size = mEffectChains.size();
1507 for (size_t i = 0; i < size; i++) {
1508 mEffectChains[i]->setMode_l(mode);
1509 }
1510}
1511
Eric Laurent83b88082014-06-20 18:31:16 -07001512void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1513{
1514 config->type = AUDIO_PORT_TYPE_MIX;
1515 config->ext.mix.handle = mId;
1516 config->sample_rate = mSampleRate;
1517 config->format = mFormat;
1518 config->channel_mask = mChannelMask;
1519 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1520 AUDIO_PORT_CONFIG_FORMAT;
1521}
1522
Eric Laurent72e3f392015-05-20 14:43:50 -07001523void AudioFlinger::ThreadBase::systemReady()
1524{
1525 Mutex::Autolock _l(mLock);
1526 if (mSystemReady) {
1527 return;
1528 }
1529 mSystemReady = true;
1530
1531 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1532 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1533 }
1534 mPendingConfigEvents.clear();
1535}
1536
Eric Laurent83b88082014-06-20 18:31:16 -07001537
Eric Laurent81784c32012-11-19 14:55:58 -08001538// ----------------------------------------------------------------------------
1539// Playback
1540// ----------------------------------------------------------------------------
1541
1542AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1543 AudioStreamOut* output,
1544 audio_io_handle_t id,
1545 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001546 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001547 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001548 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001549 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001550 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001551 mMixerBuffer(NULL),
1552 mMixerBufferSize(0),
1553 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1554 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001555 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001556 mEffectBuffer(NULL),
1557 mEffectBufferSize(0),
1558 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1559 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001560 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001561 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001562 mSuspendedFrames(0),
Eric Laurent9cab7462016-11-10 13:05:20 -08001563 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001564 // mStreamTypes[] initialized in constructor body
1565 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001566 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001567 mMixerStatus(MIXER_IDLE),
1568 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001569 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001570 mBytesRemaining(0),
1571 mCurrentWriteLength(0),
1572 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001573 mWriteAckSequence(0),
1574 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001575 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001576 mScreenState(AudioFlinger::mScreenState),
1577 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001578 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001579 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001580{
Glenn Kastend7dca052015-03-05 16:05:54 -08001581 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1582 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001583
1584 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1585 // it would be safer to explicitly pass initial masterVolume/masterMute as
1586 // parameter.
1587 //
1588 // If the HAL we are using has support for master volume or master mute,
1589 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1590 // and the mute set to false).
1591 mMasterVolume = audioFlinger->masterVolume_l();
1592 mMasterMute = audioFlinger->masterMute_l();
1593 if (mOutput && mOutput->audioHwDev) {
1594 if (mOutput->audioHwDev->canSetMasterVolume()) {
1595 mMasterVolume = 1.0;
1596 }
1597
1598 if (mOutput->audioHwDev->canSetMasterMute()) {
1599 mMasterMute = false;
1600 }
1601 }
1602
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001603 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001604
Eric Laurent223fd5c2014-11-11 13:43:36 -08001605 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001606 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001607 stream = (audio_stream_type_t) (stream + 1)) {
1608 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1609 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1610 }
Eric Laurent81784c32012-11-19 14:55:58 -08001611}
1612
1613AudioFlinger::PlaybackThread::~PlaybackThread()
1614{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001615 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001616 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001617 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001618 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001619}
1620
1621void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1622{
1623 dumpInternals(fd, args);
1624 dumpTracks(fd, args);
1625 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001626 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001627}
1628
Glenn Kasten0f11b512014-01-31 16:18:54 -08001629void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001630{
1631 const size_t SIZE = 256;
1632 char buffer[SIZE];
1633 String8 result;
1634
Marco Nelissenb2208842014-02-07 14:00:50 -08001635 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001636 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1637 const stream_type_t *st = &mStreamTypes[i];
1638 if (i > 0) {
1639 result.appendFormat(", ");
1640 }
1641 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1642 if (st->mute) {
1643 result.append("M");
1644 }
1645 }
1646 result.append("\n");
1647 write(fd, result.string(), result.length());
1648 result.clear();
1649
Eric Laurent81784c32012-11-19 14:55:58 -08001650 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1651 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001652 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001653 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001654
1655 size_t numtracks = mTracks.size();
1656 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001657 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001658 size_t numactiveseen = 0;
1659 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001660 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001661 Track::appendDumpHeader(result);
1662 for (size_t i = 0; i < numtracks; ++i) {
1663 sp<Track> track = mTracks[i];
1664 if (track != 0) {
1665 bool active = mActiveTracks.indexOf(track) >= 0;
1666 if (active) {
1667 numactiveseen++;
1668 }
1669 track->dump(buffer, SIZE, active);
1670 result.append(buffer);
1671 }
1672 }
1673 } else {
1674 result.append("\n");
1675 }
1676 if (numactiveseen != numactive) {
1677 // some tracks in the active list were not in the tracks list
1678 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1679 " not in the track list\n");
1680 result.append(buffer);
1681 Track::appendDumpHeader(result);
1682 for (size_t i = 0; i < numactive; ++i) {
Eric Laurent9cab7462016-11-10 13:05:20 -08001683 sp<Track> track = mActiveTracks[i].promote();
1684 if (track != 0 && mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001685 track->dump(buffer, SIZE, true);
1686 result.append(buffer);
1687 }
1688 }
1689 }
1690
1691 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001692}
1693
1694void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1695{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001696 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001697
1698 dumpBase(fd, args);
1699
Elliott Hughes87cebad2014-05-22 10:14:43 -07001700 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001701 dprintf(fd, " Last write occurred (msecs): %llu\n",
1702 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001703 dprintf(fd, " Total writes: %d\n", mNumWrites);
1704 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1705 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1706 dprintf(fd, " Suspend count: %d\n", mSuspended);
1707 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1708 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1709 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1710 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001711 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001712 AudioStreamOut *output = mOutput;
1713 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001714 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1715 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001716 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1717 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1718 if (mPipeSink.get() != nullptr) {
1719 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1720 }
1721 if (output != nullptr) {
1722 dprintf(fd, " Hal stream dump:\n");
1723 (void)output->stream->dump(fd);
1724 }
Eric Laurent81784c32012-11-19 14:55:58 -08001725}
1726
1727// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001728
1729void AudioFlinger::PlaybackThread::onFirstRef()
1730{
Glenn Kastend7dca052015-03-05 16:05:54 -08001731 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001732}
1733
1734// ThreadBase virtuals
1735void AudioFlinger::PlaybackThread::preExit()
1736{
1737 ALOGV(" preExit()");
1738 // FIXME this is using hard-coded strings but in the future, this functionality will be
1739 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001740 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1741 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001742}
1743
1744// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1745sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1746 const sp<AudioFlinger::Client>& client,
1747 audio_stream_type_t streamType,
1748 uint32_t sampleRate,
1749 audio_format_t format,
1750 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001751 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001752 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001753 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001754 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001755 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001756 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001757 status_t *status,
1758 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001759{
Glenn Kasten74935e42013-12-19 08:56:45 -08001760 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001761 sp<Track> track;
1762 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001763 audio_output_flags_t outputFlags = mOutput->flags;
1764
1765 // special case for FAST flag considered OK if fast mixer is present
1766 if (hasFastMixer()) {
1767 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1768 }
1769
1770 // Check if requested flags are compatible with output stream flags
1771 if ((*flags & outputFlags) != *flags) {
1772 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1773 *flags, outputFlags);
1774 *flags = (audio_output_flags_t)(*flags & outputFlags);
1775 }
Eric Laurent81784c32012-11-19 14:55:58 -08001776
Eric Laurent81784c32012-11-19 14:55:58 -08001777 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001778 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001779 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001780 // PCM data
1781 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001782 // TODO: extract as a data library function that checks that a computationally
1783 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001784 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001785 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1786 (channelMask == AUDIO_CHANNEL_OUT_MONO
1787 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001788 // hardware sample rate
1789 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001790 // normal mixer has an associated fast mixer
1791 hasFastMixer() &&
1792 // there are sufficient fast track slots available
1793 (mFastTrackAvailMask != 0)
1794 // FIXME test that MixerThread for this fast track has a capable output HAL
1795 // FIXME add a permission test also?
1796 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001797 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1798 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001799 // read the fast track multiplier property the first time it is needed
1800 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1801 if (ok != 0) {
1802 ALOGE("%s pthread_once failed: %d", __func__, ok);
1803 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001804 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001805 }
Eric Laurent4c415062016-06-17 16:14:16 -07001806
1807 // check compatibility with audio effects.
1808 { // scope for mLock
1809 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001810 for (audio_session_t session : {
1811 AUDIO_SESSION_OUTPUT_STAGE,
1812 AUDIO_SESSION_OUTPUT_MIX,
1813 sessionId,
1814 }) {
1815 sp<EffectChain> chain = getEffectChain_l(session);
1816 if (chain.get() != nullptr) {
1817 audio_output_flags_t old = *flags;
1818 chain->checkOutputFlagCompatibility(flags);
1819 if (old != *flags) {
1820 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1821 (int)session, (int)old, (int)*flags);
1822 }
Eric Laurent4c415062016-06-17 16:14:16 -07001823 }
1824 }
1825 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001826 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001827 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1828 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001829 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001830 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1831 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001832 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001833 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001834 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001835 audio_is_linear_pcm(format),
1836 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001837 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001838 }
1839 }
1840 // For normal PCM streaming tracks, update minimum frame count.
1841 // For compatibility with AudioTrack calculation, buffer depth is forced
1842 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1843 // This is probably too conservative, but legacy application code may depend on it.
1844 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001845 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001846 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001847 // this must match AudioTrack.cpp calculateMinFrameCount().
1848 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001849 uint32_t latencyMs = 0;
1850 lStatus = mOutput->stream->getLatency(&latencyMs);
1851 if (lStatus != OK) {
1852 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1853 goto Exit;
1854 }
Eric Laurent81784c32012-11-19 14:55:58 -08001855 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1856 if (minBufCount < 2) {
1857 minBufCount = 2;
1858 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001859 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1860 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001861 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001862 minBufCount * sourceFramesNeededWithTimestretch(
1863 sampleRate, mNormalFrameCount,
1864 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001865 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001866 frameCount = minFrameCount;
1867 }
Eric Laurent81784c32012-11-19 14:55:58 -08001868 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001869 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001870
Glenn Kastenc3df8382014-03-13 15:05:25 -07001871 switch (mType) {
1872
1873 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001874 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001875 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001876 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1877 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001878 sampleRate, format, channelMask, mOutput, mFormat);
1879 lStatus = BAD_VALUE;
1880 goto Exit;
1881 }
1882 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001883 break;
1884
1885 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001886 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001887 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1888 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001889 sampleRate, format, channelMask, mOutput, mFormat);
1890 lStatus = BAD_VALUE;
1891 goto Exit;
1892 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001893 break;
1894
1895 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001896 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001897 ALOGE("createTrack_l() Bad parameter: format %#x \""
1898 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001899 format, mOutput, mFormat);
1900 lStatus = BAD_VALUE;
1901 goto Exit;
1902 }
Andy Hungcd044842014-08-07 11:04:34 -07001903 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001904 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1905 lStatus = BAD_VALUE;
1906 goto Exit;
1907 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001908 break;
1909
Eric Laurent81784c32012-11-19 14:55:58 -08001910 }
1911
1912 lStatus = initCheck();
1913 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001914 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001915 goto Exit;
1916 }
1917
1918 { // scope for mLock
1919 Mutex::Autolock _l(mLock);
1920
1921 // all tracks in same audio session must share the same routing strategy otherwise
1922 // conflicts will happen when tracks are moved from one output to another by audio policy
1923 // manager
1924 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1925 for (size_t i = 0; i < mTracks.size(); ++i) {
1926 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001927 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001928 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1929 if (sessionId == t->sessionId() && strategy != actual) {
1930 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1931 strategy, actual);
1932 lStatus = BAD_VALUE;
1933 goto Exit;
1934 }
1935 }
1936 }
1937
Glenn Kastend79072e2016-01-06 08:41:20 -08001938 track = new Track(this, client, streamType, sampleRate, format,
1939 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001940 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07001941
Glenn Kasten03003332013-08-06 15:40:54 -07001942 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1943 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001944 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001945 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001946 goto Exit;
1947 }
1948 mTracks.add(track);
1949
1950 sp<EffectChain> chain = getEffectChain_l(sessionId);
1951 if (chain != 0) {
1952 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1953 track->setMainBuffer(chain->inBuffer());
1954 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1955 chain->incTrackCnt();
1956 }
1957
Eric Laurent05067782016-06-01 18:27:28 -07001958 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001959 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1960 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1961 // so ask activity manager to do this on our behalf
1962 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1963 }
1964 }
1965
1966 lStatus = NO_ERROR;
1967
1968Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001969 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001970 return track;
1971}
1972
1973uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1974{
1975 return latency;
1976}
1977
1978uint32_t AudioFlinger::PlaybackThread::latency() const
1979{
1980 Mutex::Autolock _l(mLock);
1981 return latency_l();
1982}
1983uint32_t AudioFlinger::PlaybackThread::latency_l() const
1984{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001985 uint32_t latency;
1986 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
1987 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08001988 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001989 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001990}
1991
1992void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1993{
1994 Mutex::Autolock _l(mLock);
1995 // Don't apply master volume in SW if our HAL can do it for us.
1996 if (mOutput && mOutput->audioHwDev &&
1997 mOutput->audioHwDev->canSetMasterVolume()) {
1998 mMasterVolume = 1.0;
1999 } else {
2000 mMasterVolume = value;
2001 }
2002}
2003
2004void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2005{
2006 Mutex::Autolock _l(mLock);
2007 // Don't apply master mute in SW if our HAL can do it for us.
2008 if (mOutput && mOutput->audioHwDev &&
2009 mOutput->audioHwDev->canSetMasterMute()) {
2010 mMasterMute = false;
2011 } else {
2012 mMasterMute = muted;
2013 }
2014}
2015
2016void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2017{
2018 Mutex::Autolock _l(mLock);
2019 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002020 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002021}
2022
2023void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2024{
2025 Mutex::Autolock _l(mLock);
2026 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002027 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002028}
2029
2030float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2031{
2032 Mutex::Autolock _l(mLock);
2033 return mStreamTypes[stream].volume;
2034}
2035
2036// addTrack_l() must be called with ThreadBase::mLock held
2037status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2038{
2039 status_t status = ALREADY_EXISTS;
2040
Eric Laurent81784c32012-11-19 14:55:58 -08002041 if (mActiveTracks.indexOf(track) < 0) {
2042 // the track is newly added, make sure it fills up all its
2043 // buffers before playing. This is to ensure the client will
2044 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002045 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002046 TrackBase::track_state state = track->mState;
2047 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002048 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002049 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002050 mLock.lock();
2051 // abort track was stopped/paused while we released the lock
2052 if (state != track->mState) {
2053 if (status == NO_ERROR) {
2054 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002055 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002056 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002057 mLock.lock();
2058 }
2059 return INVALID_OPERATION;
2060 }
2061 // abort if start is rejected by audio policy manager
2062 if (status != NO_ERROR) {
2063 return PERMISSION_DENIED;
2064 }
2065#ifdef ADD_BATTERY_DATA
2066 // to track the speaker usage
2067 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2068#endif
2069 }
2070
Eric Laurent51716182016-02-29 18:00:56 -08002071 // set retry count for buffer fill
2072 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002073 if (track->isStopping_1()) {
2074 track->mRetryCount = kMaxTrackStopRetriesOffload;
2075 } else {
2076 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2077 }
2078 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002079 } else {
2080 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002081 track->mFillingUpStatus =
2082 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002083 }
2084
Eric Laurent81784c32012-11-19 14:55:58 -08002085 track->mResetDone = false;
2086 track->mPresentationCompleteFrames = 0;
2087 mActiveTracks.add(track);
Eric Laurent9cab7462016-11-10 13:05:20 -08002088 mWakeLockUids.add(track->uid());
2089 mActiveTracksGeneration++;
2090 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002091 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2092 if (chain != 0) {
2093 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2094 track->sessionId());
2095 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002096 }
2097
Andy Hung2148bf02016-11-28 19:01:02 -08002098 char buffer[256];
2099 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2100 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2101
Eric Laurent81784c32012-11-19 14:55:58 -08002102 status = NO_ERROR;
2103 }
2104
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002105 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002106 return status;
2107}
2108
Eric Laurentbfb1b832013-01-07 09:53:42 -08002109bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002110{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002111 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002112 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002113 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2114 track->mState = TrackBase::STOPPED;
2115 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002116 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002117 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002118 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002119 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002120
2121 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002122}
2123
2124void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2125{
2126 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002127
2128 char buffer[256];
2129 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2130 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2131
Eric Laurent81784c32012-11-19 14:55:58 -08002132 mTracks.remove(track);
2133 deleteTrackName_l(track->name());
2134 // redundant as track is about to be destroyed, for dumpsys only
2135 track->mName = -1;
2136 if (track->isFastTrack()) {
2137 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002138 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002139 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2140 mFastTrackAvailMask |= 1 << index;
2141 // redundant as track is about to be destroyed, for dumpsys only
2142 track->mFastIndex = -1;
2143 }
2144 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2145 if (chain != 0) {
2146 chain->decTrackCnt();
2147 }
2148}
2149
Eric Laurentede6c3b2013-09-19 14:37:46 -07002150void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002151{
2152 // Thread could be blocked waiting for async
2153 // so signal it to handle state changes immediately
2154 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2155 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2156 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002157 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002158}
2159
Eric Laurent81784c32012-11-19 14:55:58 -08002160String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2161{
Eric Laurent81784c32012-11-19 14:55:58 -08002162 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002163 String8 out_s8;
2164 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2165 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002166 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002167 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002168}
2169
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002170void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002171 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2172 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002173
Eric Laurent73e26b62015-04-27 16:55:58 -07002174 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002175
2176 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002177 case AUDIO_OUTPUT_OPENED:
2178 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002179 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002180 desc->mChannelMask = mChannelMask;
2181 desc->mSamplingRate = mSampleRate;
2182 desc->mFormat = mFormat;
2183 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002184 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002185 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002186 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002187 break;
2188
Eric Laurent73e26b62015-04-27 16:55:58 -07002189 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002190 default:
2191 break;
2192 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002193 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002194}
2195
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002196void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002197{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002198 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002199}
2200
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002201void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002202{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002203 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204}
2205
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002206void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002207{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002208 mCallbackThread->setAsyncError();
2209}
2210
Eric Laurent3b4529e2013-09-05 18:09:19 -07002211void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002212{
2213 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002214 // reject out of sequence requests
2215 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2216 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002217 mWaitWorkCV.signal();
2218 }
2219}
2220
Eric Laurent3b4529e2013-09-05 18:09:19 -07002221void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002222{
2223 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002224 // reject out of sequence requests
2225 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2226 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002227 mWaitWorkCV.signal();
2228 }
2229}
2230
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002231void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002232{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002233 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002234 mSampleRate = mOutput->getSampleRate();
2235 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002236 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002237 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002238 }
Andy Hung9a592762014-07-21 21:56:01 -07002239 if ((mType == MIXER || mType == DUPLICATING)
2240 && !isValidPcmSinkChannelMask(mChannelMask)) {
2241 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2242 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002243 }
Andy Hunge5412692014-05-16 11:25:07 -07002244 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002245
2246 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002247 status_t result = mOutput->stream->getFormat(&mHALFormat);
2248 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002249 // Get format from the shim, which will be different than the HAL format
2250 // if playing compressed audio over HDMI passthrough.
2251 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002252 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002253 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002254 }
Andy Hung6146c082014-03-18 11:56:15 -07002255 if ((mType == MIXER || mType == DUPLICATING)
2256 && !isValidPcmSinkFormat(mFormat)) {
2257 LOG_FATAL("HAL format %#x not supported for mixed output",
2258 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002259 }
Phil Burk062e67a2015-02-11 13:40:50 -08002260 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002261 result = mOutput->stream->getBufferSize(&mBufferSize);
2262 LOG_ALWAYS_FATAL_IF(result != OK,
2263 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002264 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002265 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002266 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002267 mFrameCount);
2268 }
2269
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002270 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2271 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002272 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002273 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002274 }
2275 }
2276
Eric Laurentd1f69b02014-12-15 14:33:13 -08002277 mHwSupportsPause = false;
2278 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002279 bool supportsPause = false, supportsResume = false;
2280 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2281 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002282 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002283 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002284 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002285 } else if (supportsResume) {
2286 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002287 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002288 }
2289 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002290 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2291 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2292 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002293
Andy Hungfbfc3952015-01-15 13:33:51 -08002294 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2295 // For best precision, we use float instead of the associated output
2296 // device format (typically PCM 16 bit).
2297
2298 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2299 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2300 mBufferSize = mFrameSize * mFrameCount;
2301
2302 // TODO: We currently use the associated output device channel mask and sample rate.
2303 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2304 // (if a valid mask) to avoid premature downmix.
2305 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2306 // instead of the output device sample rate to avoid loss of high frequency information.
2307 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2308 }
2309
Andy Hung09a50072014-02-27 14:30:47 -08002310 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002311 double multiplier = 1.0;
2312 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2313 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002314 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2315 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002316
Eric Laurent81784c32012-11-19 14:55:58 -08002317 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2318 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2319 maxNormalFrameCount = maxNormalFrameCount & ~15;
2320 if (maxNormalFrameCount < minNormalFrameCount) {
2321 maxNormalFrameCount = minNormalFrameCount;
2322 }
2323 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2324 if (multiplier <= 1.0) {
2325 multiplier = 1.0;
2326 } else if (multiplier <= 2.0) {
2327 if (2 * mFrameCount <= maxNormalFrameCount) {
2328 multiplier = 2.0;
2329 } else {
2330 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2331 }
2332 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002333 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002334 }
2335 }
2336 mNormalFrameCount = multiplier * mFrameCount;
2337 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002338 if (mType == MIXER || mType == DUPLICATING) {
2339 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2340 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002341 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002342 mNormalFrameCount);
2343
Andy Hung08fb1742015-05-31 23:22:10 -07002344 // Check if we want to throttle the processing to no more than 2x normal rate
2345 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002346 mThreadThrottleTimeMs = 0;
2347 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002348 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2349
Andy Hung010a1a12014-03-13 13:57:33 -07002350 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2351 // Originally this was int16_t[] array, need to remove legacy implications.
2352 free(mSinkBuffer);
2353 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002354 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2355 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2356 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002357 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002358
Andy Hung69aed5f2014-02-25 17:24:40 -08002359 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2360 // drives the output.
2361 free(mMixerBuffer);
2362 mMixerBuffer = NULL;
2363 if (mMixerBufferEnabled) {
2364 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2365 mMixerBufferSize = mNormalFrameCount * mChannelCount
2366 * audio_bytes_per_sample(mMixerBufferFormat);
2367 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2368 }
Andy Hung98ef9782014-03-04 14:46:50 -08002369 free(mEffectBuffer);
2370 mEffectBuffer = NULL;
2371 if (mEffectBufferEnabled) {
2372 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2373 mEffectBufferSize = mNormalFrameCount * mChannelCount
2374 * audio_bytes_per_sample(mEffectBufferFormat);
2375 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2376 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002377
Eric Laurent81784c32012-11-19 14:55:58 -08002378 // force reconfiguration of effect chains and engines to take new buffer size and audio
2379 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002380 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002381 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2382 // matter.
2383 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2384 Vector< sp<EffectChain> > effectChains = mEffectChains;
2385 for (size_t i = 0; i < effectChains.size(); i ++) {
2386 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2387 }
2388}
2389
2390
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002391status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002392{
2393 if (halFrames == NULL || dspFrames == NULL) {
2394 return BAD_VALUE;
2395 }
2396 Mutex::Autolock _l(mLock);
2397 if (initCheck() != NO_ERROR) {
2398 return INVALID_OPERATION;
2399 }
Andy Hung818e7a32016-02-16 18:08:07 -08002400 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002401 *halFrames = framesWritten;
2402
2403 if (isSuspended()) {
2404 // return an estimation of rendered frames when the output is suspended
2405 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002406 *dspFrames = (uint32_t)
2407 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002408 return NO_ERROR;
2409 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002410 status_t status;
2411 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002412 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002413 *dspFrames = (size_t)frames;
2414 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002415 }
2416}
2417
Eric Laurent4c415062016-06-17 16:14:16 -07002418// hasAudioSession_l() must be called with ThreadBase::mLock held
2419uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002420{
Eric Laurent81784c32012-11-19 14:55:58 -08002421 uint32_t result = 0;
2422 if (getEffectChain_l(sessionId) != 0) {
2423 result = EFFECT_SESSION;
2424 }
2425
2426 for (size_t i = 0; i < mTracks.size(); ++i) {
2427 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002428 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002429 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002430 if (track->isFastTrack()) {
2431 result |= FAST_SESSION;
2432 }
Eric Laurent81784c32012-11-19 14:55:58 -08002433 break;
2434 }
2435 }
2436
2437 return result;
2438}
2439
Glenn Kastend848eb42016-03-08 13:42:11 -08002440uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002441{
2442 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2443 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2444 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2445 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2446 }
2447 for (size_t i = 0; i < mTracks.size(); i++) {
2448 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002449 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002450 return AudioSystem::getStrategyForStream(track->streamType());
2451 }
2452 }
2453 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2454}
2455
2456
Phil Burk062e67a2015-02-11 13:40:50 -08002457AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002458{
2459 Mutex::Autolock _l(mLock);
2460 return mOutput;
2461}
2462
Phil Burk062e67a2015-02-11 13:40:50 -08002463AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002464{
2465 Mutex::Autolock _l(mLock);
2466 AudioStreamOut *output = mOutput;
2467 mOutput = NULL;
2468 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2469 // must push a NULL and wait for ack
2470 mOutputSink.clear();
2471 mPipeSink.clear();
2472 mNormalSink.clear();
2473 return output;
2474}
2475
2476// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002477sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002478{
2479 if (mOutput == NULL) {
2480 return NULL;
2481 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002482 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002483}
2484
2485uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2486{
2487 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2488}
2489
2490status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2491{
2492 if (!isValidSyncEvent(event)) {
2493 return BAD_VALUE;
2494 }
2495
2496 Mutex::Autolock _l(mLock);
2497
2498 for (size_t i = 0; i < mTracks.size(); ++i) {
2499 sp<Track> track = mTracks[i];
2500 if (event->triggerSession() == track->sessionId()) {
2501 (void) track->setSyncEvent(event);
2502 return NO_ERROR;
2503 }
2504 }
2505
2506 return NAME_NOT_FOUND;
2507}
2508
2509bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2510{
2511 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2512}
2513
2514void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2515 const Vector< sp<Track> >& tracksToRemove)
2516{
2517 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002518 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002519 for (size_t i = 0 ; i < count ; i++) {
2520 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002521 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002522 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002523 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002524#ifdef ADD_BATTERY_DATA
2525 // to track the speaker usage
2526 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2527#endif
2528 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002529 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002530 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002531 }
Eric Laurent81784c32012-11-19 14:55:58 -08002532 }
2533 }
2534 }
Eric Laurent81784c32012-11-19 14:55:58 -08002535}
2536
2537void AudioFlinger::PlaybackThread::checkSilentMode_l()
2538{
2539 if (!mMasterMute) {
2540 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002541 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2542 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2543 return;
2544 }
Eric Laurent81784c32012-11-19 14:55:58 -08002545 if (property_get("ro.audio.silent", value, "0") > 0) {
2546 char *endptr;
2547 unsigned long ul = strtoul(value, &endptr, 0);
2548 if (*endptr == '\0' && ul != 0) {
2549 ALOGD("Silence is golden");
2550 // The setprop command will not allow a property to be changed after
2551 // the first time it is set, so we don't have to worry about un-muting.
2552 setMasterMute_l(true);
2553 }
2554 }
2555 }
2556}
2557
2558// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002559ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002560{
Eric Laurent81784c32012-11-19 14:55:58 -08002561 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002562 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002563 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002564
2565 // If an NBAIO sink is present, use it to write the normal mixer's submix
2566 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002567
Andy Hung010a1a12014-03-13 13:57:33 -07002568 const size_t count = mBytesRemaining / mFrameSize;
2569
Simon Wilson2d590962012-11-29 15:18:50 -08002570 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002571 // update the setpoint when AudioFlinger::mScreenState changes
2572 uint32_t screenState = AudioFlinger::mScreenState;
2573 if (screenState != mScreenState) {
2574 mScreenState = screenState;
2575 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2576 if (pipe != NULL) {
2577 pipe->setAvgFrames((mScreenState & 1) ?
2578 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2579 }
2580 }
Andy Hung010a1a12014-03-13 13:57:33 -07002581 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002582 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002583 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002584 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002585 } else {
2586 bytesWritten = framesWritten;
2587 }
2588 // otherwise use the HAL / AudioStreamOut directly
2589 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002591
Eric Laurentbfb1b832013-01-07 09:53:42 -08002592 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002593 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2594 mWriteAckSequence += 2;
2595 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002596 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002597 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002598 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002599 // FIXME We should have an implementation of timestamps for direct output threads.
2600 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002601 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002602
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603 if (mUseAsyncWrite &&
2604 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2605 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002606 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002607 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002608 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002609 }
Eric Laurent81784c32012-11-19 14:55:58 -08002610 }
2611
Eric Laurent81784c32012-11-19 14:55:58 -08002612 mNumWrites++;
2613 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002614 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002615 return bytesWritten;
2616}
2617
2618void AudioFlinger::PlaybackThread::threadLoop_drain()
2619{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002620 bool supportsDrain = false;
2621 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002622 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2623 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002624 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2625 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002626 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002627 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002628 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002629 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002630 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002631 }
2632}
2633
2634void AudioFlinger::PlaybackThread::threadLoop_exit()
2635{
Eric Laurent275e8e92014-11-30 15:14:47 -08002636 {
2637 Mutex::Autolock _l(mLock);
2638 for (size_t i = 0; i < mTracks.size(); i++) {
2639 sp<Track> track = mTracks[i];
2640 track->invalidate();
2641 }
2642 }
Eric Laurent81784c32012-11-19 14:55:58 -08002643}
2644
2645/*
2646The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002647 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002648 - mActiveSleepTimeUs from activeSleepTimeUs()
2649 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002650 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2651 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002652 - maxPeriod from frame count and sample rate (MIXER only)
2653
2654The parameters that affect these derived values are:
2655 - frame count
2656 - frame size
2657 - sample rate
2658 - device type: A2DP or not
2659 - device latency
2660 - format: PCM or not
2661 - active sleep time
2662 - idle sleep time
2663*/
2664
2665void AudioFlinger::PlaybackThread::cacheParameters_l()
2666{
Andy Hung25c2dac2014-02-27 14:56:00 -08002667 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002668 mActiveSleepTimeUs = activeSleepTimeUs();
2669 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002670
2671 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2672 // truncating audio when going to standby.
2673 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2674 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2675 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2676 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2677 }
2678 }
Eric Laurent81784c32012-11-19 14:55:58 -08002679}
2680
Eric Laurent13084622016-05-17 10:51:49 -07002681bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002682{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002683 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002684 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002685 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002686 size_t size = mTracks.size();
2687 for (size_t i = 0; i < size; i++) {
2688 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002689 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002690 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002691 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002692 }
2693 }
Eric Laurent13084622016-05-17 10:51:49 -07002694 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002695}
2696
Haynes Mathew George05317d22016-05-03 16:34:26 -07002697void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2698{
2699 Mutex::Autolock _l(mLock);
2700 invalidateTracks_l(streamType);
2701}
2702
Eric Laurent81784c32012-11-19 14:55:58 -08002703status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2704{
Glenn Kastend848eb42016-03-08 13:42:11 -08002705 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002706 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2707 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002708 bool ownsBuffer = false;
2709
2710 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002711 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002712 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002713 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002714 if (mType != DIRECT) {
2715 size_t numSamples = mNormalFrameCount * mChannelCount;
2716 buffer = new int16_t[numSamples];
2717 memset(buffer, 0, numSamples * sizeof(int16_t));
2718 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2719 ownsBuffer = true;
2720 }
2721
2722 // Attach all tracks with same session ID to this chain.
2723 for (size_t i = 0; i < mTracks.size(); ++i) {
2724 sp<Track> track = mTracks[i];
2725 if (session == track->sessionId()) {
2726 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2727 buffer);
2728 track->setMainBuffer(buffer);
2729 chain->incTrackCnt();
2730 }
2731 }
2732
2733 // indicate all active tracks in the chain
Eric Laurent9cab7462016-11-10 13:05:20 -08002734 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2735 sp<Track> track = mActiveTracks[i].promote();
2736 if (track == 0) {
2737 continue;
2738 }
Eric Laurent81784c32012-11-19 14:55:58 -08002739 if (session == track->sessionId()) {
2740 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2741 chain->incActiveTrackCnt();
2742 }
2743 }
2744 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002745 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002746 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002747 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2748 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002749 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002750 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002751 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2752 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002753 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002754 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002755 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002756 // Effect chain for other sessions are inserted at beginning of effect
2757 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002758 // sessions is not important.
2759 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2760 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2761 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002762 size_t size = mEffectChains.size();
2763 size_t i = 0;
2764 for (i = 0; i < size; i++) {
2765 if (mEffectChains[i]->sessionId() < session) {
2766 break;
2767 }
2768 }
2769 mEffectChains.insertAt(chain, i);
2770 checkSuspendOnAddEffectChain_l(chain);
2771
2772 return NO_ERROR;
2773}
2774
2775size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2776{
Glenn Kastend848eb42016-03-08 13:42:11 -08002777 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002778
2779 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2780
2781 for (size_t i = 0; i < mEffectChains.size(); i++) {
2782 if (chain == mEffectChains[i]) {
2783 mEffectChains.removeAt(i);
2784 // detach all active tracks from the chain
Eric Laurent9cab7462016-11-10 13:05:20 -08002785 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2786 sp<Track> track = mActiveTracks[i].promote();
2787 if (track == 0) {
2788 continue;
2789 }
Eric Laurent81784c32012-11-19 14:55:58 -08002790 if (session == track->sessionId()) {
2791 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2792 chain.get(), session);
2793 chain->decActiveTrackCnt();
2794 }
2795 }
2796
2797 // detach all tracks with same session ID from this chain
2798 for (size_t i = 0; i < mTracks.size(); ++i) {
2799 sp<Track> track = mTracks[i];
2800 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002801 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002802 chain->decTrackCnt();
2803 }
2804 }
2805 break;
2806 }
2807 }
2808 return mEffectChains.size();
2809}
2810
2811status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002812 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002813{
2814 Mutex::Autolock _l(mLock);
2815 return attachAuxEffect_l(track, EffectId);
2816}
2817
2818status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002819 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002820{
2821 status_t status = NO_ERROR;
2822
2823 if (EffectId == 0) {
2824 track->setAuxBuffer(0, NULL);
2825 } else {
2826 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2827 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2828 if (effect != 0) {
2829 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2830 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2831 } else {
2832 status = INVALID_OPERATION;
2833 }
2834 } else {
2835 status = BAD_VALUE;
2836 }
2837 }
2838 return status;
2839}
2840
2841void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2842{
2843 for (size_t i = 0; i < mTracks.size(); ++i) {
2844 sp<Track> track = mTracks[i];
2845 if (track->auxEffectId() == effectId) {
2846 attachAuxEffect_l(track, 0);
2847 }
2848 }
2849}
2850
2851bool AudioFlinger::PlaybackThread::threadLoop()
2852{
2853 Vector< sp<Track> > tracksToRemove;
2854
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002855 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002856 nsecs_t lastWriteFinished = -1; // time last server write completed
2857 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002858
2859 // MIXER
2860 nsecs_t lastWarning = 0;
2861
2862 // DUPLICATING
2863 // FIXME could this be made local to while loop?
2864 writeFrames = 0;
2865
Eric Laurent9cab7462016-11-10 13:05:20 -08002866 int lastGeneration = 0;
2867
Eric Laurent81784c32012-11-19 14:55:58 -08002868 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002869 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002870
2871 if (mType == MIXER) {
2872 sleepTimeShift = 0;
2873 }
2874
2875 CpuStats cpuStats;
2876 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2877
2878 acquireWakeLock();
2879
Glenn Kasten9e58b552013-01-18 15:09:48 -08002880 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2881 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2882 // and then that string will be logged at the next convenient opportunity.
2883 const char *logString = NULL;
2884
Eric Laurent664539d2013-09-23 18:24:31 -07002885 checkSilentMode_l();
2886
Eric Laurent81784c32012-11-19 14:55:58 -08002887 while (!exitPending())
2888 {
2889 cpuStats.sample(myName);
2890
2891 Vector< sp<EffectChain> > effectChains;
2892
Eric Laurent81784c32012-11-19 14:55:58 -08002893 { // scope for mLock
2894
2895 Mutex::Autolock _l(mLock);
2896
Eric Laurent021cf962014-05-13 10:18:14 -07002897 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002898
Glenn Kasten9e58b552013-01-18 15:09:48 -08002899 if (logString != NULL) {
2900 mNBLogWriter->logTimestamp();
2901 mNBLogWriter->log(logString);
2902 logString = NULL;
2903 }
2904
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002905 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002906 // and associate with the sink frames written out. We need
2907 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002908 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002909 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002910 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002911 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002912 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002913 ExtendedTimestamp timestamp; // use private copy to fetch
2914 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002915
2916 // We keep track of the last valid kernel position in case we are in underrun
2917 // and the normal mixer period is the same as the fast mixer period, or there
2918 // is some error from the HAL.
2919 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2920 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2921 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2922 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2923 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2924
2925 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2926 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2927 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2928 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002929 }
2930
2931 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2932 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002933 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002934 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002935 }
2936
Andy Hung818e7a32016-02-16 18:08:07 -08002937 // copy over kernel info
2938 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07002939 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
2940 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08002941 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2942 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002943 }
2944 // mFramesWritten for non-offloaded tracks are contiguous
2945 // even after standby() is called. This is useful for the track frame
2946 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07002947 bool serverLocationUpdate = false;
2948 if (mFramesWritten != lastFramesWritten) {
2949 serverLocationUpdate = true;
2950 lastFramesWritten = mFramesWritten;
2951 }
2952 // Only update timestamps if there is a meaningful change.
2953 // Either the kernel timestamp must be valid or we have written something.
2954 if (kernelLocationUpdate || serverLocationUpdate) {
2955 if (serverLocationUpdate) {
2956 // use the time before we called the HAL write - it is a bit more accurate
2957 // to when the server last read data than the current time here.
2958 //
2959 // If we haven't written anything, mLastWriteTime will be -1
2960 // and we use systemTime().
2961 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2962 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
2963 ? systemTime() : mLastWriteTime;
2964 }
Eric Laurent9cab7462016-11-10 13:05:20 -08002965 const size_t size = mActiveTracks.size();
2966 for (size_t i = 0; i < size; ++i) {
2967 sp<Track> t = mActiveTracks[i].promote();
2968 if (t != 0 && !t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07002969 t->updateTrackFrameInfo(
2970 t->mAudioTrackServerProxy->framesReleased(),
2971 mFramesWritten,
2972 mTimestamp);
2973 }
Andy Hunge10393e2015-06-12 13:59:33 -07002974 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002975 }
2976
Eric Laurent81784c32012-11-19 14:55:58 -08002977 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002978 if (mSignalPending) {
2979 // A signal was raised while we were unlocked
2980 mSignalPending = false;
2981 } else if (waitingAsyncCallback_l()) {
2982 if (exitPending()) {
2983 break;
2984 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002985 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07002986 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07002987 releaseWakeLock_l();
2988 released = true;
Eric Laurent9cab7462016-11-10 13:05:20 -08002989 mWakeLockUids.clear();
2990 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07002991 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002992 ALOGV("wait async completion");
2993 mWaitWorkCV.wait(mLock);
2994 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002995 if (released) {
2996 acquireWakeLock_l();
2997 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002998 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2999 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003000
3001 continue;
3002 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003003 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003004 isSuspended()) {
3005 // put audio hardware into standby after short delay
3006 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003007
3008 threadLoop_standby();
3009
3010 mStandby = true;
3011 }
3012
3013 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3014 // we're about to wait, flush the binder command buffer
3015 IPCThreadState::self()->flushCommands();
3016
3017 clearOutputTracks();
3018
3019 if (exitPending()) {
3020 break;
3021 }
3022
3023 releaseWakeLock_l();
Eric Laurent9cab7462016-11-10 13:05:20 -08003024 mWakeLockUids.clear();
3025 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003026 // wait until we have something to do...
3027 ALOGV("%s going to sleep", myName.string());
3028 mWaitWorkCV.wait(mLock);
3029 ALOGV("%s waking up", myName.string());
3030 acquireWakeLock_l();
3031
3032 mMixerStatus = MIXER_IDLE;
3033 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3034 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003035 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003036 checkSilentMode_l();
3037
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003038 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3039 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003040 if (mType == MIXER) {
3041 sleepTimeShift = 0;
3042 }
3043
3044 continue;
3045 }
3046 }
Eric Laurent81784c32012-11-19 14:55:58 -08003047 // mMixerStatusIgnoringFastTracks is also updated internally
3048 mMixerStatus = prepareTracks_l(&tracksToRemove);
3049
Eric Laurent9cab7462016-11-10 13:05:20 -08003050 // compare with previously applied list
3051 if (lastGeneration != mActiveTracksGeneration) {
3052 // update wakelock
3053 updateWakeLockUids_l(mWakeLockUids);
3054 lastGeneration = mActiveTracksGeneration;
3055 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003056
Eric Laurent81784c32012-11-19 14:55:58 -08003057 // prevent any changes in effect chain list and in each effect chain
3058 // during mixing and effect process as the audio buffers could be deleted
3059 // or modified if an effect is created or deleted
3060 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003061 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003062
Eric Laurentbfb1b832013-01-07 09:53:42 -08003063 if (mBytesRemaining == 0) {
3064 mCurrentWriteLength = 0;
3065 if (mMixerStatus == MIXER_TRACKS_READY) {
3066 // threadLoop_mix() sets mCurrentWriteLength
3067 threadLoop_mix();
3068 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3069 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003070 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003071 // must be written to HAL
3072 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003073 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003074 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003075 }
3076 }
Andy Hung98ef9782014-03-04 14:46:50 -08003077 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003078 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003079 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3080 // or mSinkBuffer (if there are no effects).
3081 //
3082 // This is done pre-effects computation; if effects change to
3083 // support higher precision, this needs to move.
3084 //
3085 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003086 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003087 if (mMixerBufferValid) {
3088 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3089 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3090
Andy Hung2ddee192015-12-18 17:34:44 -08003091 // mono blend occurs for mixer threads only (not direct or offloaded)
3092 // and is handled here if we're going directly to the sink.
3093 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003094 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3095 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003096 }
3097
Andy Hung98ef9782014-03-04 14:46:50 -08003098 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3099 mNormalFrameCount * mChannelCount);
3100 }
3101
Eric Laurentbfb1b832013-01-07 09:53:42 -08003102 mBytesRemaining = mCurrentWriteLength;
3103 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003104 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3105 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3106 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3107 mBytesWritten += mBytesRemaining;
3108 mFramesWritten += framesRemaining;
3109 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003110 mBytesRemaining = 0;
3111 }
Eric Laurent81784c32012-11-19 14:55:58 -08003112
Eric Laurentbfb1b832013-01-07 09:53:42 -08003113 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003114 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003115 for (size_t i = 0; i < effectChains.size(); i ++) {
3116 effectChains[i]->process_l();
3117 }
Eric Laurent81784c32012-11-19 14:55:58 -08003118 }
3119 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003120 // Process effect chains for offloaded thread even if no audio
3121 // was read from audio track: process only updates effect state
3122 // and thus does have to be synchronized with audio writes but may have
3123 // to be called while waiting for async write callback
3124 if (mType == OFFLOAD) {
3125 for (size_t i = 0; i < effectChains.size(); i ++) {
3126 effectChains[i]->process_l();
3127 }
3128 }
Eric Laurent81784c32012-11-19 14:55:58 -08003129
Andy Hung98ef9782014-03-04 14:46:50 -08003130 // Only if the Effects buffer is enabled and there is data in the
3131 // Effects buffer (buffer valid), we need to
3132 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003133 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003134 if (mEffectBufferValid) {
3135 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003136
3137 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003138 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3139 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003140 }
3141
Andy Hung98ef9782014-03-04 14:46:50 -08003142 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3143 mNormalFrameCount * mChannelCount);
3144 }
3145
Eric Laurent81784c32012-11-19 14:55:58 -08003146 // enable changes in effect chain
3147 unlockEffectChains(effectChains);
3148
Eric Laurentbfb1b832013-01-07 09:53:42 -08003149 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003150 // mSleepTimeUs == 0 means we must write to audio hardware
3151 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003152 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003153 // We save lastWriteFinished here, as previousLastWriteFinished,
3154 // for throttling. On thread start, previousLastWriteFinished will be
3155 // set to -1, which properly results in no throttling after the first write.
3156 nsecs_t previousLastWriteFinished = lastWriteFinished;
3157 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003158 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003159 // FIXME rewrite to reduce number of system calls
3160 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003161 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003162 lastWriteFinished = systemTime();
3163 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164 if (ret < 0) {
3165 mBytesRemaining = 0;
3166 } else {
3167 mBytesWritten += ret;
3168 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003169 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003170 }
3171 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3172 (mMixerStatus == MIXER_DRAIN_ALL)) {
3173 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003174 }
Andy Hung08fb1742015-05-31 23:22:10 -07003175 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003176 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003177 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003178 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003179 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003180 ATRACE_NAME("underrun");
3181 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003182 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003183 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003184 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003185 }
Andy Hung08fb1742015-05-31 23:22:10 -07003186
3187 if (mThreadThrottle
3188 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3189 && ret > 0) { // we wrote something
3190 // Limit MixerThread data processing to no more than twice the
3191 // expected processing rate.
3192 //
3193 // This helps prevent underruns with NuPlayer and other applications
3194 // which may set up buffers that are close to the minimum size, or use
3195 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3196 //
3197 // The throttle smooths out sudden large data drains from the device,
3198 // e.g. when it comes out of standby, which often causes problems with
3199 // (1) mixer threads without a fast mixer (which has its own warm-up)
3200 // (2) minimum buffer sized tracks (even if the track is full,
3201 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003202 //
3203 // Total time spent in last processing cycle equals time spent in
3204 // 1. threadLoop_write, as well as time spent in
3205 // 2. threadLoop_mix (significant for heavy mixing, especially
3206 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003207
Andy Hung69488c42016-05-16 18:43:33 -07003208 // it's OK if deltaMs is an overestimate.
3209 const int32_t deltaMs =
3210 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003211 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3212 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3213 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003214 // notify of throttle start on verbose log
3215 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3216 "mixer(%p) throttle begin:"
3217 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003218 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003219 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003220 // Throttle must be attributed to the previous mixer loop's write time
3221 // to allow back-to-back throttling.
3222 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003223 } else {
3224 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3225 if (diff > 0) {
3226 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003227 // but prevent spamming for bluetooth
3228 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3229 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003230 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3231 }
Andy Hung08fb1742015-05-31 23:22:10 -07003232 }
3233 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003234 }
Eric Laurent81784c32012-11-19 14:55:58 -08003235
Eric Laurentbfb1b832013-01-07 09:53:42 -08003236 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003237 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003238 Mutex::Autolock _l(mLock);
3239 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3240 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003241 }
Glenn Kastene7754022014-10-31 12:11:26 -07003242 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003243 }
Eric Laurent81784c32012-11-19 14:55:58 -08003244 }
3245
3246 // Finally let go of removed track(s), without the lock held
3247 // since we can't guarantee the destructors won't acquire that
3248 // same lock. This will also mutate and push a new fast mixer state.
3249 threadLoop_removeTracks(tracksToRemove);
3250 tracksToRemove.clear();
3251
3252 // FIXME I don't understand the need for this here;
3253 // it was in the original code but maybe the
3254 // assignment in saveOutputTracks() makes this unnecessary?
3255 clearOutputTracks();
3256
3257 // Effect chains will be actually deleted here if they were removed from
3258 // mEffectChains list during mixing or effects processing
3259 effectChains.clear();
3260
3261 // FIXME Note that the above .clear() is no longer necessary since effectChains
3262 // is now local to this block, but will keep it for now (at least until merge done).
3263 }
3264
Eric Laurentbfb1b832013-01-07 09:53:42 -08003265 threadLoop_exit();
3266
Eric Laurentcf817a22014-08-04 20:36:31 -07003267 if (!mStandby) {
3268 threadLoop_standby();
3269 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003270 }
3271
3272 releaseWakeLock();
Eric Laurent9cab7462016-11-10 13:05:20 -08003273 mWakeLockUids.clear();
3274 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003275
3276 ALOGV("Thread %p type %d exiting", this, mType);
3277 return false;
3278}
3279
Eric Laurentbfb1b832013-01-07 09:53:42 -08003280// removeTracks_l() must be called with ThreadBase::mLock held
3281void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3282{
3283 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003284 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003285 for (size_t i=0 ; i<count ; i++) {
3286 const sp<Track>& track = tracksToRemove.itemAt(i);
3287 mActiveTracks.remove(track);
Eric Laurent9cab7462016-11-10 13:05:20 -08003288 mWakeLockUids.remove(track->uid());
3289 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003290 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3291 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3292 if (chain != 0) {
3293 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3294 track->sessionId());
3295 chain->decActiveTrackCnt();
3296 }
3297 if (track->isTerminated()) {
3298 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003299 } else { // inactive but not terminated
3300 char buffer[256];
3301 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3302 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003303 }
3304 }
3305 }
3306
3307}
Eric Laurent81784c32012-11-19 14:55:58 -08003308
Eric Laurentaccc1472013-09-20 09:36:34 -07003309status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3310{
3311 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003312 ExtendedTimestamp ets;
3313 status_t status = mNormalSink->getTimestamp(ets);
3314 if (status == NO_ERROR) {
3315 status = ets.getBestTimestamp(&timestamp);
3316 }
3317 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003318 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003319 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003320 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003321 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003322 timestamp.mPosition = (uint32_t)position64;
3323 return NO_ERROR;
3324 }
3325 }
3326 return INVALID_OPERATION;
3327}
Eric Laurent1c333e22014-05-20 10:48:17 -07003328
Eric Laurent054d9d32015-04-24 08:48:48 -07003329status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3330 audio_patch_handle_t *handle)
3331{
Andy Hungf60abce2016-08-26 11:37:54 -07003332 status_t status;
3333 if (property_get_bool("af.patch_park", false /* default_value */)) {
3334 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3335 // or if HAL does not properly lock against access.
3336 AutoPark<FastMixer> park(mFastMixer);
3337 status = PlaybackThread::createAudioPatch_l(patch, handle);
3338 } else {
3339 status = PlaybackThread::createAudioPatch_l(patch, handle);
3340 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003341 return status;
3342}
3343
Eric Laurent1c333e22014-05-20 10:48:17 -07003344status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3345 audio_patch_handle_t *handle)
3346{
3347 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003348
3349 // store new device and send to effects
3350 audio_devices_t type = AUDIO_DEVICE_NONE;
3351 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3352 type |= patch->sinks[i].ext.device.type;
3353 }
3354
3355#ifdef ADD_BATTERY_DATA
3356 // when changing the audio output device, call addBatteryData to notify
3357 // the change
3358 if (mOutDevice != type) {
3359 uint32_t params = 0;
3360 // check whether speaker is on
3361 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3362 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003363 }
3364
Eric Laurent054d9d32015-04-24 08:48:48 -07003365 audio_devices_t deviceWithoutSpeaker
3366 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3367 // check if any other device (except speaker) is on
3368 if (type & deviceWithoutSpeaker) {
3369 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3370 }
3371
3372 if (params != 0) {
3373 addBatteryData(params);
3374 }
3375 }
3376#endif
3377
3378 for (size_t i = 0; i < mEffectChains.size(); i++) {
3379 mEffectChains[i]->setDevice_l(type);
3380 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003381
3382 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3383 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3384 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003385 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003386 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003387
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003388 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003389 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3390 status = hwDevice->createAudioPatch(patch->num_sources,
3391 patch->sources,
3392 patch->num_sinks,
3393 patch->sinks,
3394 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003395 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003396 char *address;
3397 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3398 //FIXME: we only support address on first sink with HAL version < 3.0
3399 address = audio_device_address_to_parameter(
3400 patch->sinks[0].ext.device.type,
3401 patch->sinks[0].ext.device.address);
3402 } else {
3403 address = (char *)calloc(1, 1);
3404 }
3405 AudioParameter param = AudioParameter(String8(address));
3406 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003407 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003408 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003409 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003410 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003411 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003412 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003413 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3414 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003415 return status;
3416}
3417
Eric Laurent054d9d32015-04-24 08:48:48 -07003418status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3419{
Andy Hungf60abce2016-08-26 11:37:54 -07003420 status_t status;
3421 if (property_get_bool("af.patch_park", false /* default_value */)) {
3422 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3423 // or if HAL does not properly lock against access.
3424 AutoPark<FastMixer> park(mFastMixer);
3425 status = PlaybackThread::releaseAudioPatch_l(handle);
3426 } else {
3427 status = PlaybackThread::releaseAudioPatch_l(handle);
3428 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003429 return status;
3430}
3431
Eric Laurent1c333e22014-05-20 10:48:17 -07003432status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3433{
3434 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003435
3436 mOutDevice = AUDIO_DEVICE_NONE;
3437
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003438 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003439 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3440 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003441 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003442 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003443 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003444 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003445 }
3446 return status;
3447}
3448
Eric Laurent83b88082014-06-20 18:31:16 -07003449void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3450{
3451 Mutex::Autolock _l(mLock);
3452 mTracks.add(track);
3453}
3454
3455void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3456{
3457 Mutex::Autolock _l(mLock);
3458 destroyTrack_l(track);
3459}
3460
3461void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3462{
3463 ThreadBase::getAudioPortConfig(config);
3464 config->role = AUDIO_PORT_ROLE_SOURCE;
3465 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3466 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3467}
3468
Eric Laurent81784c32012-11-19 14:55:58 -08003469// ----------------------------------------------------------------------------
3470
3471AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003472 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3473 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003474 // mAudioMixer below
3475 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003476 mFastMixerFutex(0),
3477 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003478 // mOutputSink below
3479 // mPipeSink below
3480 // mNormalSink below
3481{
3482 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003483 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3484 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003485 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3486 mNormalFrameCount);
3487 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3488
Andy Hungfbfc3952015-01-15 13:33:51 -08003489 if (type == DUPLICATING) {
3490 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3491 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3492 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3493 return;
3494 }
Eric Laurent81784c32012-11-19 14:55:58 -08003495 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003496 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003497 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003498 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003499#if !LOG_NDEBUG
3500 ssize_t index =
3501#else
3502 (void)
3503#endif
3504 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003505 ALOG_ASSERT(index == 0);
3506
3507 // initialize fast mixer depending on configuration
3508 bool initFastMixer;
3509 switch (kUseFastMixer) {
3510 case FastMixer_Never:
3511 initFastMixer = false;
3512 break;
3513 case FastMixer_Always:
3514 initFastMixer = true;
3515 break;
3516 case FastMixer_Static:
3517 case FastMixer_Dynamic:
3518 initFastMixer = mFrameCount < mNormalFrameCount;
3519 break;
3520 }
3521 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003522 audio_format_t fastMixerFormat;
3523 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3524 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3525 } else {
3526 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3527 }
3528 if (mFormat != fastMixerFormat) {
3529 // change our Sink format to accept our intermediate precision
3530 mFormat = fastMixerFormat;
3531 free(mSinkBuffer);
3532 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3533 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3534 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3535 }
Eric Laurent81784c32012-11-19 14:55:58 -08003536
3537 // create a MonoPipe to connect our submix to FastMixer
3538 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003539#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003540 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003541#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003542 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003543 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003544 format.mFormat = fastMixerFormat;
3545 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3546
Eric Laurent81784c32012-11-19 14:55:58 -08003547 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3548 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3549 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3550 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3551 const NBAIO_Format offers[1] = {format};
3552 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003553#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003554 ssize_t index =
3555#else
3556 (void)
3557#endif
3558 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003559 ALOG_ASSERT(index == 0);
3560 monoPipe->setAvgFrames((mScreenState & 1) ?
3561 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3562 mPipeSink = monoPipe;
3563
Glenn Kasten46909e72013-02-26 09:20:22 -08003564#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003565 if (mTeeSinkOutputEnabled) {
3566 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003567 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3568 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003569 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003570 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003571 ALOG_ASSERT(index == 0);
3572 mTeeSink = teeSink;
3573 PipeReader *teeSource = new PipeReader(*teeSink);
3574 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003575 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003576 ALOG_ASSERT(index == 0);
3577 mTeeSource = teeSource;
3578 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003579#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003580
3581 // create fast mixer and configure it initially with just one fast track for our submix
3582 mFastMixer = new FastMixer();
3583 FastMixerStateQueue *sq = mFastMixer->sq();
3584#ifdef STATE_QUEUE_DUMP
3585 sq->setObserverDump(&mStateQueueObserverDump);
3586 sq->setMutatorDump(&mStateQueueMutatorDump);
3587#endif
3588 FastMixerState *state = sq->begin();
3589 FastTrack *fastTrack = &state->mFastTracks[0];
3590 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3591 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3592 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003593 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3594 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003595 fastTrack->mGeneration++;
3596 state->mFastTracksGen++;
3597 state->mTrackMask = 1;
3598 // fast mixer will use the HAL output sink
3599 state->mOutputSink = mOutputSink.get();
3600 state->mOutputSinkGen++;
3601 state->mFrameCount = mFrameCount;
3602 state->mCommand = FastMixerState::COLD_IDLE;
3603 // already done in constructor initialization list
3604 //mFastMixerFutex = 0;
3605 state->mColdFutexAddr = &mFastMixerFutex;
3606 state->mColdGen++;
3607 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003608#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003609 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003610#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003611 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3612 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003613 sq->end();
3614 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3615
3616 // start the fast mixer
3617 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3618 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003619 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003620
3621#ifdef AUDIO_WATCHDOG
3622 // create and start the watchdog
3623 mAudioWatchdog = new AudioWatchdog();
3624 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3625 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3626 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003627 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003628#endif
3629
Eric Laurent81784c32012-11-19 14:55:58 -08003630 }
3631
3632 switch (kUseFastMixer) {
3633 case FastMixer_Never:
3634 case FastMixer_Dynamic:
3635 mNormalSink = mOutputSink;
3636 break;
3637 case FastMixer_Always:
3638 mNormalSink = mPipeSink;
3639 break;
3640 case FastMixer_Static:
3641 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3642 break;
3643 }
3644}
3645
3646AudioFlinger::MixerThread::~MixerThread()
3647{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003648 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003649 FastMixerStateQueue *sq = mFastMixer->sq();
3650 FastMixerState *state = sq->begin();
3651 if (state->mCommand == FastMixerState::COLD_IDLE) {
3652 int32_t old = android_atomic_inc(&mFastMixerFutex);
3653 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003654 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003655 }
3656 }
3657 state->mCommand = FastMixerState::EXIT;
3658 sq->end();
3659 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3660 mFastMixer->join();
3661 // Though the fast mixer thread has exited, it's state queue is still valid.
3662 // We'll use that extract the final state which contains one remaining fast track
3663 // corresponding to our sub-mix.
3664 state = sq->begin();
3665 ALOG_ASSERT(state->mTrackMask == 1);
3666 FastTrack *fastTrack = &state->mFastTracks[0];
3667 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3668 delete fastTrack->mBufferProvider;
3669 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003670 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003671#ifdef AUDIO_WATCHDOG
3672 if (mAudioWatchdog != 0) {
3673 mAudioWatchdog->requestExit();
3674 mAudioWatchdog->requestExitAndWait();
3675 mAudioWatchdog.clear();
3676 }
3677#endif
3678 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003679 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003680 delete mAudioMixer;
3681}
3682
3683
3684uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3685{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003686 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003687 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3688 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3689 }
3690 return latency;
3691}
3692
3693
3694void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3695{
3696 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3697}
3698
Eric Laurentbfb1b832013-01-07 09:53:42 -08003699ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003700{
3701 // FIXME we should only do one push per cycle; confirm this is true
3702 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003703 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003704 FastMixerStateQueue *sq = mFastMixer->sq();
3705 FastMixerState *state = sq->begin();
3706 if (state->mCommand != FastMixerState::MIX_WRITE &&
3707 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3708 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003709
3710 // FIXME workaround for first HAL write being CPU bound on some devices
3711 ATRACE_BEGIN("write");
3712 mOutput->write((char *)mSinkBuffer, 0);
3713 ATRACE_END();
3714
Eric Laurent81784c32012-11-19 14:55:58 -08003715 int32_t old = android_atomic_inc(&mFastMixerFutex);
3716 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003717 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003718 }
3719#ifdef AUDIO_WATCHDOG
3720 if (mAudioWatchdog != 0) {
3721 mAudioWatchdog->resume();
3722 }
3723#endif
3724 }
3725 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003726#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003727 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003728 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003729#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003730 sq->end();
3731 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3732 if (kUseFastMixer == FastMixer_Dynamic) {
3733 mNormalSink = mPipeSink;
3734 }
3735 } else {
3736 sq->end(false /*didModify*/);
3737 }
3738 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003739 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003740}
3741
3742void AudioFlinger::MixerThread::threadLoop_standby()
3743{
3744 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003745 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003746 FastMixerStateQueue *sq = mFastMixer->sq();
3747 FastMixerState *state = sq->begin();
3748 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003749 // Report any frames trapped in the Monopipe
3750 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3751 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3752 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3753 "monoPipeWritten:%lld monoPipeLeft:%lld",
3754 (long long)mFramesWritten, (long long)mSuspendedFrames,
3755 (long long)mPipeSink->framesWritten(), pipeFrames);
3756 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3757
Eric Laurent81784c32012-11-19 14:55:58 -08003758 state->mCommand = FastMixerState::COLD_IDLE;
3759 state->mColdFutexAddr = &mFastMixerFutex;
3760 state->mColdGen++;
3761 mFastMixerFutex = 0;
3762 sq->end();
3763 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3764 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3765 if (kUseFastMixer == FastMixer_Dynamic) {
3766 mNormalSink = mOutputSink;
3767 }
3768#ifdef AUDIO_WATCHDOG
3769 if (mAudioWatchdog != 0) {
3770 mAudioWatchdog->pause();
3771 }
3772#endif
3773 } else {
3774 sq->end(false /*didModify*/);
3775 }
3776 }
3777 PlaybackThread::threadLoop_standby();
3778}
3779
Eric Laurentbfb1b832013-01-07 09:53:42 -08003780bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3781{
3782 return false;
3783}
3784
3785bool AudioFlinger::PlaybackThread::shouldStandby_l()
3786{
3787 return !mStandby;
3788}
3789
3790bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3791{
3792 Mutex::Autolock _l(mLock);
3793 return waitingAsyncCallback_l();
3794}
3795
Eric Laurent81784c32012-11-19 14:55:58 -08003796// shared by MIXER and DIRECT, overridden by DUPLICATING
3797void AudioFlinger::PlaybackThread::threadLoop_standby()
3798{
3799 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003800 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003801 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003802 // discard any pending drain or write ack by incrementing sequence
3803 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3804 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003805 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003806 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3807 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003808 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003809 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003810}
3811
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003812void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3813{
3814 ALOGV("signal playback thread");
3815 broadcast_l();
3816}
3817
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003818void AudioFlinger::PlaybackThread::onAsyncError()
3819{
3820 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3821 invalidateTracks((audio_stream_type_t)i);
3822 }
3823}
3824
Eric Laurent81784c32012-11-19 14:55:58 -08003825void AudioFlinger::MixerThread::threadLoop_mix()
3826{
Eric Laurent81784c32012-11-19 14:55:58 -08003827 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003828 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003829 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003830 // increase sleep time progressively when application underrun condition clears.
3831 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3832 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3833 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003834 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003835 sleepTimeShift--;
3836 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003837 mSleepTimeUs = 0;
3838 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003839 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003840
Eric Laurent81784c32012-11-19 14:55:58 -08003841}
3842
3843void AudioFlinger::MixerThread::threadLoop_sleepTime()
3844{
3845 // If no tracks are ready, sleep once for the duration of an output
3846 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003847 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003848 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003849 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3850 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3851 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003852 }
3853 // reduce sleep time in case of consecutive application underruns to avoid
3854 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3855 // duration we would end up writing less data than needed by the audio HAL if
3856 // the condition persists.
3857 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3858 sleepTimeShift++;
3859 }
3860 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003861 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003862 }
3863 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003864 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3865 // before effects processing or output.
3866 if (mMixerBufferValid) {
3867 memset(mMixerBuffer, 0, mMixerBufferSize);
3868 } else {
3869 memset(mSinkBuffer, 0, mSinkBufferSize);
3870 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003871 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003872 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3873 "anticipated start");
3874 }
3875 // TODO add standby time extension fct of effect tail
3876}
3877
3878// prepareTracks_l() must be called with ThreadBase::mLock held
3879AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3880 Vector< sp<Track> > *tracksToRemove)
3881{
3882
3883 mixer_state mixerStatus = MIXER_IDLE;
3884 // find out which tracks need to be processed
3885 size_t count = mActiveTracks.size();
3886 size_t mixedTracks = 0;
3887 size_t tracksWithEffect = 0;
3888 // counts only _active_ fast tracks
3889 size_t fastTracks = 0;
3890 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3891
3892 float masterVolume = mMasterVolume;
3893 bool masterMute = mMasterMute;
3894
3895 if (masterMute) {
3896 masterVolume = 0;
3897 }
3898 // Delegate master volume control to effect in output mix effect chain if needed
3899 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3900 if (chain != 0) {
3901 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3902 chain->setVolume_l(&v, &v);
3903 masterVolume = (float)((v + (1 << 23)) >> 24);
3904 chain.clear();
3905 }
3906
3907 // prepare a new state to push
3908 FastMixerStateQueue *sq = NULL;
3909 FastMixerState *state = NULL;
3910 bool didModify = false;
3911 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003912 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003913 sq = mFastMixer->sq();
3914 state = sq->begin();
3915 }
3916
Andy Hung69aed5f2014-02-25 17:24:40 -08003917 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003918 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003919
Eric Laurent81784c32012-11-19 14:55:58 -08003920 for (size_t i=0 ; i<count ; i++) {
Eric Laurent9cab7462016-11-10 13:05:20 -08003921 const sp<Track> t = mActiveTracks[i].promote();
3922 if (t == 0) {
3923 continue;
3924 }
Eric Laurent81784c32012-11-19 14:55:58 -08003925
3926 // this const just means the local variable doesn't change
3927 Track* const track = t.get();
3928
3929 // process fast tracks
3930 if (track->isFastTrack()) {
3931
3932 // It's theoretically possible (though unlikely) for a fast track to be created
3933 // and then removed within the same normal mix cycle. This is not a problem, as
3934 // the track never becomes active so it's fast mixer slot is never touched.
3935 // The converse, of removing an (active) track and then creating a new track
3936 // at the identical fast mixer slot within the same normal mix cycle,
3937 // is impossible because the slot isn't marked available until the end of each cycle.
3938 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003939 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003940 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3941 FastTrack *fastTrack = &state->mFastTracks[j];
3942
3943 // Determine whether the track is currently in underrun condition,
3944 // and whether it had a recent underrun.
3945 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3946 FastTrackUnderruns underruns = ftDump->mUnderruns;
3947 uint32_t recentFull = (underruns.mBitFields.mFull -
3948 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3949 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3950 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3951 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3952 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3953 uint32_t recentUnderruns = recentPartial + recentEmpty;
3954 track->mObservedUnderruns = underruns;
3955 // don't count underruns that occur while stopping or pausing
3956 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003957 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3958 recentUnderruns > 0) {
3959 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3960 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003961 } else {
3962 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003963 }
3964
3965 // This is similar to the state machine for normal tracks,
3966 // with a few modifications for fast tracks.
3967 bool isActive = true;
3968 switch (track->mState) {
3969 case TrackBase::STOPPING_1:
3970 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003971 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003972 track->mState = TrackBase::STOPPING_2;
3973 }
3974 break;
3975 case TrackBase::PAUSING:
3976 // ramp down is not yet implemented
3977 track->setPaused();
3978 break;
3979 case TrackBase::RESUMING:
3980 // ramp up is not yet implemented
3981 track->mState = TrackBase::ACTIVE;
3982 break;
3983 case TrackBase::ACTIVE:
3984 if (recentFull > 0 || recentPartial > 0) {
3985 // track has provided at least some frames recently: reset retry count
3986 track->mRetryCount = kMaxTrackRetries;
3987 }
3988 if (recentUnderruns == 0) {
3989 // no recent underruns: stay active
3990 break;
3991 }
3992 // there has recently been an underrun of some kind
3993 if (track->sharedBuffer() == 0) {
3994 // were any of the recent underruns "empty" (no frames available)?
3995 if (recentEmpty == 0) {
3996 // no, then ignore the partial underruns as they are allowed indefinitely
3997 break;
3998 }
3999 // there has recently been an "empty" underrun: decrement the retry counter
4000 if (--(track->mRetryCount) > 0) {
4001 break;
4002 }
4003 // indicate to client process that the track was disabled because of underrun;
4004 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004005 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004006 // remove from active list, but state remains ACTIVE [confusing but true]
4007 isActive = false;
4008 break;
4009 }
4010 // fall through
4011 case TrackBase::STOPPING_2:
4012 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004013 case TrackBase::STOPPED:
4014 case TrackBase::FLUSHED: // flush() while active
4015 // Check for presentation complete if track is inactive
4016 // We have consumed all the buffers of this track.
4017 // This would be incomplete if we auto-paused on underrun
4018 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004019 uint32_t latency = 0;
4020 status_t result = mOutput->stream->getLatency(&latency);
4021 ALOGE_IF(result != OK,
4022 "Error when retrieving output stream latency: %d", result);
4023 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004024 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004025 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4026 // track stays in active list until presentation is complete
4027 break;
4028 }
4029 }
4030 if (track->isStopping_2()) {
4031 track->mState = TrackBase::STOPPED;
4032 }
4033 if (track->isStopped()) {
4034 // Can't reset directly, as fast mixer is still polling this track
4035 // track->reset();
4036 // So instead mark this track as needing to be reset after push with ack
4037 resetMask |= 1 << i;
4038 }
4039 isActive = false;
4040 break;
4041 case TrackBase::IDLE:
4042 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004043 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004044 }
4045
4046 if (isActive) {
4047 // was it previously inactive?
4048 if (!(state->mTrackMask & (1 << j))) {
4049 ExtendedAudioBufferProvider *eabp = track;
4050 VolumeProvider *vp = track;
4051 fastTrack->mBufferProvider = eabp;
4052 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004053 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004054 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004055 fastTrack->mGeneration++;
4056 state->mTrackMask |= 1 << j;
4057 didModify = true;
4058 // no acknowledgement required for newly active tracks
4059 }
4060 // cache the combined master volume and stream type volume for fast mixer; this
4061 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004062 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004063 ++fastTracks;
4064 } else {
4065 // was it previously active?
4066 if (state->mTrackMask & (1 << j)) {
4067 fastTrack->mBufferProvider = NULL;
4068 fastTrack->mGeneration++;
4069 state->mTrackMask &= ~(1 << j);
4070 didModify = true;
4071 // If any fast tracks were removed, we must wait for acknowledgement
4072 // because we're about to decrement the last sp<> on those tracks.
4073 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4074 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004075 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4076 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4077 j, track->mState, state->mTrackMask, recentUnderruns,
4078 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004079 }
4080 tracksToRemove->add(track);
4081 // Avoids a misleading display in dumpsys
4082 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4083 }
4084 continue;
4085 }
4086
4087 { // local variable scope to avoid goto warning
4088
4089 audio_track_cblk_t* cblk = track->cblk();
4090
4091 // The first time a track is added we wait
4092 // for all its buffers to be filled before processing it
4093 int name = track->name();
4094 // make sure that we have enough frames to mix one full buffer.
4095 // enforce this condition only once to enable draining the buffer in case the client
4096 // app does not call stop() and relies on underrun to stop:
4097 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4098 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004099 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004100 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004101 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004102
4103 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004104 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004105 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4106 // add frames already consumed but not yet released by the resampler
4107 // because mAudioTrackServerProxy->framesReady() will include these frames
4108 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4109
Eric Laurent81784c32012-11-19 14:55:58 -08004110 uint32_t minFrames = 1;
4111 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4112 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004113 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004114 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004115
4116 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004117 if (ATRACE_ENABLED()) {
4118 // I wish we had formatted trace names
4119 char traceName[16];
4120 strcpy(traceName, "nRdy");
4121 int name = track->name();
4122 if (AudioMixer::TRACK0 <= name &&
4123 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4124 name -= AudioMixer::TRACK0;
4125 traceName[4] = (name / 10) + '0';
4126 traceName[5] = (name % 10) + '0';
4127 } else {
4128 traceName[4] = '?';
4129 traceName[5] = '?';
4130 }
4131 traceName[6] = '\0';
4132 ATRACE_INT(traceName, framesReady);
4133 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004134 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004135 !track->isPaused() && !track->isTerminated())
4136 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004137 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004138
4139 mixedTracks++;
4140
Andy Hung69aed5f2014-02-25 17:24:40 -08004141 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4142 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004143 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004144 if (track->mainBuffer() != mSinkBuffer &&
4145 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004146 if (mEffectBufferEnabled) {
4147 mEffectBufferValid = true; // Later can set directly.
4148 }
Eric Laurent81784c32012-11-19 14:55:58 -08004149 chain = getEffectChain_l(track->sessionId());
4150 // Delegate volume control to effect in track effect chain if needed
4151 if (chain != 0) {
4152 tracksWithEffect++;
4153 } else {
4154 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4155 "session %d",
4156 name, track->sessionId());
4157 }
4158 }
4159
4160
4161 int param = AudioMixer::VOLUME;
4162 if (track->mFillingUpStatus == Track::FS_FILLED) {
4163 // no ramp for the first volume setting
4164 track->mFillingUpStatus = Track::FS_ACTIVE;
4165 if (track->mState == TrackBase::RESUMING) {
4166 track->mState = TrackBase::ACTIVE;
4167 param = AudioMixer::RAMP_VOLUME;
4168 }
4169 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004170 // FIXME should not make a decision based on mServer
4171 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004172 // If the track is stopped before the first frame was mixed,
4173 // do not apply ramp
4174 param = AudioMixer::RAMP_VOLUME;
4175 }
4176
4177 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004178 uint32_t vl, vr; // in U8.24 integer format
4179 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004180 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004181 vl = vr = 0;
4182 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004183 if (track->isPausing()) {
4184 track->setPaused();
4185 }
4186 } else {
4187
4188 // read original volumes with volume control
4189 float typeVolume = mStreamTypes[track->streamType()].volume;
4190 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004191 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004192 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004193 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4194 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004195 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004196 if (vlf > GAIN_FLOAT_UNITY) {
4197 ALOGV("Track left volume out of range: %.3g", vlf);
4198 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004199 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004200 if (vrf > GAIN_FLOAT_UNITY) {
4201 ALOGV("Track right volume out of range: %.3g", vrf);
4202 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004203 }
4204 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004205 vlf *= v;
4206 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004207 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004208 // then derive vl and vr as U8.24 versions for the effect chain
4209 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4210 vl = (uint32_t) (scaleto8_24 * vlf);
4211 vr = (uint32_t) (scaleto8_24 * vrf);
4212 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004213 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004214 // send level comes from shared memory and so may be corrupt
4215 if (sendLevel > MAX_GAIN_INT) {
4216 ALOGV("Track send level out of range: %04X", sendLevel);
4217 sendLevel = MAX_GAIN_INT;
4218 }
Andy Hung6be49402014-05-30 10:42:03 -07004219 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4220 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004221 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004222
Eric Laurent81784c32012-11-19 14:55:58 -08004223 // Delegate volume control to effect in track effect chain if needed
4224 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4225 // Do not ramp volume if volume is controlled by effect
4226 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004227 // Update remaining floating point volume levels
4228 vlf = (float)vl / (1 << 24);
4229 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004230 track->mHasVolumeController = true;
4231 } else {
4232 // force no volume ramp when volume controller was just disabled or removed
4233 // from effect chain to avoid volume spike
4234 if (track->mHasVolumeController) {
4235 param = AudioMixer::VOLUME;
4236 }
4237 track->mHasVolumeController = false;
4238 }
4239
Eric Laurent81784c32012-11-19 14:55:58 -08004240 // XXX: these things DON'T need to be done each time
4241 mAudioMixer->setBufferProvider(name, track);
4242 mAudioMixer->enable(name);
4243
Andy Hung6be49402014-05-30 10:42:03 -07004244 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4245 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4246 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004247 mAudioMixer->setParameter(
4248 name,
4249 AudioMixer::TRACK,
4250 AudioMixer::FORMAT, (void *)track->format());
4251 mAudioMixer->setParameter(
4252 name,
4253 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004254 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004255 mAudioMixer->setParameter(
4256 name,
4257 AudioMixer::TRACK,
4258 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004259 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004260 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004261 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004262 if (reqSampleRate == 0) {
4263 reqSampleRate = mSampleRate;
4264 } else if (reqSampleRate > maxSampleRate) {
4265 reqSampleRate = maxSampleRate;
4266 }
Eric Laurent81784c32012-11-19 14:55:58 -08004267 mAudioMixer->setParameter(
4268 name,
4269 AudioMixer::RESAMPLE,
4270 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004271 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004272
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004273 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004274 mAudioMixer->setParameter(
4275 name,
4276 AudioMixer::TIMESTRETCH,
4277 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004278 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004279
Andy Hung69aed5f2014-02-25 17:24:40 -08004280 /*
4281 * Select the appropriate output buffer for the track.
4282 *
Andy Hung98ef9782014-03-04 14:46:50 -08004283 * Tracks with effects go into their own effects chain buffer
4284 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004285 *
4286 * Other tracks can use mMixerBuffer for higher precision
4287 * channel accumulation. If this buffer is enabled
4288 * (mMixerBufferEnabled true), then selected tracks will accumulate
4289 * into it.
4290 *
4291 */
4292 if (mMixerBufferEnabled
4293 && (track->mainBuffer() == mSinkBuffer
4294 || track->mainBuffer() == mMixerBuffer)) {
4295 mAudioMixer->setParameter(
4296 name,
4297 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004298 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004299 mAudioMixer->setParameter(
4300 name,
4301 AudioMixer::TRACK,
4302 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4303 // TODO: override track->mainBuffer()?
4304 mMixerBufferValid = true;
4305 } else {
4306 mAudioMixer->setParameter(
4307 name,
4308 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004309 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004310 mAudioMixer->setParameter(
4311 name,
4312 AudioMixer::TRACK,
4313 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4314 }
Eric Laurent81784c32012-11-19 14:55:58 -08004315 mAudioMixer->setParameter(
4316 name,
4317 AudioMixer::TRACK,
4318 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4319
4320 // reset retry count
4321 track->mRetryCount = kMaxTrackRetries;
4322
4323 // If one track is ready, set the mixer ready if:
4324 // - the mixer was not ready during previous round OR
4325 // - no other track is not ready
4326 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4327 mixerStatus != MIXER_TRACKS_ENABLED) {
4328 mixerStatus = MIXER_TRACKS_READY;
4329 }
4330 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004331 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004332 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4333 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004334 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004335 } else {
4336 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004337 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004338
Eric Laurent81784c32012-11-19 14:55:58 -08004339 // clear effect chain input buffer if an active track underruns to avoid sending
4340 // previous audio buffer again to effects
4341 chain = getEffectChain_l(track->sessionId());
4342 if (chain != 0) {
4343 chain->clearInputBuffer();
4344 }
4345
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004346 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004347 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4348 track->isStopped() || track->isPaused()) {
4349 // We have consumed all the buffers of this track.
4350 // Remove it from the list of active tracks.
4351 // TODO: use actual buffer filling status instead of latency when available from
4352 // audio HAL
4353 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004354 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004355 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4356 if (track->isStopped()) {
4357 track->reset();
4358 }
4359 tracksToRemove->add(track);
4360 }
4361 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004362 // No buffers for this track. Give it a few chances to
4363 // fill a buffer, then remove it from active list.
4364 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004365 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004366 tracksToRemove->add(track);
4367 // indicate to client process that the track was disabled because of underrun;
4368 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004369 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004370 // If one track is not ready, mark the mixer also not ready if:
4371 // - the mixer was ready during previous round OR
4372 // - no other track is ready
4373 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4374 mixerStatus != MIXER_TRACKS_READY) {
4375 mixerStatus = MIXER_TRACKS_ENABLED;
4376 }
4377 }
4378 mAudioMixer->disable(name);
4379 }
4380
4381 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004382
4383 }
4384
4385 // Push the new FastMixer state if necessary
4386 bool pauseAudioWatchdog = false;
4387 if (didModify) {
4388 state->mFastTracksGen++;
4389 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4390 if (kUseFastMixer == FastMixer_Dynamic &&
4391 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4392 state->mCommand = FastMixerState::COLD_IDLE;
4393 state->mColdFutexAddr = &mFastMixerFutex;
4394 state->mColdGen++;
4395 mFastMixerFutex = 0;
4396 if (kUseFastMixer == FastMixer_Dynamic) {
4397 mNormalSink = mOutputSink;
4398 }
4399 // If we go into cold idle, need to wait for acknowledgement
4400 // so that fast mixer stops doing I/O.
4401 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4402 pauseAudioWatchdog = true;
4403 }
Eric Laurent81784c32012-11-19 14:55:58 -08004404 }
4405 if (sq != NULL) {
4406 sq->end(didModify);
4407 sq->push(block);
4408 }
4409#ifdef AUDIO_WATCHDOG
4410 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4411 mAudioWatchdog->pause();
4412 }
4413#endif
4414
4415 // Now perform the deferred reset on fast tracks that have stopped
4416 while (resetMask != 0) {
4417 size_t i = __builtin_ctz(resetMask);
4418 ALOG_ASSERT(i < count);
4419 resetMask &= ~(1 << i);
Eric Laurent9cab7462016-11-10 13:05:20 -08004420 sp<Track> t = mActiveTracks[i].promote();
4421 if (t == 0) {
4422 continue;
4423 }
4424 Track* track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004425 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4426 track->reset();
4427 }
4428
4429 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004430 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004431
Eric Laurent97d547d2014-09-02 14:45:53 -07004432 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4433 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004434 }
4435
4436 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004437 // as long as there are effects we should clear the effects buffer, to avoid
4438 // passing a non-clean buffer to the effect chain
4439 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004440 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004441 // sink or mix buffer must be cleared if all tracks are connected to an
4442 // effect chain as in this case the mixer will not write to the sink or mix buffer
4443 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004444 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4445 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004446 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004447 if (mMixerBufferValid) {
4448 memset(mMixerBuffer, 0, mMixerBufferSize);
4449 // TODO: In testing, mSinkBuffer below need not be cleared because
4450 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4451 // after mixing.
4452 //
4453 // To enforce this guarantee:
4454 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4455 // (mixedTracks == 0 && fastTracks > 0))
4456 // must imply MIXER_TRACKS_READY.
4457 // Later, we may clear buffers regardless, and skip much of this logic.
4458 }
Andy Hung98ef9782014-03-04 14:46:50 -08004459 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004460 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004461 }
4462
4463 // if any fast tracks, then status is ready
4464 mMixerStatusIgnoringFastTracks = mixerStatus;
4465 if (fastTracks > 0) {
4466 mixerStatus = MIXER_TRACKS_READY;
4467 }
4468 return mixerStatus;
4469}
4470
Eric Laurentad7dd962016-09-22 12:38:37 -07004471// trackCountForUid_l() must be called with ThreadBase::mLock held
4472uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4473{
4474 uint32_t trackCount = 0;
4475 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004476 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004477 trackCount++;
4478 }
4479 }
4480 return trackCount;
4481}
4482
Eric Laurent81784c32012-11-19 14:55:58 -08004483// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004484int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004485 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004486{
Eric Laurentad7dd962016-09-22 12:38:37 -07004487 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4488 return -1;
4489 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004490 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004491}
4492
4493// deleteTrackName_l() must be called with ThreadBase::mLock held
4494void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4495{
4496 ALOGV("remove track (%d) and delete from mixer", name);
4497 mAudioMixer->deleteTrackName(name);
4498}
4499
Eric Laurent10351942014-05-08 18:49:52 -07004500// checkForNewParameter_l() must be called with ThreadBase::mLock held
4501bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4502 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004503{
Eric Laurent81784c32012-11-19 14:55:58 -08004504 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004505 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004506
Eric Laurent10351942014-05-08 18:49:52 -07004507 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004508
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004509 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004510
Eric Laurent10351942014-05-08 18:49:52 -07004511 AudioParameter param = AudioParameter(keyValuePair);
4512 int value;
4513 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4514 reconfig = true;
4515 }
4516 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004517 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004518 status = BAD_VALUE;
4519 } else {
4520 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004521 reconfig = true;
4522 }
Eric Laurent10351942014-05-08 18:49:52 -07004523 }
4524 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004525 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004526 status = BAD_VALUE;
4527 } else {
4528 // no need to save value, since it's constant
4529 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004530 }
Eric Laurent10351942014-05-08 18:49:52 -07004531 }
4532 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4533 // do not accept frame count changes if tracks are open as the track buffer
4534 // size depends on frame count and correct behavior would not be guaranteed
4535 // if frame count is changed after track creation
4536 if (!mTracks.isEmpty()) {
4537 status = INVALID_OPERATION;
4538 } else {
4539 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004540 }
Eric Laurent10351942014-05-08 18:49:52 -07004541 }
4542 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004543#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004544 // when changing the audio output device, call addBatteryData to notify
4545 // the change
4546 if (mOutDevice != value) {
4547 uint32_t params = 0;
4548 // check whether speaker is on
4549 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4550 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004551 }
Eric Laurent10351942014-05-08 18:49:52 -07004552
4553 audio_devices_t deviceWithoutSpeaker
4554 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4555 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004556 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004557 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4558 }
4559
4560 if (params != 0) {
4561 addBatteryData(params);
4562 }
4563 }
Eric Laurent81784c32012-11-19 14:55:58 -08004564#endif
4565
Eric Laurent10351942014-05-08 18:49:52 -07004566 // forward device change to effects that have requested to be
4567 // aware of attached audio device.
4568 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004569 a2dpDeviceChanged =
4570 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004571 mOutDevice = value;
4572 for (size_t i = 0; i < mEffectChains.size(); i++) {
4573 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004574 }
4575 }
Eric Laurent10351942014-05-08 18:49:52 -07004576 }
Eric Laurent81784c32012-11-19 14:55:58 -08004577
Eric Laurent10351942014-05-08 18:49:52 -07004578 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004579 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004580 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004581 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004582 mStandby = true;
4583 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004584 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004585 }
Eric Laurent10351942014-05-08 18:49:52 -07004586 if (status == NO_ERROR && reconfig) {
4587 readOutputParameters_l();
4588 delete mAudioMixer;
4589 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4590 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004591 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004592 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004593 if (name < 0) {
4594 break;
4595 }
4596 mTracks[i]->mName = name;
4597 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004598 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004599 }
Eric Laurent81784c32012-11-19 14:55:58 -08004600 }
4601
Eric Laurent42537be2016-01-08 17:16:42 -08004602 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004603}
4604
4605
4606void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4607{
Eric Laurent81784c32012-11-19 14:55:58 -08004608 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004609 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004610 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004611 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004612
4613 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004614 // while we are dumping it. It may be inconsistent, but it won't mutate!
4615 // This is a large object so we place it on the heap.
4616 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4617 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4618 copy->dump(fd);
4619 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004620
4621#ifdef STATE_QUEUE_DUMP
4622 // Similar for state queue
4623 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4624 observerCopy.dump(fd);
4625 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4626 mutatorCopy.dump(fd);
4627#endif
4628
Glenn Kasten46909e72013-02-26 09:20:22 -08004629#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004630 // Write the tee output to a .wav file
4631 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004632#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004633
4634#ifdef AUDIO_WATCHDOG
4635 if (mAudioWatchdog != 0) {
4636 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4637 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4638 wdCopy.dump(fd);
4639 }
4640#endif
4641}
4642
4643uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4644{
4645 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4646}
4647
4648uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4649{
4650 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4651}
4652
4653void AudioFlinger::MixerThread::cacheParameters_l()
4654{
4655 PlaybackThread::cacheParameters_l();
4656
4657 // FIXME: Relaxed timing because of a certain device that can't meet latency
4658 // Should be reduced to 2x after the vendor fixes the driver issue
4659 // increase threshold again due to low power audio mode. The way this warning
4660 // threshold is calculated and its usefulness should be reconsidered anyway.
4661 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4662}
4663
4664// ----------------------------------------------------------------------------
4665
4666AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004667 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4668 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004669 // mLeftVolFloat, mRightVolFloat
4670{
4671}
4672
Eric Laurentbfb1b832013-01-07 09:53:42 -08004673AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4674 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004675 ThreadBase::type_t type, bool systemReady)
4676 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004677 // mLeftVolFloat, mRightVolFloat
4678{
4679}
4680
Eric Laurent81784c32012-11-19 14:55:58 -08004681AudioFlinger::DirectOutputThread::~DirectOutputThread()
4682{
4683}
4684
Eric Laurent5850c4c2016-11-10 13:04:31 -08004685void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004686{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004687 float left, right;
4688
4689 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4690 left = right = 0;
4691 } else {
4692 float typeVolume = mStreamTypes[track->streamType()].volume;
4693 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004694 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004695 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4696 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4697 if (left > GAIN_FLOAT_UNITY) {
4698 left = GAIN_FLOAT_UNITY;
4699 }
4700 left *= v;
4701 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4702 if (right > GAIN_FLOAT_UNITY) {
4703 right = GAIN_FLOAT_UNITY;
4704 }
4705 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004706 }
4707
4708 if (lastTrack) {
4709 if (left != mLeftVolFloat || right != mRightVolFloat) {
4710 mLeftVolFloat = left;
4711 mRightVolFloat = right;
4712
4713 // Convert volumes from float to 8.24
4714 uint32_t vl = (uint32_t)(left * (1 << 24));
4715 uint32_t vr = (uint32_t)(right * (1 << 24));
4716
4717 // Delegate volume control to effect in track effect chain if needed
4718 // only one effect chain can be present on DirectOutputThread, so if
4719 // there is one, the track is connected to it
4720 if (!mEffectChains.isEmpty()) {
4721 mEffectChains[0]->setVolume_l(&vl, &vr);
4722 left = (float)vl / (1 << 24);
4723 right = (float)vr / (1 << 24);
4724 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004725 status_t result = mOutput->stream->setVolume(left, right);
4726 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004727 }
4728 }
4729}
4730
Phil Burk43b4dcc2015-06-09 16:53:44 -07004731void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4732{
4733 sp<Track> previousTrack = mPreviousTrack.promote();
Eric Laurent9cab7462016-11-10 13:05:20 -08004734 sp<Track> latestTrack = mLatestActiveTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004735
Eric Laurent0f0631e2015-07-06 18:01:25 -07004736 if (previousTrack != 0 && latestTrack != 0) {
4737 if (mType == DIRECT) {
4738 if (previousTrack.get() != latestTrack.get()) {
4739 mFlushPending = true;
4740 }
4741 } else /* mType == OFFLOAD */ {
4742 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4743 mFlushPending = true;
4744 }
4745 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004746 }
4747 PlaybackThread::onAddNewTrack_l();
4748}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004749
Eric Laurent81784c32012-11-19 14:55:58 -08004750AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4751 Vector< sp<Track> > *tracksToRemove
4752)
4753{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004754 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004755 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004756 bool doHwPause = false;
4757 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004758
4759 // find out which tracks need to be processed
Eric Laurent9cab7462016-11-10 13:05:20 -08004760 for (size_t i = 0; i < count; i++) {
4761 sp<Track> t = mActiveTracks[i].promote();
4762 // The track died recently
4763 if (t == 0) {
4764 continue;
4765 }
4766
Eric Laurent5850c4c2016-11-10 13:04:31 -08004767 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004768 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004769 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004770 continue;
4771 }
4772
Eric Laurent5850c4c2016-11-10 13:04:31 -08004773 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004774#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004775 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004776#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004777 // Only consider last track started for volume and mixer state control.
4778 // In theory an older track could underrun and restart after the new one starts
4779 // but as we only care about the transition phase between two tracks on a
4780 // direct output, it is not a problem to ignore the underrun case.
Eric Laurent9cab7462016-11-10 13:05:20 -08004781 sp<Track> l = mLatestActiveTrack.promote();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004782 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004783
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004784 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004785 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004786 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004787 doHwPause = true;
4788 mHwPaused = true;
4789 }
4790 tracksToRemove->add(track);
4791 } else if (track->isFlushPending()) {
4792 track->flushAck();
4793 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004794 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004795 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004796 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004797 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004798 if (last) {
4799 mLeftVolFloat = mRightVolFloat = -1.0;
4800 if (mHwPaused) {
4801 doHwResume = true;
4802 mHwPaused = false;
4803 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004804 }
4805 }
4806
Eric Laurent81784c32012-11-19 14:55:58 -08004807 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004808 // for all its buffers to be filled before processing it.
4809 // Allow draining the buffer in case the client
4810 // app does not call stop() and relies on underrun to stop:
4811 // hence the test on (track->mRetryCount > 1).
4812 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004813 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004814 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004815 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004816 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004817 minFrames = mNormalFrameCount;
4818 } else {
4819 minFrames = 1;
4820 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004821
Eric Laurentab5cdba2014-06-09 17:22:27 -07004822 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4823 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004824 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004825 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004826
4827 if (track->mFillingUpStatus == Track::FS_FILLED) {
4828 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004829 if (last) {
4830 // make sure processVolume_l() will apply new volume even if 0
4831 mLeftVolFloat = mRightVolFloat = -1.0;
4832 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004833 if (!mHwSupportsPause) {
4834 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004835 }
4836 }
4837
4838 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004839 processVolume_l(track, last);
4840 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004841 sp<Track> previousTrack = mPreviousTrack.promote();
4842 if (previousTrack != 0) {
4843 if (track != previousTrack.get()) {
4844 // Flush any data still being written from last track
4845 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004846 // Invalidate previous track to force a seek when resuming.
4847 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004848 }
4849 }
4850 mPreviousTrack = track;
4851
Eric Laurentd595b7c2013-04-03 17:27:56 -07004852 // reset retry count
4853 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004854 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004855 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004856 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004857 doHwResume = true;
4858 mHwPaused = false;
4859 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004860 }
Eric Laurent81784c32012-11-19 14:55:58 -08004861 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004862 // clear effect chain input buffer if the last active track started underruns
4863 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004864 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004865 mEffectChains[0]->clearInputBuffer();
4866 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004867 if (track->isStopping_1()) {
4868 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004869 if (last && mHwPaused) {
4870 doHwResume = true;
4871 mHwPaused = false;
4872 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004873 }
4874 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4875 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004876 // We have consumed all the buffers of this track.
4877 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004878 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004879 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004880 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4881 } else {
4882 audioHALFrames = 0;
4883 }
4884
Andy Hung818e7a32016-02-16 18:08:07 -08004885 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004886 if (mStandby || !last ||
4887 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004888 if (track->isStopping_2()) {
4889 track->mState = TrackBase::STOPPED;
4890 }
Eric Laurent81784c32012-11-19 14:55:58 -08004891 if (track->isStopped()) {
4892 track->reset();
4893 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004894 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004895 }
4896 } else {
4897 // No buffers for this track. Give it a few chances to
4898 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004899 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004900 if (--(track->mRetryCount) <= 0) {
4901 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004902 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004903 // indicate to client process that the track was disabled because of underrun;
4904 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004905 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004906 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004907 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4908 "minFrames = %u, mFormat = %#x",
4909 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004910 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004911 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004912 doHwPause = true;
4913 mHwPaused = true;
4914 }
Eric Laurent81784c32012-11-19 14:55:58 -08004915 }
4916 }
4917 }
4918 }
4919
Eric Laurentd1f69b02014-12-15 14:33:13 -08004920 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004921 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004922 for (size_t i = 0; i < mTracks.size(); i++) {
4923 if (mTracks[i]->isFlushPending()) {
4924 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004925 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004926 }
4927 }
4928 }
4929
4930 // make sure the pause/flush/resume sequence is executed in the right order.
4931 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4932 // before flush and then resume HW. This can happen in case of pause/flush/resume
4933 // if resume is received before pause is executed.
4934 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004935 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004936 status_t result = mOutput->stream->pause();
4937 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004938 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004939 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004940 flushHw_l();
4941 }
4942 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004943 status_t result = mOutput->stream->resume();
4944 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004945 }
Eric Laurent81784c32012-11-19 14:55:58 -08004946 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004947 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004948
4949 return mixerStatus;
4950}
4951
4952void AudioFlinger::DirectOutputThread::threadLoop_mix()
4953{
Eric Laurent81784c32012-11-19 14:55:58 -08004954 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004955 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004956 // output audio to hardware
4957 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004958 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004959 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004960 status_t status = mActiveTrack->getNextBuffer(&buffer);
4961 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004962 // no need to pad with 0 for compressed audio
4963 if (audio_has_proportional_frames(mFormat)) {
4964 memset(curBuf, 0, frameCount * mFrameSize);
4965 }
Eric Laurent81784c32012-11-19 14:55:58 -08004966 break;
4967 }
4968 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4969 frameCount -= buffer.frameCount;
4970 curBuf += buffer.frameCount * mFrameSize;
4971 mActiveTrack->releaseBuffer(&buffer);
4972 }
Andy Hung2098f272014-02-27 14:00:06 -08004973 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004974 mSleepTimeUs = 0;
4975 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004976 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004977}
4978
4979void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4980{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004981 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004982 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004983 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004984 return;
4985 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004986 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004987 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07004988 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004989 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004990 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004991 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004992 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004993 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004994 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004995 }
4996}
4997
Eric Laurentd1f69b02014-12-15 14:33:13 -08004998void AudioFlinger::DirectOutputThread::threadLoop_exit()
4999{
5000 {
5001 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005002 for (size_t i = 0; i < mTracks.size(); i++) {
5003 if (mTracks[i]->isFlushPending()) {
5004 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005005 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005006 }
5007 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005008 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005009 flushHw_l();
5010 }
5011 }
5012 PlaybackThread::threadLoop_exit();
5013}
5014
5015// must be called with thread mutex locked
5016bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5017{
5018 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005019 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005020
vivek mehta9cd7ad12016-03-17 00:18:29 -07005021 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5022 return !mStandby;
5023 }
5024
Eric Laurentd1f69b02014-12-15 14:33:13 -08005025 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5026 // after a timeout and we will enter standby then.
5027 if (mTracks.size() > 0) {
5028 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005029 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5030 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005031 }
5032
Eric Laurent5cff4032015-05-26 13:49:58 -07005033 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005034}
5035
Eric Laurent81784c32012-11-19 14:55:58 -08005036// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005037int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005038 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005039{
Eric Laurentad7dd962016-09-22 12:38:37 -07005040 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5041 return -1;
5042 }
Eric Laurent81784c32012-11-19 14:55:58 -08005043 return 0;
5044}
5045
5046// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005047void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005048{
5049}
5050
Eric Laurent10351942014-05-08 18:49:52 -07005051// checkForNewParameter_l() must be called with ThreadBase::mLock held
5052bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5053 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005054{
5055 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005056 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005057
Eric Laurent10351942014-05-08 18:49:52 -07005058 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005059
Eric Laurent10351942014-05-08 18:49:52 -07005060 AudioParameter param = AudioParameter(keyValuePair);
5061 int value;
5062 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5063 // forward device change to effects that have requested to be
5064 // aware of attached audio device.
5065 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005066 a2dpDeviceChanged =
5067 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005068 mOutDevice = value;
5069 for (size_t i = 0; i < mEffectChains.size(); i++) {
5070 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005071 }
5072 }
Eric Laurent81784c32012-11-19 14:55:58 -08005073 }
Eric Laurent10351942014-05-08 18:49:52 -07005074 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5075 // do not accept frame count changes if tracks are open as the track buffer
5076 // size depends on frame count and correct behavior would not be garantied
5077 // if frame count is changed after track creation
5078 if (!mTracks.isEmpty()) {
5079 status = INVALID_OPERATION;
5080 } else {
5081 reconfig = true;
5082 }
5083 }
5084 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005085 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005086 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005087 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005088 mStandby = true;
5089 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005090 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005091 }
5092 if (status == NO_ERROR && reconfig) {
5093 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005094 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005095 }
5096 }
5097
Eric Laurent42537be2016-01-08 17:16:42 -08005098 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005099}
5100
5101uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5102{
5103 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005104 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005105 time = PlaybackThread::activeSleepTimeUs();
5106 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005107 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005108 }
5109 return time;
5110}
5111
5112uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5113{
5114 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005115 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005116 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5117 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005118 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005119 }
5120 return time;
5121}
5122
5123uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5124{
5125 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005126 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005127 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5128 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005129 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005130 }
5131 return time;
5132}
5133
5134void AudioFlinger::DirectOutputThread::cacheParameters_l()
5135{
5136 PlaybackThread::cacheParameters_l();
5137
5138 // use shorter standby delay as on normal output to release
5139 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005140 // no delay on outputs with HW A/V sync
5141 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005142 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005143 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005144 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005145 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005146 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005147 }
Eric Laurent81784c32012-11-19 14:55:58 -08005148}
5149
Eric Laurente659ef42014-09-29 13:06:46 -07005150void AudioFlinger::DirectOutputThread::flushHw_l()
5151{
Phil Burk062e67a2015-02-11 13:40:50 -08005152 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005153 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005154 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005155}
5156
Eric Laurent81784c32012-11-19 14:55:58 -08005157// ----------------------------------------------------------------------------
5158
Eric Laurentbfb1b832013-01-07 09:53:42 -08005159AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005160 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005161 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005162 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005163 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005164 mDrainSequence(0),
5165 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005166{
5167}
5168
5169AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5170{
5171}
5172
5173void AudioFlinger::AsyncCallbackThread::onFirstRef()
5174{
5175 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5176}
5177
5178bool AudioFlinger::AsyncCallbackThread::threadLoop()
5179{
5180 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005181 uint32_t writeAckSequence;
5182 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005183 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005184
5185 {
5186 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005187 while (!((mWriteAckSequence & 1) ||
5188 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005189 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005190 exitPending())) {
5191 mWaitWorkCV.wait(mLock);
5192 }
5193
Eric Laurentbfb1b832013-01-07 09:53:42 -08005194 if (exitPending()) {
5195 break;
5196 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005197 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5198 mWriteAckSequence, mDrainSequence);
5199 writeAckSequence = mWriteAckSequence;
5200 mWriteAckSequence &= ~1;
5201 drainSequence = mDrainSequence;
5202 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005203 asyncError = mAsyncError;
5204 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005205 }
5206 {
Eric Laurent4de95592013-09-26 15:28:21 -07005207 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5208 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005209 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005210 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005211 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005212 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005213 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005214 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005215 if (asyncError) {
5216 playbackThread->onAsyncError();
5217 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005218 }
5219 }
5220 }
5221 return false;
5222}
5223
5224void AudioFlinger::AsyncCallbackThread::exit()
5225{
5226 ALOGV("AsyncCallbackThread::exit");
5227 Mutex::Autolock _l(mLock);
5228 requestExit();
5229 mWaitWorkCV.broadcast();
5230}
5231
Eric Laurent3b4529e2013-09-05 18:09:19 -07005232void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005233{
5234 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005235 // bit 0 is cleared
5236 mWriteAckSequence = sequence << 1;
5237}
5238
5239void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5240{
5241 Mutex::Autolock _l(mLock);
5242 // ignore unexpected callbacks
5243 if (mWriteAckSequence & 2) {
5244 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005245 mWaitWorkCV.signal();
5246 }
5247}
5248
Eric Laurent3b4529e2013-09-05 18:09:19 -07005249void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005250{
5251 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005252 // bit 0 is cleared
5253 mDrainSequence = sequence << 1;
5254}
5255
5256void AudioFlinger::AsyncCallbackThread::resetDraining()
5257{
5258 Mutex::Autolock _l(mLock);
5259 // ignore unexpected callbacks
5260 if (mDrainSequence & 2) {
5261 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005262 mWaitWorkCV.signal();
5263 }
5264}
5265
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005266void AudioFlinger::AsyncCallbackThread::setAsyncError()
5267{
5268 Mutex::Autolock _l(mLock);
5269 mAsyncError = true;
5270 mWaitWorkCV.signal();
5271}
5272
Eric Laurentbfb1b832013-01-07 09:53:42 -08005273
5274// ----------------------------------------------------------------------------
5275AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005276 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5277 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005278 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5279 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005280{
Eric Laurentfd477972013-10-25 18:10:40 -07005281 //FIXME: mStandby should be set to true by ThreadBase constructor
5282 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005283 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005284}
5285
Eric Laurentbfb1b832013-01-07 09:53:42 -08005286void AudioFlinger::OffloadThread::threadLoop_exit()
5287{
5288 if (mFlushPending || mHwPaused) {
5289 // If a flush is pending or track was paused, just discard buffered data
5290 flushHw_l();
5291 } else {
5292 mMixerStatus = MIXER_DRAIN_ALL;
5293 threadLoop_drain();
5294 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005295 if (mUseAsyncWrite) {
5296 ALOG_ASSERT(mCallbackThread != 0);
5297 mCallbackThread->exit();
5298 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005299 PlaybackThread::threadLoop_exit();
5300}
5301
5302AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5303 Vector< sp<Track> > *tracksToRemove
5304)
5305{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005306 size_t count = mActiveTracks.size();
5307
5308 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005309 bool doHwPause = false;
5310 bool doHwResume = false;
5311
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005312 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005313
Eric Laurentbfb1b832013-01-07 09:53:42 -08005314 // find out which tracks need to be processed
Eric Laurent9cab7462016-11-10 13:05:20 -08005315 for (size_t i = 0; i < count; i++) {
5316 sp<Track> t = mActiveTracks[i].promote();
5317 // The track died recently
5318 if (t == 0) {
5319 continue;
5320 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005321 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005322#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005323 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005324#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005325 // Only consider last track started for volume and mixer state control.
5326 // In theory an older track could underrun and restart after the new one starts
5327 // but as we only care about the transition phase between two tracks on a
5328 // direct output, it is not a problem to ignore the underrun case.
Eric Laurent9cab7462016-11-10 13:05:20 -08005329 sp<Track> l = mLatestActiveTrack.promote();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005330 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005331
Haynes Mathew George7844f672014-01-15 12:32:55 -08005332 if (track->isInvalid()) {
5333 ALOGW("An invalidated track shouldn't be in active list");
5334 tracksToRemove->add(track);
5335 continue;
5336 }
5337
5338 if (track->mState == TrackBase::IDLE) {
5339 ALOGW("An idle track shouldn't be in active list");
5340 continue;
5341 }
5342
Eric Laurentbfb1b832013-01-07 09:53:42 -08005343 if (track->isPausing()) {
5344 track->setPaused();
5345 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005346 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005347 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005348 mHwPaused = true;
5349 }
5350 // If we were part way through writing the mixbuffer to
5351 // the HAL we must save this until we resume
5352 // BUG - this will be wrong if a different track is made active,
5353 // in that case we want to discard the pending data in the
5354 // mixbuffer and tell the client to present it again when the
5355 // track is resumed
5356 mPausedWriteLength = mCurrentWriteLength;
5357 mPausedBytesRemaining = mBytesRemaining;
5358 mBytesRemaining = 0; // stop writing
5359 }
5360 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005361 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005362 if (track->isStopping_1()) {
5363 track->mRetryCount = kMaxTrackStopRetriesOffload;
5364 } else {
5365 track->mRetryCount = kMaxTrackRetriesOffload;
5366 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005367 track->flushAck();
5368 if (last) {
5369 mFlushPending = true;
5370 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005371 } else if (track->isResumePending()){
5372 track->resumeAck();
5373 if (last) {
5374 if (mPausedBytesRemaining) {
5375 // Need to continue write that was interrupted
5376 mCurrentWriteLength = mPausedWriteLength;
5377 mBytesRemaining = mPausedBytesRemaining;
5378 mPausedBytesRemaining = 0;
5379 }
5380 if (mHwPaused) {
5381 doHwResume = true;
5382 mHwPaused = false;
5383 // threadLoop_mix() will handle the case that we need to
5384 // resume an interrupted write
5385 }
5386 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005387 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005388
Eric Laurent3df841a2016-07-15 15:15:40 -07005389 mLeftVolFloat = mRightVolFloat = -1.0;
5390
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005391 // Do not handle new data in this iteration even if track->framesReady()
5392 mixerStatus = MIXER_TRACKS_ENABLED;
5393 }
5394 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005395 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005396 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397 if (track->mFillingUpStatus == Track::FS_FILLED) {
5398 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005399 if (last) {
5400 // make sure processVolume_l() will apply new volume even if 0
5401 mLeftVolFloat = mRightVolFloat = -1.0;
5402 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005403 }
5404
5405 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005406 sp<Track> previousTrack = mPreviousTrack.promote();
5407 if (previousTrack != 0) {
5408 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005409 // Flush any data still being written from last track
5410 mBytesRemaining = 0;
5411 if (mPausedBytesRemaining) {
5412 // Last track was paused so we also need to flush saved
5413 // mixbuffer state and invalidate track so that it will
5414 // re-submit that unwritten data when it is next resumed
5415 mPausedBytesRemaining = 0;
5416 // Invalidate is a bit drastic - would be more efficient
5417 // to have a flag to tell client that some of the
5418 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005419 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005420 }
5421 // flush data already sent to the DSP if changing audio session as audio
5422 // comes from a different source. Also invalidate previous track to force a
5423 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005424 if (previousTrack->sessionId() != track->sessionId()) {
5425 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005426 }
5427 }
5428 }
5429 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005430 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005431 if (track->isStopping_1()) {
5432 track->mRetryCount = kMaxTrackStopRetriesOffload;
5433 } else {
5434 track->mRetryCount = kMaxTrackRetriesOffload;
5435 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005436 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005437 mixerStatus = MIXER_TRACKS_READY;
5438 }
5439 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005440 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005441 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005442 if (--(track->mRetryCount) <= 0) {
5443 // Hardware buffer can hold a large amount of audio so we must
5444 // wait for all current track's data to drain before we say
5445 // that the track is stopped.
5446 if (mBytesRemaining == 0) {
5447 // Only start draining when all data in mixbuffer
5448 // has been written
5449 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5450 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5451 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5452 if (last && !mStandby) {
5453 // do not modify drain sequence if we are already draining. This happens
5454 // when resuming from pause after drain.
5455 if ((mDrainSequence & 1) == 0) {
5456 mSleepTimeUs = 0;
5457 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5458 mixerStatus = MIXER_DRAIN_TRACK;
5459 mDrainSequence += 2;
5460 }
5461 if (mHwPaused) {
5462 // It is possible to move from PAUSED to STOPPING_1 without
5463 // a resume so we must ensure hardware is running
5464 doHwResume = true;
5465 mHwPaused = false;
5466 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005467 }
5468 }
Eric Laurente93cc032016-05-05 10:15:10 -07005469 } else if (last) {
5470 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5471 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005472 }
5473 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005474 // Drain has completed or we are in standby, signal presentation complete
5475 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005476 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005477 uint32_t latency = 0;
5478 status_t result = mOutput->stream->getLatency(&latency);
5479 ALOGE_IF(result != OK,
5480 "Error when retrieving output stream latency: %d", result);
5481 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005482 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005483 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005484 track->presentationComplete(framesWritten, audioHALFrames);
5485 track->reset();
5486 tracksToRemove->add(track);
5487 }
5488 } else {
5489 // No buffers for this track. Give it a few chances to
5490 // fill a buffer, then remove it from active list.
5491 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005492 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005493 uint64_t position = 0;
5494 struct timespec unused;
5495 // The running check restarts the retry counter at least once.
5496 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5497 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5498 running = true;
5499 mOffloadUnderrunPosition = position;
5500 }
5501 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005502 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5503 (long long)position, (long long)mOffloadUnderrunPosition);
5504 }
5505 if (running) { // still running, give us more time.
5506 track->mRetryCount = kMaxTrackRetriesOffload;
5507 } else {
5508 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5509 track->name());
5510 tracksToRemove->add(track);
5511 // indicate to client process that the track was disabled because of underrun;
5512 // it will then automatically call start() when data is available
5513 track->disable();
5514 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005515 } else if (last){
5516 mixerStatus = MIXER_TRACKS_ENABLED;
5517 }
5518 }
5519 }
5520 // compute volume for this track
5521 processVolume_l(track, last);
5522 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005523
Eric Laurentea0fade2013-10-04 16:23:48 -07005524 // make sure the pause/flush/resume sequence is executed in the right order.
5525 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5526 // before flush and then resume HW. This can happen in case of pause/flush/resume
5527 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005528 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005529 status_t result = mOutput->stream->pause();
5530 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005531 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005532 if (mFlushPending) {
5533 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005534 }
Eric Laurentfd477972013-10-25 18:10:40 -07005535 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005536 status_t result = mOutput->stream->resume();
5537 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005538 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005539
Eric Laurentbfb1b832013-01-07 09:53:42 -08005540 // remove all the tracks that need to be...
5541 removeTracks_l(*tracksToRemove);
5542
5543 return mixerStatus;
5544}
5545
Eric Laurentbfb1b832013-01-07 09:53:42 -08005546// must be called with thread mutex locked
5547bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5548{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005549 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5550 mWriteAckSequence, mDrainSequence);
5551 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005552 return true;
5553 }
5554 return false;
5555}
5556
Eric Laurentbfb1b832013-01-07 09:53:42 -08005557bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5558{
5559 Mutex::Autolock _l(mLock);
5560 return waitingAsyncCallback_l();
5561}
5562
5563void AudioFlinger::OffloadThread::flushHw_l()
5564{
Eric Laurente659ef42014-09-29 13:06:46 -07005565 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005566 // Flush anything still waiting in the mixbuffer
5567 mCurrentWriteLength = 0;
5568 mBytesRemaining = 0;
5569 mPausedWriteLength = 0;
5570 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005571 // reset bytes written count to reflect that DSP buffers are empty after flush.
5572 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005573 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005574
Eric Laurentbfb1b832013-01-07 09:53:42 -08005575 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005576 // discard any pending drain or write ack by incrementing sequence
5577 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5578 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005579 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005580 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5581 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005582 }
5583}
5584
Haynes Mathew George05317d22016-05-03 16:34:26 -07005585void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5586{
5587 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005588 if (PlaybackThread::invalidateTracks_l(streamType)) {
5589 mFlushPending = true;
5590 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005591}
5592
Eric Laurentbfb1b832013-01-07 09:53:42 -08005593// ----------------------------------------------------------------------------
5594
Eric Laurent81784c32012-11-19 14:55:58 -08005595AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005596 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005597 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005598 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005599 mWaitTimeMs(UINT_MAX)
5600{
5601 addOutputTrack(mainThread);
5602}
5603
5604AudioFlinger::DuplicatingThread::~DuplicatingThread()
5605{
5606 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5607 mOutputTracks[i]->destroy();
5608 }
5609}
5610
5611void AudioFlinger::DuplicatingThread::threadLoop_mix()
5612{
5613 // mix buffers...
5614 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005615 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005616 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005617 if (mMixerBufferValid) {
5618 memset(mMixerBuffer, 0, mMixerBufferSize);
5619 } else {
5620 memset(mSinkBuffer, 0, mSinkBufferSize);
5621 }
Eric Laurent81784c32012-11-19 14:55:58 -08005622 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005623 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005624 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005625 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005626 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005627}
5628
5629void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5630{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005631 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005632 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005633 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005634 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005635 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005636 }
5637 } else if (mBytesWritten != 0) {
5638 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5639 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005640 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005641 } else {
5642 // flush remaining overflow buffers in output tracks
5643 writeFrames = 0;
5644 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005645 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005646 }
5647}
5648
Eric Laurentbfb1b832013-01-07 09:53:42 -08005649ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005650{
5651 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005652 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005653 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005654 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005655 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005656}
5657
5658void AudioFlinger::DuplicatingThread::threadLoop_standby()
5659{
5660 // DuplicatingThread implements standby by stopping all tracks
5661 for (size_t i = 0; i < outputTracks.size(); i++) {
5662 outputTracks[i]->stop();
5663 }
5664}
5665
5666void AudioFlinger::DuplicatingThread::saveOutputTracks()
5667{
5668 outputTracks = mOutputTracks;
5669}
5670
5671void AudioFlinger::DuplicatingThread::clearOutputTracks()
5672{
5673 outputTracks.clear();
5674}
5675
5676void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5677{
5678 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005679 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5680 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5681 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5682 const size_t frameCount =
5683 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5684 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5685 // from different OutputTracks and their associated MixerThreads (e.g. one may
5686 // nearly empty and the other may be dropping data).
5687
5688 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005689 this,
5690 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005691 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005692 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005693 frameCount,
5694 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005695 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5696 if (status != NO_ERROR) {
5697 ALOGE("addOutputTrack() initCheck failed %d", status);
5698 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005699 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005700 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5701 mOutputTracks.add(outputTrack);
5702 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5703 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005704}
5705
5706void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5707{
5708 Mutex::Autolock _l(mLock);
5709 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5710 if (mOutputTracks[i]->thread() == thread) {
5711 mOutputTracks[i]->destroy();
5712 mOutputTracks.removeAt(i);
5713 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005714 if (thread->getOutput() == mOutput) {
5715 mOutput = NULL;
5716 }
Eric Laurent81784c32012-11-19 14:55:58 -08005717 return;
5718 }
5719 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005720 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005721}
5722
5723// caller must hold mLock
5724void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5725{
5726 mWaitTimeMs = UINT_MAX;
5727 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5728 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5729 if (strong != 0) {
5730 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5731 if (waitTimeMs < mWaitTimeMs) {
5732 mWaitTimeMs = waitTimeMs;
5733 }
5734 }
5735 }
5736}
5737
5738
5739bool AudioFlinger::DuplicatingThread::outputsReady(
5740 const SortedVector< sp<OutputTrack> > &outputTracks)
5741{
5742 for (size_t i = 0; i < outputTracks.size(); i++) {
5743 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5744 if (thread == 0) {
5745 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5746 outputTracks[i].get());
5747 return false;
5748 }
5749 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5750 // see note at standby() declaration
5751 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5752 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5753 thread.get());
5754 return false;
5755 }
5756 }
5757 return true;
5758}
5759
5760uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5761{
5762 return (mWaitTimeMs * 1000) / 2;
5763}
5764
5765void AudioFlinger::DuplicatingThread::cacheParameters_l()
5766{
5767 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5768 updateWaitTime_l();
5769
5770 MixerThread::cacheParameters_l();
5771}
5772
5773// ----------------------------------------------------------------------------
5774// Record
5775// ----------------------------------------------------------------------------
5776
5777AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5778 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005779 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005780 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005781 audio_devices_t inDevice,
5782 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005783#ifdef TEE_SINK
5784 , const sp<NBAIO_Sink>& teeSink
5785#endif
5786 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005787 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Eric Laurent9cab7462016-11-10 13:05:20 -08005788 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005789 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005790 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005791#ifdef TEE_SINK
5792 , mTeeSink(teeSink)
5793#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005794 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5795 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005796 // mFastCapture below
5797 , mFastCaptureFutex(0)
5798 // mInputSource
5799 // mPipeSink
5800 // mPipeSource
5801 , mPipeFramesP2(0)
5802 // mPipeMemory
5803 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005804 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005805{
Glenn Kastend7dca052015-03-05 16:05:54 -08005806 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5807 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005808
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005809 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005810
5811 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005812 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005813 size_t numCounterOffers = 0;
5814 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005815#if !LOG_NDEBUG
5816 ssize_t index =
5817#else
5818 (void)
5819#endif
5820 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005821 ALOG_ASSERT(index == 0);
5822
5823 // initialize fast capture depending on configuration
5824 bool initFastCapture;
5825 switch (kUseFastCapture) {
5826 case FastCapture_Never:
5827 initFastCapture = false;
5828 break;
5829 case FastCapture_Always:
5830 initFastCapture = true;
5831 break;
5832 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005833 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005834 break;
5835 // case FastCapture_Dynamic:
5836 }
5837
5838 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005839 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005840 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005841 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5842 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005843 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5844 void *pipeBuffer;
5845 const sp<MemoryDealer> roHeap(readOnlyHeap());
5846 sp<IMemory> pipeMemory;
5847 if ((roHeap == 0) ||
5848 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5849 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5850 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5851 goto failed;
5852 }
5853 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5854 memset(pipeBuffer, 0, pipeSize);
5855 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5856 const NBAIO_Format offers[1] = {format};
5857 size_t numCounterOffers = 0;
5858 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5859 ALOG_ASSERT(index == 0);
5860 mPipeSink = pipe;
5861 PipeReader *pipeReader = new PipeReader(*pipe);
5862 numCounterOffers = 0;
5863 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5864 ALOG_ASSERT(index == 0);
5865 mPipeSource = pipeReader;
5866 mPipeFramesP2 = pipeFramesP2;
5867 mPipeMemory = pipeMemory;
5868
5869 // create fast capture
5870 mFastCapture = new FastCapture();
5871 FastCaptureStateQueue *sq = mFastCapture->sq();
5872#ifdef STATE_QUEUE_DUMP
5873 // FIXME
5874#endif
5875 FastCaptureState *state = sq->begin();
5876 state->mCblk = NULL;
5877 state->mInputSource = mInputSource.get();
5878 state->mInputSourceGen++;
5879 state->mPipeSink = pipe;
5880 state->mPipeSinkGen++;
5881 state->mFrameCount = mFrameCount;
5882 state->mCommand = FastCaptureState::COLD_IDLE;
5883 // already done in constructor initialization list
5884 //mFastCaptureFutex = 0;
5885 state->mColdFutexAddr = &mFastCaptureFutex;
5886 state->mColdGen++;
5887 state->mDumpState = &mFastCaptureDumpState;
5888#ifdef TEE_SINK
5889 // FIXME
5890#endif
5891 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5892 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5893 sq->end();
5894 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5895
5896 // start the fast capture
5897 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5898 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005899 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005900#ifdef AUDIO_WATCHDOG
5901 // FIXME
5902#endif
5903
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005904 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005905 }
5906failed: ;
5907
5908 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005909}
5910
Eric Laurent81784c32012-11-19 14:55:58 -08005911AudioFlinger::RecordThread::~RecordThread()
5912{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005913 if (mFastCapture != 0) {
5914 FastCaptureStateQueue *sq = mFastCapture->sq();
5915 FastCaptureState *state = sq->begin();
5916 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5917 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5918 if (old == -1) {
5919 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5920 }
5921 }
5922 state->mCommand = FastCaptureState::EXIT;
5923 sq->end();
5924 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5925 mFastCapture->join();
5926 mFastCapture.clear();
5927 }
5928 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005929 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005930 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005931}
5932
5933void AudioFlinger::RecordThread::onFirstRef()
5934{
Glenn Kastend7dca052015-03-05 16:05:54 -08005935 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005936}
5937
Eric Laurent81784c32012-11-19 14:55:58 -08005938bool AudioFlinger::RecordThread::threadLoop()
5939{
Eric Laurent81784c32012-11-19 14:55:58 -08005940 nsecs_t lastWarning = 0;
5941
5942 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005943
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005944reacquire_wakelock:
5945 sp<RecordTrack> activeTrack;
Eric Laurent9cab7462016-11-10 13:05:20 -08005946 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005947 {
5948 Mutex::Autolock _l(mLock);
Eric Laurent9cab7462016-11-10 13:05:20 -08005949 size_t size = mActiveTracks.size();
5950 activeTracksGen = mActiveTracksGen;
5951 if (size > 0) {
5952 // FIXME an arbitrary choice
5953 activeTrack = mActiveTracks[0];
5954 acquireWakeLock_l(activeTrack->uid());
5955 if (size > 1) {
5956 SortedVector<int> tmp;
5957 for (size_t i = 0; i < size; i++) {
5958 tmp.add(mActiveTracks[i]->uid());
5959 }
5960 updateWakeLockUids_l(tmp);
5961 }
5962 } else {
5963 acquireWakeLock_l(-1);
5964 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005965 }
5966
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005967 // used to request a deferred sleep, to be executed later while mutex is unlocked
5968 uint32_t sleepUs = 0;
5969
5970 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005971 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005972 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005973
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005974 // activeTracks accumulates a copy of a subset of mActiveTracks
5975 Vector< sp<RecordTrack> > activeTracks;
5976
Glenn Kasten735f45f2014-08-18 15:51:59 -07005977 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005978 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005979
Glenn Kasten735f45f2014-08-18 15:51:59 -07005980 // reference to a fast track which is about to be removed
5981 sp<RecordTrack> fastTrackToRemove;
5982
Eric Laurent81784c32012-11-19 14:55:58 -08005983 { // scope for mLock
5984 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005985
Eric Laurent021cf962014-05-13 10:18:14 -07005986 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005987
Eric Laurent000a4192014-01-29 15:17:32 -08005988 // check exitPending here because checkForNewParameters_l() and
5989 // checkForNewParameters_l() can temporarily release mLock
5990 if (exitPending()) {
5991 break;
5992 }
5993
Eric Laurent5c25d562016-07-13 17:17:45 -07005994 // sleep with mutex unlocked
5995 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07005996 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07005997 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
5998 ATRACE_END();
5999 sleepUs = 0;
6000 continue;
6001 }
6002
Glenn Kasten2b806402013-11-20 16:37:38 -08006003 // if no active track(s), then standby and release wakelock
6004 size_t size = mActiveTracks.size();
6005 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006006 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006007 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006008 releaseWakeLock_l();
6009 ALOGV("RecordThread: loop stopping");
6010 // go to sleep
6011 mWaitWorkCV.wait(mLock);
6012 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006013 goto reacquire_wakelock;
6014 }
6015
Eric Laurent9cab7462016-11-10 13:05:20 -08006016 if (mActiveTracksGen != activeTracksGen) {
6017 activeTracksGen = mActiveTracksGen;
6018 SortedVector<int> tmp;
6019 for (size_t i = 0; i < size; i++) {
6020 tmp.add(mActiveTracks[i]->uid());
6021 }
6022 updateWakeLockUids_l(tmp);
6023 }
6024
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006025 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006026 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006027 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006028
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006029 activeTrack = mActiveTracks[i];
6030 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006031 if (activeTrack->isFastTrack()) {
6032 ALOG_ASSERT(fastTrackToRemove == 0);
6033 fastTrackToRemove = activeTrack;
6034 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006035 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006036 mActiveTracks.remove(activeTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006037 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006038 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006039 continue;
6040 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006041
6042 TrackBase::track_state activeTrackState = activeTrack->mState;
6043 switch (activeTrackState) {
6044
6045 case TrackBase::PAUSING:
6046 mActiveTracks.remove(activeTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006047 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006048 doBroadcast = true;
6049 size--;
6050 continue;
6051
6052 case TrackBase::STARTING_1:
6053 sleepUs = 10000;
6054 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006055 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006056 continue;
6057
6058 case TrackBase::STARTING_2:
6059 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006060 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006061 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006062 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006063 break;
6064
6065 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006066 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006067 break;
6068
6069 case TrackBase::IDLE:
6070 i++;
6071 continue;
6072
6073 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006074 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006075 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006076
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006077 activeTracks.add(activeTrack);
6078 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006079
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006080 if (activeTrack->isFastTrack()) {
6081 ALOG_ASSERT(!mFastTrackAvail);
6082 ALOG_ASSERT(fastTrack == 0);
6083 fastTrack = activeTrack;
6084 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006085 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006086
6087 if (allStopped) {
6088 standbyIfNotAlreadyInStandby();
6089 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006090 if (doBroadcast) {
6091 mStartStopCond.broadcast();
6092 }
6093
6094 // sleep if there are no active tracks to process
6095 if (activeTracks.size() == 0) {
6096 if (sleepUs == 0) {
6097 sleepUs = kRecordThreadSleepUs;
6098 }
6099 continue;
6100 }
6101 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006102
Eric Laurent81784c32012-11-19 14:55:58 -08006103 lockEffectChains_l(effectChains);
6104 }
6105
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006106 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006107
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006108 size_t size = effectChains.size();
6109 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006110 // thread mutex is not locked, but effect chain is locked
6111 effectChains[i]->process_l();
6112 }
6113
Glenn Kasten735f45f2014-08-18 15:51:59 -07006114 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006115 if (mFastCapture != 0) {
6116 FastCaptureStateQueue *sq = mFastCapture->sq();
6117 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006118 bool didModify = false;
6119 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006120 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6121 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6122 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6123 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6124 if (old == -1) {
6125 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6126 }
6127 }
6128 state->mCommand = FastCaptureState::READ_WRITE;
6129#if 0 // FIXME
6130 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006131 FastThreadDumpState::kSamplingNforLowRamDevice :
6132 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006133#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006134 didModify = true;
6135 }
6136 audio_track_cblk_t *cblkOld = state->mCblk;
6137 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6138 if (cblkNew != cblkOld) {
6139 state->mCblk = cblkNew;
6140 // block until acked if removing a fast track
6141 if (cblkOld != NULL) {
6142 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6143 }
6144 didModify = true;
6145 }
6146 sq->end(didModify);
6147 if (didModify) {
6148 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006149#if 0
6150 if (kUseFastCapture == FastCapture_Dynamic) {
6151 mNormalSource = mPipeSource;
6152 }
6153#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006154 }
6155 }
6156
Glenn Kasten735f45f2014-08-18 15:51:59 -07006157 // now run the fast track destructor with thread mutex unlocked
6158 fastTrackToRemove.clear();
6159
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006160 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6161 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6162 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6163 // If destination is non-contiguous, first read past the nominal end of buffer, then
6164 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006165
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006166 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006167 ssize_t framesRead;
6168
6169 // If an NBAIO source is present, use it to read the normal capture's data
6170 if (mPipeSource != 0) {
6171 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006172 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006173 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006174 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006175 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6176 // buffer size or at least for 20ms.
6177 size_t sleepFrames = max(
6178 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6179 if (framesRead <= (ssize_t) sleepFrames) {
6180 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6181 }
6182 if (framesRead < 0) {
6183 status_t status = (status_t) framesRead;
6184 switch (status) {
6185 case OVERRUN:
6186 ALOGW("overrun on read from pipe");
6187 framesRead = 0;
6188 break;
6189 case NEGOTIATE:
6190 ALOGE("re-negotiation is needed");
6191 framesRead = -1; // Will cause an attempt to recover.
6192 break;
6193 default:
6194 ALOGE("unknown error %d on read from pipe", status);
6195 break;
6196 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006197 }
6198 // otherwise use the HAL / AudioStreamIn directly
6199 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006200 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006201 size_t bytesRead;
6202 status_t result = mInput->stream->read(
6203 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006204 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006205 if (result < 0) {
6206 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006207 } else {
6208 framesRead = bytesRead / mFrameSize;
6209 }
6210 }
6211
Andy Hung3f0c9022016-01-15 17:49:46 -08006212 // Update server timestamp with server stats
6213 // systemTime() is optional if the hardware supports timestamps.
6214 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6215 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6216
6217 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006218 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006219 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006220 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006221 if (ret == NO_ERROR) {
6222 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6223 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6224 // Note: In general record buffers should tend to be empty in
6225 // a properly running pipeline.
6226 //
6227 // Also, it is not advantageous to call get_presentation_position during the read
6228 // as the read obtains a lock, preventing the timestamp call from executing.
6229 }
6230 }
6231 // Use this to track timestamp information
6232 // ALOGD("%s", mTimestamp.toString().c_str());
6233
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006234 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006235 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006236 // Force input into standby so that it tries to recover at next read attempt
6237 inputStandBy();
6238 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006239 }
6240 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006241 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006242 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006243 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006244
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006245 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006246 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006247 }
6248 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006249 {
6250 size_t part1 = mRsmpInFramesP2 - rear;
6251 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006252 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006253 (framesRead - part1) * mFrameSize);
6254 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006255 }
6256 rear = mRsmpInRear += framesRead;
6257
6258 size = activeTracks.size();
6259 // loop over each active track
6260 for (size_t i = 0; i < size; i++) {
6261 activeTrack = activeTracks[i];
6262
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006263 // skip fast tracks, as those are handled directly by FastCapture
6264 if (activeTrack->isFastTrack()) {
6265 continue;
6266 }
6267
Andy Hung73c02e42015-03-29 01:13:58 -07006268 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006269 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6270
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006271 enum {
6272 OVERRUN_UNKNOWN,
6273 OVERRUN_TRUE,
6274 OVERRUN_FALSE
6275 } overrun = OVERRUN_UNKNOWN;
6276
6277 // loop over getNextBuffer to handle circular sink
6278 for (;;) {
6279
6280 activeTrack->mSink.frameCount = ~0;
6281 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6282 size_t framesOut = activeTrack->mSink.frameCount;
6283 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6284
Andy Hung73c02e42015-03-29 01:13:58 -07006285 // check available frames and handle overrun conditions
6286 // if the record track isn't draining fast enough.
6287 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006288 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006289 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6290 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006291 overrun = OVERRUN_TRUE;
6292 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006293 if (framesOut == 0 || framesIn == 0) {
6294 break;
6295 }
6296
Andy Hung6770c6f2015-04-07 13:43:36 -07006297 // Don't allow framesOut to be larger than what is possible with resampling
6298 // from framesIn.
6299 // This isn't strictly necessary but helps limit buffer resizing in
6300 // RecordBufferConverter. TODO: remove when no longer needed.
6301 framesOut = min(framesOut,
6302 destinationFramesPossible(
6303 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006304 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6305 framesOut = activeTrack->mRecordBufferConverter->convert(
6306 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006307
6308 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6309 overrun = OVERRUN_FALSE;
6310 }
6311
6312 if (activeTrack->mFramesToDrop == 0) {
6313 if (framesOut > 0) {
6314 activeTrack->mSink.frameCount = framesOut;
6315 activeTrack->releaseBuffer(&activeTrack->mSink);
6316 }
6317 } else {
6318 // FIXME could do a partial drop of framesOut
6319 if (activeTrack->mFramesToDrop > 0) {
6320 activeTrack->mFramesToDrop -= framesOut;
6321 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006322 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006323 }
6324 } else {
6325 activeTrack->mFramesToDrop += framesOut;
6326 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6327 activeTrack->mSyncStartEvent->isCancelled()) {
6328 ALOGW("Synced record %s, session %d, trigger session %d",
6329 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6330 activeTrack->sessionId(),
6331 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006332 activeTrack->mSyncStartEvent->triggerSession() :
6333 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006334 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006335 }
6336 }
6337 }
6338
6339 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006340 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006341 }
6342 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006343
6344 switch (overrun) {
6345 case OVERRUN_TRUE:
6346 // client isn't retrieving buffers fast enough
6347 if (!activeTrack->setOverflow()) {
6348 nsecs_t now = systemTime();
6349 // FIXME should lastWarning per track?
6350 if ((now - lastWarning) > kWarningThrottleNs) {
6351 ALOGW("RecordThread: buffer overflow");
6352 lastWarning = now;
6353 }
6354 }
6355 break;
6356 case OVERRUN_FALSE:
6357 activeTrack->clearOverflow();
6358 break;
6359 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006360 break;
6361 }
6362
Andy Hung3f0c9022016-01-15 17:49:46 -08006363 // update frame information and push timestamp out
6364 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006365 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006366 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6367 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006368 }
6369
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006370unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006371 // enable changes in effect chain
6372 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006373 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006374 }
6375
Glenn Kasten93e471f2013-08-19 08:40:07 -07006376 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006377
6378 {
6379 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006380 for (size_t i = 0; i < mTracks.size(); i++) {
6381 sp<RecordTrack> track = mTracks[i];
6382 track->invalidate();
6383 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006384 mActiveTracks.clear();
Eric Laurent9cab7462016-11-10 13:05:20 -08006385 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006386 mStartStopCond.broadcast();
6387 }
6388
6389 releaseWakeLock();
6390
6391 ALOGV("RecordThread %p exiting", this);
6392 return false;
6393}
6394
Glenn Kasten93e471f2013-08-19 08:40:07 -07006395void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006396{
6397 if (!mStandby) {
6398 inputStandBy();
6399 mStandby = true;
6400 }
6401}
6402
6403void AudioFlinger::RecordThread::inputStandBy()
6404{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006405 // Idle the fast capture if it's currently running
6406 if (mFastCapture != 0) {
6407 FastCaptureStateQueue *sq = mFastCapture->sq();
6408 FastCaptureState *state = sq->begin();
6409 if (!(state->mCommand & FastCaptureState::IDLE)) {
6410 state->mCommand = FastCaptureState::COLD_IDLE;
6411 state->mColdFutexAddr = &mFastCaptureFutex;
6412 state->mColdGen++;
6413 mFastCaptureFutex = 0;
6414 sq->end();
6415 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6416 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6417#if 0
6418 if (kUseFastCapture == FastCapture_Dynamic) {
6419 // FIXME
6420 }
6421#endif
6422#ifdef AUDIO_WATCHDOG
6423 // FIXME
6424#endif
6425 } else {
6426 sq->end(false /*didModify*/);
6427 }
6428 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006429 status_t result = mInput->stream->standby();
6430 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006431
6432 // If going into standby, flush the pipe source.
6433 if (mPipeSource.get() != nullptr) {
6434 const ssize_t flushed = mPipeSource->flush();
6435 if (flushed > 0) {
6436 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6437 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6438 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6439 }
6440 }
Eric Laurent81784c32012-11-19 14:55:58 -08006441}
6442
Glenn Kasten05997e22014-03-13 15:08:33 -07006443// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006444sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006445 const sp<AudioFlinger::Client>& client,
6446 uint32_t sampleRate,
6447 audio_format_t format,
6448 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006449 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006450 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006451 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006452 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006453 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006454 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006455 status_t *status,
6456 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006457{
Glenn Kasten74935e42013-12-19 08:56:45 -08006458 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006459 sp<RecordTrack> track;
6460 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006461 audio_input_flags_t inputFlags = mInput->flags;
6462
6463 // special case for FAST flag considered OK if fast capture is present
6464 if (hasFastCapture()) {
6465 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6466 }
6467
6468 // Check if requested flags are compatible with output stream flags
6469 if ((*flags & inputFlags) != *flags) {
6470 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6471 " input flags (%08x)",
6472 *flags, inputFlags);
6473 *flags = (audio_input_flags_t)(*flags & inputFlags);
6474 }
Eric Laurent81784c32012-11-19 14:55:58 -08006475
Glenn Kasten90e58b12013-07-31 16:16:02 -07006476 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006477 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006478 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006479 // we formerly checked for a callback handler (non-0 tid),
6480 // but that is no longer required for TRANSFER_OBTAIN mode
6481 //
Glenn Kasten74105912014-07-03 12:28:53 -07006482 // frame count is not specified, or is exactly the pipe depth
6483 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006484 // PCM data
6485 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006486 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006487 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006488 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006489 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006490 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006491 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006492 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006493 hasFastCapture() &&
6494 // there are sufficient fast track slots available
6495 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006496 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006497 // check compatibility with audio effects.
6498 Mutex::Autolock _l(mLock);
6499 // Do not accept FAST flag if the session has software effects
6500 sp<EffectChain> chain = getEffectChain_l(sessionId);
6501 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006502 audio_input_flags_t old = *flags;
6503 chain->checkInputFlagCompatibility(flags);
6504 if (old != *flags) {
6505 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6506 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006507 }
6508 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006509 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006510 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6511 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006512 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006513 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006514 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006515 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006516 frameCount, mFrameCount, mPipeFramesP2,
6517 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6518 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006519 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006520 }
6521 }
6522
6523 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006524 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006525 // fast track: frame count is exactly the pipe depth
6526 frameCount = mPipeFramesP2;
6527 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6528 *notificationFrames = mFrameCount;
6529 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006530 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6531 // or 20 ms if there is a fast capture
6532 // TODO This could be a roundupRatio inline, and const
6533 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6534 * sampleRate + mSampleRate - 1) / mSampleRate;
6535 // minimum number of notification periods is at least kMinNotifications,
6536 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6537 static const size_t kMinNotifications = 3;
6538 static const uint32_t kMinMs = 30;
6539 // TODO This could be a roundupRatio inline
6540 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6541 // TODO This could be a roundupRatio inline
6542 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6543 maxNotificationFrames;
6544 const size_t minFrameCount = maxNotificationFrames *
6545 max(kMinNotifications, minNotificationsByMs);
6546 frameCount = max(frameCount, minFrameCount);
6547 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6548 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006549 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006550 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006551 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006552
Glenn Kasten15e57982013-09-24 11:52:37 -07006553 lStatus = initCheck();
6554 if (lStatus != NO_ERROR) {
6555 ALOGE("createRecordTrack_l() audio driver not initialized");
6556 goto Exit;
6557 }
Eric Laurent81784c32012-11-19 14:55:58 -08006558
6559 { // scope for mLock
6560 Mutex::Autolock _l(mLock);
6561
6562 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006563 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006564 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006565
Glenn Kasten03003332013-08-06 15:40:54 -07006566 lStatus = track->initCheck();
6567 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006568 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006569 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006570 goto Exit;
6571 }
6572 mTracks.add(track);
6573
6574 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6575 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6576 mAudioFlinger->btNrecIsOff();
6577 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6578 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006579
Eric Laurent05067782016-06-01 18:27:28 -07006580 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006581 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6582 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6583 // so ask activity manager to do this on our behalf
6584 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6585 }
Eric Laurent81784c32012-11-19 14:55:58 -08006586 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006587
Eric Laurent81784c32012-11-19 14:55:58 -08006588 lStatus = NO_ERROR;
6589
6590Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006591 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006592 return track;
6593}
6594
6595status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6596 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006597 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006598{
6599 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6600 sp<ThreadBase> strongMe = this;
6601 status_t status = NO_ERROR;
6602
6603 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006604 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006605 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006606 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006607 triggerSession,
6608 recordTrack->sessionId(),
6609 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006610 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006611 // Sync event can be cancelled by the trigger session if the track is not in a
6612 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006613 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006614 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006615 } else {
6616 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006617 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006618 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006619 }
6620 }
6621
6622 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006623 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006624 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006625 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6626 if (recordTrack->mState == TrackBase::PAUSING) {
6627 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006628 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006629 } else {
6630 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006631 }
6632 return status;
6633 }
6634
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006635 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6636 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6637 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006638 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006639 mActiveTracks.add(recordTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006640 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006641 status_t status = NO_ERROR;
6642 if (recordTrack->isExternalTrack()) {
6643 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006644 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006645 mLock.lock();
6646 // FIXME should verify that recordTrack is still in mActiveTracks
6647 if (status != NO_ERROR) {
6648 mActiveTracks.remove(recordTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006649 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006650 recordTrack->clearSyncStartEvent();
6651 ALOGV("RecordThread::start error %d", status);
6652 return status;
6653 }
Eric Laurent81784c32012-11-19 14:55:58 -08006654 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006655 // Catch up with current buffer indices if thread is already running.
6656 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6657 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6658 // see previously buffered data before it called start(), but with greater risk of overrun.
6659
Andy Hung73c02e42015-03-29 01:13:58 -07006660 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006661 // clear any converter state as new data will be discontinuous
6662 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006663 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006664 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006665 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006666 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006667 ALOGV("Record failed to start");
6668 status = BAD_VALUE;
6669 goto startError;
6670 }
Eric Laurent81784c32012-11-19 14:55:58 -08006671 return status;
6672 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006673
Eric Laurent81784c32012-11-19 14:55:58 -08006674startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006675 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006676 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006677 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006678 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006679 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006680 return status;
6681}
6682
Eric Laurent81784c32012-11-19 14:55:58 -08006683void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6684{
6685 sp<SyncEvent> strongEvent = event.promote();
6686
6687 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006688 sp<RefBase> ptr = strongEvent->cookie().promote();
6689 if (ptr != 0) {
6690 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6691 recordTrack->handleSyncStartEvent(strongEvent);
6692 }
Eric Laurent81784c32012-11-19 14:55:58 -08006693 }
6694}
6695
Glenn Kastena8356f62013-07-25 14:37:52 -07006696bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006697 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006698 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006699 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006700 return false;
6701 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006702 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006703 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006704 // signal thread to stop
6705 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006706 // do not wait for mStartStopCond if exiting
6707 if (exitPending()) {
6708 return true;
6709 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006710 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006711 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006712 // if we have been restarted, recordTrack is in mActiveTracks here
6713 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006714 ALOGV("Record stopped OK");
6715 return true;
6716 }
6717 return false;
6718}
6719
Glenn Kasten0f11b512014-01-31 16:18:54 -08006720bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006721{
6722 return false;
6723}
6724
Glenn Kasten0f11b512014-01-31 16:18:54 -08006725status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006726{
6727#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6728 if (!isValidSyncEvent(event)) {
6729 return BAD_VALUE;
6730 }
6731
Glenn Kastend848eb42016-03-08 13:42:11 -08006732 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006733 status_t ret = NAME_NOT_FOUND;
6734
6735 Mutex::Autolock _l(mLock);
6736
6737 for (size_t i = 0; i < mTracks.size(); i++) {
6738 sp<RecordTrack> track = mTracks[i];
6739 if (eventSession == track->sessionId()) {
6740 (void) track->setSyncEvent(event);
6741 ret = NO_ERROR;
6742 }
6743 }
6744 return ret;
6745#else
6746 return BAD_VALUE;
6747#endif
6748}
6749
6750// destroyTrack_l() must be called with ThreadBase::mLock held
6751void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6752{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006753 track->terminate();
6754 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006755 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006756 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006757 removeTrack_l(track);
6758 }
6759}
6760
6761void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6762{
6763 mTracks.remove(track);
6764 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006765 if (track->isFastTrack()) {
6766 ALOG_ASSERT(!mFastTrackAvail);
6767 mFastTrackAvail = true;
6768 }
Eric Laurent81784c32012-11-19 14:55:58 -08006769}
6770
6771void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6772{
6773 dumpInternals(fd, args);
6774 dumpTracks(fd, args);
6775 dumpEffectChains(fd, args);
6776}
6777
6778void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6779{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006780 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006781
Glenn Kasten44182c22015-03-05 17:12:23 -08006782 dumpBase(fd, args);
6783
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006784 AudioStreamIn *input = mInput;
6785 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6786 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6787 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006788 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006789 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006790 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006791 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006792 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006793
Glenn Kasten2f90c512015-12-02 11:40:09 -08006794 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6795 // while we are dumping it. It may be inconsistent, but it won't mutate!
6796 // This is a large object so we place it on the heap.
6797 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6798 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6799 copy->dump(fd);
6800 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006801}
6802
Glenn Kasten0f11b512014-01-31 16:18:54 -08006803void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006804{
6805 const size_t SIZE = 256;
6806 char buffer[SIZE];
6807 String8 result;
6808
Marco Nelissenb2208842014-02-07 14:00:50 -08006809 size_t numtracks = mTracks.size();
6810 size_t numactive = mActiveTracks.size();
6811 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006812 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006813 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006814 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006815 RecordTrack::appendDumpHeader(result);
6816 for (size_t i = 0; i < numtracks ; ++i) {
6817 sp<RecordTrack> track = mTracks[i];
6818 if (track != 0) {
6819 bool active = mActiveTracks.indexOf(track) >= 0;
6820 if (active) {
6821 numactiveseen++;
6822 }
6823 track->dump(buffer, SIZE, active);
6824 result.append(buffer);
6825 }
Eric Laurent81784c32012-11-19 14:55:58 -08006826 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006827 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006828 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006829 }
6830
Marco Nelissenb2208842014-02-07 14:00:50 -08006831 if (numactiveseen != numactive) {
6832 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6833 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006834 result.append(buffer);
6835 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006836 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006837 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006838 if (mTracks.indexOf(track) < 0) {
6839 track->dump(buffer, SIZE, true);
6840 result.append(buffer);
6841 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006842 }
Eric Laurent81784c32012-11-19 14:55:58 -08006843
6844 }
6845 write(fd, result.string(), result.size());
6846}
6847
Andy Hung73c02e42015-03-29 01:13:58 -07006848
6849void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6850{
6851 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6852 RecordThread *recordThread = (RecordThread *) threadBase.get();
6853 mRsmpInFront = recordThread->mRsmpInRear;
6854 mRsmpInUnrel = 0;
6855}
6856
6857void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6858 size_t *framesAvailable, bool *hasOverrun)
6859{
6860 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6861 RecordThread *recordThread = (RecordThread *) threadBase.get();
6862 const int32_t rear = recordThread->mRsmpInRear;
6863 const int32_t front = mRsmpInFront;
6864 const ssize_t filled = rear - front;
6865
6866 size_t framesIn;
6867 bool overrun = false;
6868 if (filled < 0) {
6869 // should not happen, but treat like a massive overrun and re-sync
6870 framesIn = 0;
6871 mRsmpInFront = rear;
6872 overrun = true;
6873 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6874 framesIn = (size_t) filled;
6875 } else {
6876 // client is not keeping up with server, but give it latest data
6877 framesIn = recordThread->mRsmpInFrames;
6878 mRsmpInFront = /* front = */ rear - framesIn;
6879 overrun = true;
6880 }
6881 if (framesAvailable != NULL) {
6882 *framesAvailable = framesIn;
6883 }
6884 if (hasOverrun != NULL) {
6885 *hasOverrun = overrun;
6886 }
6887}
6888
Eric Laurent81784c32012-11-19 14:55:58 -08006889// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006890status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006891 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006892{
Andy Hung73c02e42015-03-29 01:13:58 -07006893 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006894 if (threadBase == 0) {
6895 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006896 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006897 return NOT_ENOUGH_DATA;
6898 }
6899 RecordThread *recordThread = (RecordThread *) threadBase.get();
6900 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006901 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006902 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006903 // FIXME should not be P2 (don't want to increase latency)
6904 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006905 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006906 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006907 front &= recordThread->mRsmpInFramesP2 - 1;
6908 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006909 if (part1 > (size_t) filled) {
6910 part1 = filled;
6911 }
6912 size_t ask = buffer->frameCount;
6913 ALOG_ASSERT(ask > 0);
6914 if (part1 > ask) {
6915 part1 = ask;
6916 }
6917 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006918 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006919 buffer->raw = NULL;
6920 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006921 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006922 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006923 }
6924
Andy Hung57446612015-04-19 23:56:46 -07006925 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006926 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006927 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006928 return NO_ERROR;
6929}
6930
6931// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006932void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6933 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006934{
Glenn Kasten85948432013-08-19 12:09:05 -07006935 size_t stepCount = buffer->frameCount;
6936 if (stepCount == 0) {
6937 return;
6938 }
Andy Hung73c02e42015-03-29 01:13:58 -07006939 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6940 mRsmpInUnrel -= stepCount;
6941 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006942 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006943 buffer->frameCount = 0;
6944}
6945
Andy Hung97a893e2015-03-29 01:03:07 -07006946AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6947 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6948 uint32_t srcSampleRate,
6949 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6950 uint32_t dstSampleRate) :
6951 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6952 // mSrcFormat
6953 // mSrcSampleRate
6954 // mDstChannelMask
6955 // mDstFormat
6956 // mDstSampleRate
6957 // mSrcChannelCount
6958 // mDstChannelCount
6959 // mDstFrameSize
6960 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006961 mResampler(NULL),
6962 mIsLegacyDownmix(false),
6963 mIsLegacyUpmix(false),
6964 mRequiresFloat(false),
6965 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006966{
6967 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6968 dstChannelMask, dstFormat, dstSampleRate);
6969}
6970
6971AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6972 free(mBuf);
6973 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006974 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006975}
6976
6977size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6978 AudioBufferProvider *provider, size_t frames)
6979{
Andy Hungd330ee42015-04-20 13:23:41 -07006980 if (mInputConverterProvider != NULL) {
6981 mInputConverterProvider->setBufferProvider(provider);
6982 provider = mInputConverterProvider;
6983 }
6984
6985 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006986 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6987 mSrcSampleRate, mSrcFormat, mDstFormat);
6988
6989 AudioBufferProvider::Buffer buffer;
6990 for (size_t i = frames; i > 0; ) {
6991 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006992 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006993 if (status != OK || buffer.frameCount == 0) {
6994 frames -= i; // cannot fill request.
6995 break;
6996 }
Andy Hungd330ee42015-04-20 13:23:41 -07006997 // format convert to destination buffer
6998 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006999
7000 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7001 i -= buffer.frameCount;
7002 provider->releaseBuffer(&buffer);
7003 }
7004 } else {
7005 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7006 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7007
Andy Hungd330ee42015-04-20 13:23:41 -07007008 // reallocate buffer if needed
7009 if (mBufFrameSize != 0 && mBufFrames < frames) {
7010 free(mBuf);
7011 mBufFrames = frames;
7012 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7013 }
Andy Hung97a893e2015-03-29 01:03:07 -07007014 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007015 memset(mBuf, 0, frames * mBufFrameSize);
7016 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7017 // format convert to destination buffer
7018 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007019 }
7020 return frames;
7021}
7022
7023status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7024 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7025 uint32_t srcSampleRate,
7026 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7027 uint32_t dstSampleRate)
7028{
7029 // quick evaluation if there is any change.
7030 if (mSrcFormat == srcFormat
7031 && mSrcChannelMask == srcChannelMask
7032 && mSrcSampleRate == srcSampleRate
7033 && mDstFormat == dstFormat
7034 && mDstChannelMask == dstChannelMask
7035 && mDstSampleRate == dstSampleRate) {
7036 return NO_ERROR;
7037 }
7038
Andy Hungdb4c0312015-05-06 08:46:52 -07007039 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7040 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7041 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007042 const bool valid =
7043 audio_is_input_channel(srcChannelMask)
7044 && audio_is_input_channel(dstChannelMask)
7045 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7046 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7047 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7048 ; // no upsampling checks for now
7049 if (!valid) {
7050 return BAD_VALUE;
7051 }
7052
7053 mSrcFormat = srcFormat;
7054 mSrcChannelMask = srcChannelMask;
7055 mSrcSampleRate = srcSampleRate;
7056 mDstFormat = dstFormat;
7057 mDstChannelMask = dstChannelMask;
7058 mDstSampleRate = dstSampleRate;
7059
7060 // compute derived parameters
7061 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7062 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7063 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7064
Andy Hungd330ee42015-04-20 13:23:41 -07007065 // do we need to resample?
7066 delete mResampler;
7067 mResampler = NULL;
7068 if (mSrcSampleRate != mDstSampleRate) {
7069 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7070 mSrcChannelCount, mDstSampleRate);
7071 mResampler->setSampleRate(mSrcSampleRate);
7072 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7073 }
7074
7075 // are we running legacy channel conversion modes?
7076 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7077 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7078 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7079 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7080 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7081 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7082
7083 // do we need to process in float?
7084 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7085
7086 // do we need a staging buffer to convert for destination (we can still optimize this)?
7087 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7088 if (mResampler != NULL) {
7089 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7090 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007091 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007092 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7093 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007094 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7095 } else {
7096 mBufFrameSize = 0;
7097 }
7098 mBufFrames = 0; // force the buffer to be resized.
7099
Andy Hungd330ee42015-04-20 13:23:41 -07007100 // do we need an input converter buffer provider to give us float?
7101 delete mInputConverterProvider;
7102 mInputConverterProvider = NULL;
7103 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7104 mInputConverterProvider = new ReformatBufferProvider(
7105 audio_channel_count_from_in_mask(mSrcChannelMask),
7106 mSrcFormat,
7107 AUDIO_FORMAT_PCM_FLOAT,
7108 256 /* provider buffer frame count */);
7109 }
7110
7111 // do we need a remixer to do channel mask conversion
7112 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7113 (void) memcpy_by_index_array_initialization_from_channel_mask(
7114 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007115 }
7116 return NO_ERROR;
7117}
7118
Andy Hungd330ee42015-04-20 13:23:41 -07007119void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7120 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007121{
Andy Hungd330ee42015-04-20 13:23:41 -07007122 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007123 if (mBufFrameSize != 0 && mBufFrames < frames) {
7124 free(mBuf);
7125 mBufFrames = frames;
7126 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7127 }
Andy Hungd330ee42015-04-20 13:23:41 -07007128 // do we need to do legacy upmix and downmix?
7129 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007130 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007131 if (mIsLegacyUpmix) {
7132 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7133 (const float *)src, frames);
7134 } else /*mIsLegacyDownmix */ {
7135 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7136 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007137 }
Andy Hungd330ee42015-04-20 13:23:41 -07007138 if (mBuf != NULL) {
7139 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7140 frames * mDstChannelCount);
7141 }
7142 return;
7143 }
7144 // do we need to do channel mask conversion?
7145 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007146 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007147 memcpy_by_index_array(dstBuf, mDstChannelCount,
7148 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7149 if (dstBuf == dst) {
7150 return; // format is the same
7151 }
7152 }
7153 // convert to destination buffer
7154 const void *convertBuf = mBuf != NULL ? mBuf : src;
7155 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7156 frames * mDstChannelCount);
7157}
7158
7159void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7160 void *dst, /*not-a-const*/ void *src, size_t frames)
7161{
7162 // src buffer format is ALWAYS float when entering this routine
7163 if (mIsLegacyUpmix) {
7164 ; // mono to stereo already handled by resampler
7165 } else if (mIsLegacyDownmix
7166 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7167 // the resampler outputs stereo for mono input channel (a feature?)
7168 // must convert to mono
7169 downmix_to_mono_float_from_stereo_float((float *)src,
7170 (const float *)src, frames);
7171 } else if (mSrcChannelMask != mDstChannelMask) {
7172 // convert to mono channel again for channel mask conversion (could be skipped
7173 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007174 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007175 downmix_to_mono_float_from_stereo_float((float *)src,
7176 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007177 }
Andy Hungd330ee42015-04-20 13:23:41 -07007178 // convert to destination format (in place, OK as float is larger than other types)
7179 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7180 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7181 frames * mSrcChannelCount);
7182 }
7183 // channel convert and save to dst
7184 memcpy_by_index_array(dst, mDstChannelCount,
7185 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7186 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007187 }
Andy Hungd330ee42015-04-20 13:23:41 -07007188 // convert to destination format and save to dst
7189 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7190 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007191}
7192
Eric Laurent10351942014-05-08 18:49:52 -07007193bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7194 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007195{
7196 bool reconfig = false;
7197
Eric Laurent10351942014-05-08 18:49:52 -07007198 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007199
Eric Laurent10351942014-05-08 18:49:52 -07007200 audio_format_t reqFormat = mFormat;
7201 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007202 // 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 -07007203 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7204
7205 AudioParameter param = AudioParameter(keyValuePair);
7206 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007207
7208 // scope for AutoPark extends to end of method
7209 AutoPark<FastCapture> park(mFastCapture);
7210
Eric Laurent10351942014-05-08 18:49:52 -07007211 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7212 // channel count change can be requested. Do we mandate the first client defines the
7213 // HAL sampling rate and channel count or do we allow changes on the fly?
7214 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7215 samplingRate = value;
7216 reconfig = true;
7217 }
7218 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007219 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007220 status = BAD_VALUE;
7221 } else {
7222 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007223 reconfig = true;
7224 }
Eric Laurent10351942014-05-08 18:49:52 -07007225 }
7226 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7227 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007228 if (!audio_is_input_channel(mask) ||
7229 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007230 status = BAD_VALUE;
7231 } else {
7232 channelMask = mask;
7233 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007234 }
Eric Laurent10351942014-05-08 18:49:52 -07007235 }
7236 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7237 // do not accept frame count changes if tracks are open as the track buffer
7238 // size depends on frame count and correct behavior would not be guaranteed
7239 // if frame count is changed after track creation
7240 if (mActiveTracks.size() > 0) {
7241 status = INVALID_OPERATION;
7242 } else {
7243 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007244 }
Eric Laurent10351942014-05-08 18:49:52 -07007245 }
7246 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7247 // forward device change to effects that have requested to be
7248 // aware of attached audio device.
7249 for (size_t i = 0; i < mEffectChains.size(); i++) {
7250 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007251 }
Eric Laurent81784c32012-11-19 14:55:58 -08007252
Eric Laurent10351942014-05-08 18:49:52 -07007253 // store input device and output device but do not forward output device to audio HAL.
7254 // Note that status is ignored by the caller for output device
7255 // (see AudioFlinger::setParameters()
7256 if (audio_is_output_devices(value)) {
7257 mOutDevice = value;
7258 status = BAD_VALUE;
7259 } else {
7260 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007261 if (value != AUDIO_DEVICE_NONE) {
7262 mPrevInDevice = value;
7263 }
Eric Laurent10351942014-05-08 18:49:52 -07007264 // disable AEC and NS if the device is a BT SCO headset supporting those
7265 // pre processings
7266 if (mTracks.size() > 0) {
7267 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7268 mAudioFlinger->btNrecIsOff();
7269 for (size_t i = 0; i < mTracks.size(); i++) {
7270 sp<RecordTrack> track = mTracks[i];
7271 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7272 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007273 }
7274 }
7275 }
Eric Laurent10351942014-05-08 18:49:52 -07007276 }
7277 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7278 mAudioSource != (audio_source_t)value) {
7279 // forward device change to effects that have requested to be
7280 // aware of attached audio device.
7281 for (size_t i = 0; i < mEffectChains.size(); i++) {
7282 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007283 }
Eric Laurent10351942014-05-08 18:49:52 -07007284 mAudioSource = (audio_source_t)value;
7285 }
Glenn Kastene198c362013-08-13 09:13:36 -07007286
Eric Laurent10351942014-05-08 18:49:52 -07007287 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007288 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007289 if (status == INVALID_OPERATION) {
7290 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007291 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007292 }
7293 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007294 if (status == BAD_VALUE) {
7295 uint32_t sRate;
7296 audio_channel_mask_t channelMask;
7297 audio_format_t format;
7298 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7299 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7300 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7301 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7302 status = NO_ERROR;
7303 }
Eric Laurent81784c32012-11-19 14:55:58 -08007304 }
Eric Laurent10351942014-05-08 18:49:52 -07007305 if (status == NO_ERROR) {
7306 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007307 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007308 }
7309 }
Eric Laurent81784c32012-11-19 14:55:58 -08007310 }
Eric Laurent10351942014-05-08 18:49:52 -07007311
Eric Laurent81784c32012-11-19 14:55:58 -08007312 return reconfig;
7313}
7314
7315String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7316{
Eric Laurent81784c32012-11-19 14:55:58 -08007317 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007318 if (initCheck() == NO_ERROR) {
7319 String8 out_s8;
7320 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7321 return out_s8;
7322 }
Eric Laurent81784c32012-11-19 14:55:58 -08007323 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007324 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007325}
7326
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007327void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007328 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7329
7330 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007331
7332 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007333 case AUDIO_INPUT_OPENED:
7334 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007335 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007336 desc->mChannelMask = mChannelMask;
7337 desc->mSamplingRate = mSampleRate;
7338 desc->mFormat = mFormat;
7339 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007340 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007341 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007342 break;
7343
Eric Laurent73e26b62015-04-27 16:55:58 -07007344 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007345 default:
7346 break;
7347 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007348 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007349}
7350
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007351void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007352{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007353 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7354 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007355 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007356 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007357 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007358 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7359 result = mInput->stream->getFrameSize(&mFrameSize);
7360 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7361 result = mInput->stream->getBufferSize(&mBufferSize);
7362 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007363 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007364 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007365 // 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 -07007366 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007367 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007368 // A larger value should allow more old data to be read after a track calls start(),
7369 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007370 //
7371 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007372 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007373 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007374 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007375 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007376
7377 // TODO optimize audio capture buffer sizes ...
7378 // Here we calculate the size of the sliding buffer used as a source
7379 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7380 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7381 // be better to have it derived from the pipe depth in the long term.
7382 // The current value is higher than necessary. However it should not add to latency.
7383
Glenn Kasten85948432013-08-19 12:09:05 -07007384 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007385 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7386 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7387 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007388
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007389 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7390 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007391}
7392
Glenn Kasten5f972c02014-01-13 09:59:31 -08007393uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007394{
7395 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007396 uint32_t result;
7397 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7398 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007399 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007400 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007401}
7402
Eric Laurent4c415062016-06-17 16:14:16 -07007403// hasAudioSession_l() must be called with ThreadBase::mLock held
7404uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007405{
Eric Laurent81784c32012-11-19 14:55:58 -08007406 uint32_t result = 0;
7407 if (getEffectChain_l(sessionId) != 0) {
7408 result = EFFECT_SESSION;
7409 }
7410
7411 for (size_t i = 0; i < mTracks.size(); ++i) {
7412 if (sessionId == mTracks[i]->sessionId()) {
7413 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007414 if (mTracks[i]->isFastTrack()) {
7415 result |= FAST_SESSION;
7416 }
Eric Laurent81784c32012-11-19 14:55:58 -08007417 break;
7418 }
7419 }
7420
7421 return result;
7422}
7423
Glenn Kastend848eb42016-03-08 13:42:11 -08007424KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007425{
Glenn Kastend848eb42016-03-08 13:42:11 -08007426 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007427 Mutex::Autolock _l(mLock);
7428 for (size_t j = 0; j < mTracks.size(); ++j) {
7429 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007430 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007431 if (ids.indexOfKey(sessionId) < 0) {
7432 ids.add(sessionId, true);
7433 }
7434 }
7435 return ids;
7436}
7437
7438AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7439{
7440 Mutex::Autolock _l(mLock);
7441 AudioStreamIn *input = mInput;
7442 mInput = NULL;
7443 return input;
7444}
7445
7446// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007447sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007448{
7449 if (mInput == NULL) {
7450 return NULL;
7451 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007452 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007453}
7454
7455status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7456{
7457 // only one chain per input thread
7458 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007459 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007460 return INVALID_OPERATION;
7461 }
7462 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007463 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007464 chain->setInBuffer(NULL);
7465 chain->setOutBuffer(NULL);
7466
7467 checkSuspendOnAddEffectChain_l(chain);
7468
Eric Laurent1b928682014-10-02 19:41:47 -07007469 // make sure enabled pre processing effects state is communicated to the HAL as we
7470 // just moved them to a new input stream.
7471 chain->syncHalEffectsState();
7472
Eric Laurent81784c32012-11-19 14:55:58 -08007473 mEffectChains.add(chain);
7474
7475 return NO_ERROR;
7476}
7477
7478size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7479{
7480 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7481 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007482 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007483 chain.get(), mEffectChains.size(), this);
7484 if (mEffectChains.size() == 1) {
7485 mEffectChains.removeAt(0);
7486 }
7487 return 0;
7488}
7489
Eric Laurent1c333e22014-05-20 10:48:17 -07007490status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7491 audio_patch_handle_t *handle)
7492{
7493 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007494
7495 // store new device and send to effects
7496 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007497 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007498 for (size_t i = 0; i < mEffectChains.size(); i++) {
7499 mEffectChains[i]->setDevice_l(mInDevice);
7500 }
7501
7502 // disable AEC and NS if the device is a BT SCO headset supporting those
7503 // pre processings
7504 if (mTracks.size() > 0) {
7505 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7506 mAudioFlinger->btNrecIsOff();
7507 for (size_t i = 0; i < mTracks.size(); i++) {
7508 sp<RecordTrack> track = mTracks[i];
7509 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7510 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7511 }
7512 }
7513
7514 // store new source and send to effects
7515 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7516 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007517 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007518 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007519 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007520 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007521
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007522 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007523 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7524 status = hwDevice->createAudioPatch(patch->num_sources,
7525 patch->sources,
7526 patch->num_sinks,
7527 patch->sinks,
7528 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007529 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007530 char *address;
7531 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7532 address = audio_device_address_to_parameter(
7533 patch->sources[0].ext.device.type,
7534 patch->sources[0].ext.device.address);
7535 } else {
7536 address = (char *)calloc(1, 1);
7537 }
7538 AudioParameter param = AudioParameter(String8(address));
7539 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007540 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007541 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007542 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007543 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007544 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007545 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007546 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007547
Eric Laurente8726fe2015-06-26 09:39:24 -07007548 if (mInDevice != mPrevInDevice) {
7549 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7550 mPrevInDevice = mInDevice;
7551 }
Eric Laurent296fb132015-05-01 11:38:42 -07007552
Eric Laurent1c333e22014-05-20 10:48:17 -07007553 return status;
7554}
7555
7556status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7557{
7558 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007559
7560 mInDevice = AUDIO_DEVICE_NONE;
7561
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007562 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007563 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7564 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007565 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007566 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007567 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007568 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007569 }
7570 return status;
7571}
7572
Eric Laurent83b88082014-06-20 18:31:16 -07007573void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7574{
7575 Mutex::Autolock _l(mLock);
7576 mTracks.add(record);
7577}
7578
7579void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7580{
7581 Mutex::Autolock _l(mLock);
7582 destroyTrack_l(record);
7583}
7584
7585void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7586{
7587 ThreadBase::getAudioPortConfig(config);
7588 config->role = AUDIO_PORT_ROLE_SINK;
7589 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7590 config->ext.mix.usecase.source = mAudioSource;
7591}
Eric Laurent1c333e22014-05-20 10:48:17 -07007592
Glenn Kasten63238ef2015-03-02 15:50:29 -08007593} // namespace android