blob: 9966eebad950df27c5595b4de9457c2ded33bb78 [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 Laurent81784c32012-11-19 14:55:58 -08001757 status_t *status)
1758{
Glenn Kasten74935e42013-12-19 08:56:45 -08001759 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001760 sp<Track> track;
1761 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001762 audio_output_flags_t outputFlags = mOutput->flags;
1763
1764 // special case for FAST flag considered OK if fast mixer is present
1765 if (hasFastMixer()) {
1766 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1767 }
1768
1769 // Check if requested flags are compatible with output stream flags
1770 if ((*flags & outputFlags) != *flags) {
1771 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1772 *flags, outputFlags);
1773 *flags = (audio_output_flags_t)(*flags & outputFlags);
1774 }
Eric Laurent81784c32012-11-19 14:55:58 -08001775
Eric Laurent81784c32012-11-19 14:55:58 -08001776 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001777 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001778 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001779 // PCM data
1780 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001781 // TODO: extract as a data library function that checks that a computationally
1782 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001783 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001784 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1785 (channelMask == AUDIO_CHANNEL_OUT_MONO
1786 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001787 // hardware sample rate
1788 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001789 // normal mixer has an associated fast mixer
1790 hasFastMixer() &&
1791 // there are sufficient fast track slots available
1792 (mFastTrackAvailMask != 0)
1793 // FIXME test that MixerThread for this fast track has a capable output HAL
1794 // FIXME add a permission test also?
1795 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001796 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1797 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001798 // read the fast track multiplier property the first time it is needed
1799 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1800 if (ok != 0) {
1801 ALOGE("%s pthread_once failed: %d", __func__, ok);
1802 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001803 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001804 }
Eric Laurent4c415062016-06-17 16:14:16 -07001805
1806 // check compatibility with audio effects.
1807 { // scope for mLock
1808 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001809 for (audio_session_t session : {
1810 AUDIO_SESSION_OUTPUT_STAGE,
1811 AUDIO_SESSION_OUTPUT_MIX,
1812 sessionId,
1813 }) {
1814 sp<EffectChain> chain = getEffectChain_l(session);
1815 if (chain.get() != nullptr) {
1816 audio_output_flags_t old = *flags;
1817 chain->checkOutputFlagCompatibility(flags);
1818 if (old != *flags) {
1819 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1820 (int)session, (int)old, (int)*flags);
1821 }
Eric Laurent4c415062016-06-17 16:14:16 -07001822 }
1823 }
1824 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001825 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001826 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1827 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001828 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001829 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1830 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001831 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001832 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001833 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001834 audio_is_linear_pcm(format),
1835 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001836 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001837 }
1838 }
1839 // For normal PCM streaming tracks, update minimum frame count.
1840 // For compatibility with AudioTrack calculation, buffer depth is forced
1841 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1842 // This is probably too conservative, but legacy application code may depend on it.
1843 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001844 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001845 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001846 // this must match AudioTrack.cpp calculateMinFrameCount().
1847 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001848 uint32_t latencyMs = 0;
1849 lStatus = mOutput->stream->getLatency(&latencyMs);
1850 if (lStatus != OK) {
1851 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1852 goto Exit;
1853 }
Eric Laurent81784c32012-11-19 14:55:58 -08001854 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1855 if (minBufCount < 2) {
1856 minBufCount = 2;
1857 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001858 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1859 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001860 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001861 minBufCount * sourceFramesNeededWithTimestretch(
1862 sampleRate, mNormalFrameCount,
1863 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001864 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001865 frameCount = minFrameCount;
1866 }
Eric Laurent81784c32012-11-19 14:55:58 -08001867 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001868 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001869
Glenn Kastenc3df8382014-03-13 15:05:25 -07001870 switch (mType) {
1871
1872 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001873 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001874 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001875 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1876 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001877 sampleRate, format, channelMask, mOutput, mFormat);
1878 lStatus = BAD_VALUE;
1879 goto Exit;
1880 }
1881 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001882 break;
1883
1884 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001885 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001886 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1887 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001888 sampleRate, format, channelMask, mOutput, mFormat);
1889 lStatus = BAD_VALUE;
1890 goto Exit;
1891 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001892 break;
1893
1894 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001895 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001896 ALOGE("createTrack_l() Bad parameter: format %#x \""
1897 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001898 format, mOutput, mFormat);
1899 lStatus = BAD_VALUE;
1900 goto Exit;
1901 }
Andy Hungcd044842014-08-07 11:04:34 -07001902 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001903 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1904 lStatus = BAD_VALUE;
1905 goto Exit;
1906 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001907 break;
1908
Eric Laurent81784c32012-11-19 14:55:58 -08001909 }
1910
1911 lStatus = initCheck();
1912 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001913 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001914 goto Exit;
1915 }
1916
1917 { // scope for mLock
1918 Mutex::Autolock _l(mLock);
1919
1920 // all tracks in same audio session must share the same routing strategy otherwise
1921 // conflicts will happen when tracks are moved from one output to another by audio policy
1922 // manager
1923 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1924 for (size_t i = 0; i < mTracks.size(); ++i) {
1925 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001926 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001927 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1928 if (sessionId == t->sessionId() && strategy != actual) {
1929 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1930 strategy, actual);
1931 lStatus = BAD_VALUE;
1932 goto Exit;
1933 }
1934 }
1935 }
1936
Glenn Kastend79072e2016-01-06 08:41:20 -08001937 track = new Track(this, client, streamType, sampleRate, format,
1938 channelMask, frameCount, NULL, sharedBuffer,
1939 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001940
Glenn Kasten03003332013-08-06 15:40:54 -07001941 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1942 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001943 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001944 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001945 goto Exit;
1946 }
1947 mTracks.add(track);
1948
1949 sp<EffectChain> chain = getEffectChain_l(sessionId);
1950 if (chain != 0) {
1951 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1952 track->setMainBuffer(chain->inBuffer());
1953 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1954 chain->incTrackCnt();
1955 }
1956
Eric Laurent05067782016-06-01 18:27:28 -07001957 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001958 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1959 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1960 // so ask activity manager to do this on our behalf
1961 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1962 }
1963 }
1964
1965 lStatus = NO_ERROR;
1966
1967Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001968 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001969 return track;
1970}
1971
1972uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1973{
1974 return latency;
1975}
1976
1977uint32_t AudioFlinger::PlaybackThread::latency() const
1978{
1979 Mutex::Autolock _l(mLock);
1980 return latency_l();
1981}
1982uint32_t AudioFlinger::PlaybackThread::latency_l() const
1983{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001984 uint32_t latency;
1985 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
1986 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08001987 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001988 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001989}
1990
1991void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1992{
1993 Mutex::Autolock _l(mLock);
1994 // Don't apply master volume in SW if our HAL can do it for us.
1995 if (mOutput && mOutput->audioHwDev &&
1996 mOutput->audioHwDev->canSetMasterVolume()) {
1997 mMasterVolume = 1.0;
1998 } else {
1999 mMasterVolume = value;
2000 }
2001}
2002
2003void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2004{
2005 Mutex::Autolock _l(mLock);
2006 // Don't apply master mute in SW if our HAL can do it for us.
2007 if (mOutput && mOutput->audioHwDev &&
2008 mOutput->audioHwDev->canSetMasterMute()) {
2009 mMasterMute = false;
2010 } else {
2011 mMasterMute = muted;
2012 }
2013}
2014
2015void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2016{
2017 Mutex::Autolock _l(mLock);
2018 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002019 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002020}
2021
2022void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2023{
2024 Mutex::Autolock _l(mLock);
2025 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002026 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002027}
2028
2029float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2030{
2031 Mutex::Autolock _l(mLock);
2032 return mStreamTypes[stream].volume;
2033}
2034
2035// addTrack_l() must be called with ThreadBase::mLock held
2036status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2037{
2038 status_t status = ALREADY_EXISTS;
2039
Eric Laurent81784c32012-11-19 14:55:58 -08002040 if (mActiveTracks.indexOf(track) < 0) {
2041 // the track is newly added, make sure it fills up all its
2042 // buffers before playing. This is to ensure the client will
2043 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002044 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002045 TrackBase::track_state state = track->mState;
2046 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002047 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002048 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002049 mLock.lock();
2050 // abort track was stopped/paused while we released the lock
2051 if (state != track->mState) {
2052 if (status == NO_ERROR) {
2053 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002054 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002055 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002056 mLock.lock();
2057 }
2058 return INVALID_OPERATION;
2059 }
2060 // abort if start is rejected by audio policy manager
2061 if (status != NO_ERROR) {
2062 return PERMISSION_DENIED;
2063 }
2064#ifdef ADD_BATTERY_DATA
2065 // to track the speaker usage
2066 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2067#endif
2068 }
2069
Eric Laurent51716182016-02-29 18:00:56 -08002070 // set retry count for buffer fill
2071 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002072 if (track->isStopping_1()) {
2073 track->mRetryCount = kMaxTrackStopRetriesOffload;
2074 } else {
2075 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2076 }
2077 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002078 } else {
2079 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002080 track->mFillingUpStatus =
2081 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002082 }
2083
Eric Laurent81784c32012-11-19 14:55:58 -08002084 track->mResetDone = false;
2085 track->mPresentationCompleteFrames = 0;
2086 mActiveTracks.add(track);
Eric Laurent9cab7462016-11-10 13:05:20 -08002087 mWakeLockUids.add(track->uid());
2088 mActiveTracksGeneration++;
2089 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002090 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2091 if (chain != 0) {
2092 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2093 track->sessionId());
2094 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002095 }
2096
Andy Hung2148bf02016-11-28 19:01:02 -08002097 char buffer[256];
2098 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2099 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2100
Eric Laurent81784c32012-11-19 14:55:58 -08002101 status = NO_ERROR;
2102 }
2103
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002104 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002105 return status;
2106}
2107
Eric Laurentbfb1b832013-01-07 09:53:42 -08002108bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002109{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002110 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002111 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002112 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2113 track->mState = TrackBase::STOPPED;
2114 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002115 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002116 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002117 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002118 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002119
2120 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002121}
2122
2123void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2124{
2125 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002126
2127 char buffer[256];
2128 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2129 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2130
Eric Laurent81784c32012-11-19 14:55:58 -08002131 mTracks.remove(track);
2132 deleteTrackName_l(track->name());
2133 // redundant as track is about to be destroyed, for dumpsys only
2134 track->mName = -1;
2135 if (track->isFastTrack()) {
2136 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002137 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002138 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2139 mFastTrackAvailMask |= 1 << index;
2140 // redundant as track is about to be destroyed, for dumpsys only
2141 track->mFastIndex = -1;
2142 }
2143 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2144 if (chain != 0) {
2145 chain->decTrackCnt();
2146 }
2147}
2148
Eric Laurentede6c3b2013-09-19 14:37:46 -07002149void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002150{
2151 // Thread could be blocked waiting for async
2152 // so signal it to handle state changes immediately
2153 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2154 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2155 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002156 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157}
2158
Eric Laurent81784c32012-11-19 14:55:58 -08002159String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2160{
Eric Laurent81784c32012-11-19 14:55:58 -08002161 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002162 String8 out_s8;
2163 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2164 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002165 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002166 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002167}
2168
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002169void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002170 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2171 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002172
Eric Laurent73e26b62015-04-27 16:55:58 -07002173 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002174
2175 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002176 case AUDIO_OUTPUT_OPENED:
2177 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002178 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002179 desc->mChannelMask = mChannelMask;
2180 desc->mSamplingRate = mSampleRate;
2181 desc->mFormat = mFormat;
2182 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002183 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002184 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002185 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002186 break;
2187
Eric Laurent73e26b62015-04-27 16:55:58 -07002188 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002189 default:
2190 break;
2191 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002192 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002193}
2194
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002195void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002196{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002197 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002198}
2199
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002200void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002201{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002202 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002203}
2204
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002205void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002206{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002207 mCallbackThread->setAsyncError();
2208}
2209
Eric Laurent3b4529e2013-09-05 18:09:19 -07002210void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002211{
2212 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002213 // reject out of sequence requests
2214 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2215 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002216 mWaitWorkCV.signal();
2217 }
2218}
2219
Eric Laurent3b4529e2013-09-05 18:09:19 -07002220void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002221{
2222 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002223 // reject out of sequence requests
2224 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2225 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002226 mWaitWorkCV.signal();
2227 }
2228}
2229
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002230void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002231{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002232 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002233 mSampleRate = mOutput->getSampleRate();
2234 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002235 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002236 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002237 }
Andy Hung9a592762014-07-21 21:56:01 -07002238 if ((mType == MIXER || mType == DUPLICATING)
2239 && !isValidPcmSinkChannelMask(mChannelMask)) {
2240 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2241 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002242 }
Andy Hunge5412692014-05-16 11:25:07 -07002243 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002244
2245 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002246 status_t result = mOutput->stream->getFormat(&mHALFormat);
2247 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002248 // Get format from the shim, which will be different than the HAL format
2249 // if playing compressed audio over HDMI passthrough.
2250 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002251 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002252 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002253 }
Andy Hung6146c082014-03-18 11:56:15 -07002254 if ((mType == MIXER || mType == DUPLICATING)
2255 && !isValidPcmSinkFormat(mFormat)) {
2256 LOG_FATAL("HAL format %#x not supported for mixed output",
2257 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002258 }
Phil Burk062e67a2015-02-11 13:40:50 -08002259 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002260 result = mOutput->stream->getBufferSize(&mBufferSize);
2261 LOG_ALWAYS_FATAL_IF(result != OK,
2262 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002263 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002264 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002265 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002266 mFrameCount);
2267 }
2268
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002269 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2270 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002271 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002272 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273 }
2274 }
2275
Eric Laurentd1f69b02014-12-15 14:33:13 -08002276 mHwSupportsPause = false;
2277 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002278 bool supportsPause = false, supportsResume = false;
2279 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2280 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002281 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002282 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002283 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002284 } else if (supportsResume) {
2285 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002286 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002287 }
2288 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002289 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2290 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2291 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002292
Andy Hungfbfc3952015-01-15 13:33:51 -08002293 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2294 // For best precision, we use float instead of the associated output
2295 // device format (typically PCM 16 bit).
2296
2297 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2298 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2299 mBufferSize = mFrameSize * mFrameCount;
2300
2301 // TODO: We currently use the associated output device channel mask and sample rate.
2302 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2303 // (if a valid mask) to avoid premature downmix.
2304 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2305 // instead of the output device sample rate to avoid loss of high frequency information.
2306 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2307 }
2308
Andy Hung09a50072014-02-27 14:30:47 -08002309 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002310 double multiplier = 1.0;
2311 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2312 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002313 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2314 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002315
Eric Laurent81784c32012-11-19 14:55:58 -08002316 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2317 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2318 maxNormalFrameCount = maxNormalFrameCount & ~15;
2319 if (maxNormalFrameCount < minNormalFrameCount) {
2320 maxNormalFrameCount = minNormalFrameCount;
2321 }
2322 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2323 if (multiplier <= 1.0) {
2324 multiplier = 1.0;
2325 } else if (multiplier <= 2.0) {
2326 if (2 * mFrameCount <= maxNormalFrameCount) {
2327 multiplier = 2.0;
2328 } else {
2329 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2330 }
2331 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002332 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002333 }
2334 }
2335 mNormalFrameCount = multiplier * mFrameCount;
2336 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002337 if (mType == MIXER || mType == DUPLICATING) {
2338 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2339 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002340 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002341 mNormalFrameCount);
2342
Andy Hung08fb1742015-05-31 23:22:10 -07002343 // Check if we want to throttle the processing to no more than 2x normal rate
2344 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002345 mThreadThrottleTimeMs = 0;
2346 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002347 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2348
Andy Hung010a1a12014-03-13 13:57:33 -07002349 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2350 // Originally this was int16_t[] array, need to remove legacy implications.
2351 free(mSinkBuffer);
2352 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002353 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2354 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2355 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002356 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002357
Andy Hung69aed5f2014-02-25 17:24:40 -08002358 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2359 // drives the output.
2360 free(mMixerBuffer);
2361 mMixerBuffer = NULL;
2362 if (mMixerBufferEnabled) {
2363 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2364 mMixerBufferSize = mNormalFrameCount * mChannelCount
2365 * audio_bytes_per_sample(mMixerBufferFormat);
2366 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2367 }
Andy Hung98ef9782014-03-04 14:46:50 -08002368 free(mEffectBuffer);
2369 mEffectBuffer = NULL;
2370 if (mEffectBufferEnabled) {
2371 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2372 mEffectBufferSize = mNormalFrameCount * mChannelCount
2373 * audio_bytes_per_sample(mEffectBufferFormat);
2374 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2375 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002376
Eric Laurent81784c32012-11-19 14:55:58 -08002377 // force reconfiguration of effect chains and engines to take new buffer size and audio
2378 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002379 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002380 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2381 // matter.
2382 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2383 Vector< sp<EffectChain> > effectChains = mEffectChains;
2384 for (size_t i = 0; i < effectChains.size(); i ++) {
2385 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2386 }
2387}
2388
2389
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002390status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002391{
2392 if (halFrames == NULL || dspFrames == NULL) {
2393 return BAD_VALUE;
2394 }
2395 Mutex::Autolock _l(mLock);
2396 if (initCheck() != NO_ERROR) {
2397 return INVALID_OPERATION;
2398 }
Andy Hung818e7a32016-02-16 18:08:07 -08002399 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002400 *halFrames = framesWritten;
2401
2402 if (isSuspended()) {
2403 // return an estimation of rendered frames when the output is suspended
2404 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002405 *dspFrames = (uint32_t)
2406 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002407 return NO_ERROR;
2408 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002409 status_t status;
2410 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002411 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002412 *dspFrames = (size_t)frames;
2413 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002414 }
2415}
2416
Eric Laurent4c415062016-06-17 16:14:16 -07002417// hasAudioSession_l() must be called with ThreadBase::mLock held
2418uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002419{
Eric Laurent81784c32012-11-19 14:55:58 -08002420 uint32_t result = 0;
2421 if (getEffectChain_l(sessionId) != 0) {
2422 result = EFFECT_SESSION;
2423 }
2424
2425 for (size_t i = 0; i < mTracks.size(); ++i) {
2426 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002427 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002428 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002429 if (track->isFastTrack()) {
2430 result |= FAST_SESSION;
2431 }
Eric Laurent81784c32012-11-19 14:55:58 -08002432 break;
2433 }
2434 }
2435
2436 return result;
2437}
2438
Glenn Kastend848eb42016-03-08 13:42:11 -08002439uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002440{
2441 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2442 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2443 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2444 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2445 }
2446 for (size_t i = 0; i < mTracks.size(); i++) {
2447 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002448 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002449 return AudioSystem::getStrategyForStream(track->streamType());
2450 }
2451 }
2452 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2453}
2454
2455
Phil Burk062e67a2015-02-11 13:40:50 -08002456AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002457{
2458 Mutex::Autolock _l(mLock);
2459 return mOutput;
2460}
2461
Phil Burk062e67a2015-02-11 13:40:50 -08002462AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002463{
2464 Mutex::Autolock _l(mLock);
2465 AudioStreamOut *output = mOutput;
2466 mOutput = NULL;
2467 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2468 // must push a NULL and wait for ack
2469 mOutputSink.clear();
2470 mPipeSink.clear();
2471 mNormalSink.clear();
2472 return output;
2473}
2474
2475// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002476sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002477{
2478 if (mOutput == NULL) {
2479 return NULL;
2480 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002481 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002482}
2483
2484uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2485{
2486 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2487}
2488
2489status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2490{
2491 if (!isValidSyncEvent(event)) {
2492 return BAD_VALUE;
2493 }
2494
2495 Mutex::Autolock _l(mLock);
2496
2497 for (size_t i = 0; i < mTracks.size(); ++i) {
2498 sp<Track> track = mTracks[i];
2499 if (event->triggerSession() == track->sessionId()) {
2500 (void) track->setSyncEvent(event);
2501 return NO_ERROR;
2502 }
2503 }
2504
2505 return NAME_NOT_FOUND;
2506}
2507
2508bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2509{
2510 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2511}
2512
2513void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2514 const Vector< sp<Track> >& tracksToRemove)
2515{
2516 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002517 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002518 for (size_t i = 0 ; i < count ; i++) {
2519 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002520 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002521 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002522 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002523#ifdef ADD_BATTERY_DATA
2524 // to track the speaker usage
2525 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2526#endif
2527 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002528 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002529 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002530 }
Eric Laurent81784c32012-11-19 14:55:58 -08002531 }
2532 }
2533 }
Eric Laurent81784c32012-11-19 14:55:58 -08002534}
2535
2536void AudioFlinger::PlaybackThread::checkSilentMode_l()
2537{
2538 if (!mMasterMute) {
2539 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002540 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2541 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2542 return;
2543 }
Eric Laurent81784c32012-11-19 14:55:58 -08002544 if (property_get("ro.audio.silent", value, "0") > 0) {
2545 char *endptr;
2546 unsigned long ul = strtoul(value, &endptr, 0);
2547 if (*endptr == '\0' && ul != 0) {
2548 ALOGD("Silence is golden");
2549 // The setprop command will not allow a property to be changed after
2550 // the first time it is set, so we don't have to worry about un-muting.
2551 setMasterMute_l(true);
2552 }
2553 }
2554 }
2555}
2556
2557// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002558ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002559{
Eric Laurent81784c32012-11-19 14:55:58 -08002560 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002561 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002562 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002563
2564 // If an NBAIO sink is present, use it to write the normal mixer's submix
2565 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002566
Andy Hung010a1a12014-03-13 13:57:33 -07002567 const size_t count = mBytesRemaining / mFrameSize;
2568
Simon Wilson2d590962012-11-29 15:18:50 -08002569 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002570 // update the setpoint when AudioFlinger::mScreenState changes
2571 uint32_t screenState = AudioFlinger::mScreenState;
2572 if (screenState != mScreenState) {
2573 mScreenState = screenState;
2574 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2575 if (pipe != NULL) {
2576 pipe->setAvgFrames((mScreenState & 1) ?
2577 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2578 }
2579 }
Andy Hung010a1a12014-03-13 13:57:33 -07002580 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002581 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002582 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002583 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002584 } else {
2585 bytesWritten = framesWritten;
2586 }
2587 // otherwise use the HAL / AudioStreamOut directly
2588 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002589 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002590
Eric Laurentbfb1b832013-01-07 09:53:42 -08002591 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002592 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2593 mWriteAckSequence += 2;
2594 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002596 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002598 // FIXME We should have an implementation of timestamps for direct output threads.
2599 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002600 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002601
Eric Laurentbfb1b832013-01-07 09:53:42 -08002602 if (mUseAsyncWrite &&
2603 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2604 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002605 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002606 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002607 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002608 }
Eric Laurent81784c32012-11-19 14:55:58 -08002609 }
2610
Eric Laurent81784c32012-11-19 14:55:58 -08002611 mNumWrites++;
2612 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002613 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002614 return bytesWritten;
2615}
2616
2617void AudioFlinger::PlaybackThread::threadLoop_drain()
2618{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002619 bool supportsDrain = false;
2620 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002621 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2622 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002623 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2624 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002625 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002626 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002627 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002628 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002629 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002630 }
2631}
2632
2633void AudioFlinger::PlaybackThread::threadLoop_exit()
2634{
Eric Laurent275e8e92014-11-30 15:14:47 -08002635 {
2636 Mutex::Autolock _l(mLock);
2637 for (size_t i = 0; i < mTracks.size(); i++) {
2638 sp<Track> track = mTracks[i];
2639 track->invalidate();
2640 }
2641 }
Eric Laurent81784c32012-11-19 14:55:58 -08002642}
2643
2644/*
2645The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002646 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002647 - mActiveSleepTimeUs from activeSleepTimeUs()
2648 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002649 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2650 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002651 - maxPeriod from frame count and sample rate (MIXER only)
2652
2653The parameters that affect these derived values are:
2654 - frame count
2655 - frame size
2656 - sample rate
2657 - device type: A2DP or not
2658 - device latency
2659 - format: PCM or not
2660 - active sleep time
2661 - idle sleep time
2662*/
2663
2664void AudioFlinger::PlaybackThread::cacheParameters_l()
2665{
Andy Hung25c2dac2014-02-27 14:56:00 -08002666 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002667 mActiveSleepTimeUs = activeSleepTimeUs();
2668 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002669
2670 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2671 // truncating audio when going to standby.
2672 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2673 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2674 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2675 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2676 }
2677 }
Eric Laurent81784c32012-11-19 14:55:58 -08002678}
2679
Eric Laurent13084622016-05-17 10:51:49 -07002680bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002681{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002682 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002683 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002684 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002685 size_t size = mTracks.size();
2686 for (size_t i = 0; i < size; i++) {
2687 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002688 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002689 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002690 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002691 }
2692 }
Eric Laurent13084622016-05-17 10:51:49 -07002693 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002694}
2695
Haynes Mathew George05317d22016-05-03 16:34:26 -07002696void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2697{
2698 Mutex::Autolock _l(mLock);
2699 invalidateTracks_l(streamType);
2700}
2701
Eric Laurent81784c32012-11-19 14:55:58 -08002702status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2703{
Glenn Kastend848eb42016-03-08 13:42:11 -08002704 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002705 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2706 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002707 bool ownsBuffer = false;
2708
2709 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002710 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002711 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002712 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002713 if (mType != DIRECT) {
2714 size_t numSamples = mNormalFrameCount * mChannelCount;
2715 buffer = new int16_t[numSamples];
2716 memset(buffer, 0, numSamples * sizeof(int16_t));
2717 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2718 ownsBuffer = true;
2719 }
2720
2721 // Attach all tracks with same session ID to this chain.
2722 for (size_t i = 0; i < mTracks.size(); ++i) {
2723 sp<Track> track = mTracks[i];
2724 if (session == track->sessionId()) {
2725 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2726 buffer);
2727 track->setMainBuffer(buffer);
2728 chain->incTrackCnt();
2729 }
2730 }
2731
2732 // indicate all active tracks in the chain
Eric Laurent9cab7462016-11-10 13:05:20 -08002733 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2734 sp<Track> track = mActiveTracks[i].promote();
2735 if (track == 0) {
2736 continue;
2737 }
Eric Laurent81784c32012-11-19 14:55:58 -08002738 if (session == track->sessionId()) {
2739 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2740 chain->incActiveTrackCnt();
2741 }
2742 }
2743 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002744 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002745 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002746 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2747 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002748 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002749 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002750 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2751 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002752 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002753 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002754 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002755 // Effect chain for other sessions are inserted at beginning of effect
2756 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002757 // sessions is not important.
2758 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2759 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2760 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002761 size_t size = mEffectChains.size();
2762 size_t i = 0;
2763 for (i = 0; i < size; i++) {
2764 if (mEffectChains[i]->sessionId() < session) {
2765 break;
2766 }
2767 }
2768 mEffectChains.insertAt(chain, i);
2769 checkSuspendOnAddEffectChain_l(chain);
2770
2771 return NO_ERROR;
2772}
2773
2774size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2775{
Glenn Kastend848eb42016-03-08 13:42:11 -08002776 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002777
2778 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2779
2780 for (size_t i = 0; i < mEffectChains.size(); i++) {
2781 if (chain == mEffectChains[i]) {
2782 mEffectChains.removeAt(i);
2783 // detach all active tracks from the chain
Eric Laurent9cab7462016-11-10 13:05:20 -08002784 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2785 sp<Track> track = mActiveTracks[i].promote();
2786 if (track == 0) {
2787 continue;
2788 }
Eric Laurent81784c32012-11-19 14:55:58 -08002789 if (session == track->sessionId()) {
2790 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2791 chain.get(), session);
2792 chain->decActiveTrackCnt();
2793 }
2794 }
2795
2796 // detach all tracks with same session ID from this chain
2797 for (size_t i = 0; i < mTracks.size(); ++i) {
2798 sp<Track> track = mTracks[i];
2799 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002800 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002801 chain->decTrackCnt();
2802 }
2803 }
2804 break;
2805 }
2806 }
2807 return mEffectChains.size();
2808}
2809
2810status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002811 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002812{
2813 Mutex::Autolock _l(mLock);
2814 return attachAuxEffect_l(track, EffectId);
2815}
2816
2817status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002818 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002819{
2820 status_t status = NO_ERROR;
2821
2822 if (EffectId == 0) {
2823 track->setAuxBuffer(0, NULL);
2824 } else {
2825 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2826 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2827 if (effect != 0) {
2828 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2829 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2830 } else {
2831 status = INVALID_OPERATION;
2832 }
2833 } else {
2834 status = BAD_VALUE;
2835 }
2836 }
2837 return status;
2838}
2839
2840void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2841{
2842 for (size_t i = 0; i < mTracks.size(); ++i) {
2843 sp<Track> track = mTracks[i];
2844 if (track->auxEffectId() == effectId) {
2845 attachAuxEffect_l(track, 0);
2846 }
2847 }
2848}
2849
2850bool AudioFlinger::PlaybackThread::threadLoop()
2851{
2852 Vector< sp<Track> > tracksToRemove;
2853
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002854 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002855 nsecs_t lastWriteFinished = -1; // time last server write completed
2856 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002857
2858 // MIXER
2859 nsecs_t lastWarning = 0;
2860
2861 // DUPLICATING
2862 // FIXME could this be made local to while loop?
2863 writeFrames = 0;
2864
Eric Laurent9cab7462016-11-10 13:05:20 -08002865 int lastGeneration = 0;
2866
Eric Laurent81784c32012-11-19 14:55:58 -08002867 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002868 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002869
2870 if (mType == MIXER) {
2871 sleepTimeShift = 0;
2872 }
2873
2874 CpuStats cpuStats;
2875 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2876
2877 acquireWakeLock();
2878
Glenn Kasten9e58b552013-01-18 15:09:48 -08002879 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2880 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2881 // and then that string will be logged at the next convenient opportunity.
2882 const char *logString = NULL;
2883
Eric Laurent664539d2013-09-23 18:24:31 -07002884 checkSilentMode_l();
2885
Eric Laurent81784c32012-11-19 14:55:58 -08002886 while (!exitPending())
2887 {
2888 cpuStats.sample(myName);
2889
2890 Vector< sp<EffectChain> > effectChains;
2891
Eric Laurent81784c32012-11-19 14:55:58 -08002892 { // scope for mLock
2893
2894 Mutex::Autolock _l(mLock);
2895
Eric Laurent021cf962014-05-13 10:18:14 -07002896 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002897
Glenn Kasten9e58b552013-01-18 15:09:48 -08002898 if (logString != NULL) {
2899 mNBLogWriter->logTimestamp();
2900 mNBLogWriter->log(logString);
2901 logString = NULL;
2902 }
2903
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002904 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002905 // and associate with the sink frames written out. We need
2906 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002907 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002908 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002909 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002910 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002911 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002912 ExtendedTimestamp timestamp; // use private copy to fetch
2913 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002914
2915 // We keep track of the last valid kernel position in case we are in underrun
2916 // and the normal mixer period is the same as the fast mixer period, or there
2917 // is some error from the HAL.
2918 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2919 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2920 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2921 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2922 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2923
2924 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2925 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2926 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2927 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002928 }
2929
2930 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2931 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002932 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002933 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002934 }
2935
Andy Hung818e7a32016-02-16 18:08:07 -08002936 // copy over kernel info
2937 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07002938 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
2939 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08002940 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2941 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002942 }
2943 // mFramesWritten for non-offloaded tracks are contiguous
2944 // even after standby() is called. This is useful for the track frame
2945 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07002946 bool serverLocationUpdate = false;
2947 if (mFramesWritten != lastFramesWritten) {
2948 serverLocationUpdate = true;
2949 lastFramesWritten = mFramesWritten;
2950 }
2951 // Only update timestamps if there is a meaningful change.
2952 // Either the kernel timestamp must be valid or we have written something.
2953 if (kernelLocationUpdate || serverLocationUpdate) {
2954 if (serverLocationUpdate) {
2955 // use the time before we called the HAL write - it is a bit more accurate
2956 // to when the server last read data than the current time here.
2957 //
2958 // If we haven't written anything, mLastWriteTime will be -1
2959 // and we use systemTime().
2960 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2961 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
2962 ? systemTime() : mLastWriteTime;
2963 }
Eric Laurent9cab7462016-11-10 13:05:20 -08002964 const size_t size = mActiveTracks.size();
2965 for (size_t i = 0; i < size; ++i) {
2966 sp<Track> t = mActiveTracks[i].promote();
2967 if (t != 0 && !t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07002968 t->updateTrackFrameInfo(
2969 t->mAudioTrackServerProxy->framesReleased(),
2970 mFramesWritten,
2971 mTimestamp);
2972 }
Andy Hunge10393e2015-06-12 13:59:33 -07002973 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002974 }
2975
Eric Laurent81784c32012-11-19 14:55:58 -08002976 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002977 if (mSignalPending) {
2978 // A signal was raised while we were unlocked
2979 mSignalPending = false;
2980 } else if (waitingAsyncCallback_l()) {
2981 if (exitPending()) {
2982 break;
2983 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002984 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07002985 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07002986 releaseWakeLock_l();
2987 released = true;
Eric Laurent9cab7462016-11-10 13:05:20 -08002988 mWakeLockUids.clear();
2989 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07002990 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002991 ALOGV("wait async completion");
2992 mWaitWorkCV.wait(mLock);
2993 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002994 if (released) {
2995 acquireWakeLock_l();
2996 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002997 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2998 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002999
3000 continue;
3001 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003002 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003003 isSuspended()) {
3004 // put audio hardware into standby after short delay
3005 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003006
3007 threadLoop_standby();
3008
3009 mStandby = true;
3010 }
3011
3012 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3013 // we're about to wait, flush the binder command buffer
3014 IPCThreadState::self()->flushCommands();
3015
3016 clearOutputTracks();
3017
3018 if (exitPending()) {
3019 break;
3020 }
3021
3022 releaseWakeLock_l();
Eric Laurent9cab7462016-11-10 13:05:20 -08003023 mWakeLockUids.clear();
3024 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003025 // wait until we have something to do...
3026 ALOGV("%s going to sleep", myName.string());
3027 mWaitWorkCV.wait(mLock);
3028 ALOGV("%s waking up", myName.string());
3029 acquireWakeLock_l();
3030
3031 mMixerStatus = MIXER_IDLE;
3032 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3033 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003034 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003035 checkSilentMode_l();
3036
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003037 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3038 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003039 if (mType == MIXER) {
3040 sleepTimeShift = 0;
3041 }
3042
3043 continue;
3044 }
3045 }
Eric Laurent81784c32012-11-19 14:55:58 -08003046 // mMixerStatusIgnoringFastTracks is also updated internally
3047 mMixerStatus = prepareTracks_l(&tracksToRemove);
3048
Eric Laurent9cab7462016-11-10 13:05:20 -08003049 // compare with previously applied list
3050 if (lastGeneration != mActiveTracksGeneration) {
3051 // update wakelock
3052 updateWakeLockUids_l(mWakeLockUids);
3053 lastGeneration = mActiveTracksGeneration;
3054 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003055
Eric Laurent81784c32012-11-19 14:55:58 -08003056 // prevent any changes in effect chain list and in each effect chain
3057 // during mixing and effect process as the audio buffers could be deleted
3058 // or modified if an effect is created or deleted
3059 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003060 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003061
Eric Laurentbfb1b832013-01-07 09:53:42 -08003062 if (mBytesRemaining == 0) {
3063 mCurrentWriteLength = 0;
3064 if (mMixerStatus == MIXER_TRACKS_READY) {
3065 // threadLoop_mix() sets mCurrentWriteLength
3066 threadLoop_mix();
3067 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3068 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003069 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003070 // must be written to HAL
3071 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003072 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003073 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003074 }
3075 }
Andy Hung98ef9782014-03-04 14:46:50 -08003076 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003077 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003078 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3079 // or mSinkBuffer (if there are no effects).
3080 //
3081 // This is done pre-effects computation; if effects change to
3082 // support higher precision, this needs to move.
3083 //
3084 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003085 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003086 if (mMixerBufferValid) {
3087 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3088 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3089
Andy Hung2ddee192015-12-18 17:34:44 -08003090 // mono blend occurs for mixer threads only (not direct or offloaded)
3091 // and is handled here if we're going directly to the sink.
3092 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003093 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3094 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003095 }
3096
Andy Hung98ef9782014-03-04 14:46:50 -08003097 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3098 mNormalFrameCount * mChannelCount);
3099 }
3100
Eric Laurentbfb1b832013-01-07 09:53:42 -08003101 mBytesRemaining = mCurrentWriteLength;
3102 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003103 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3104 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3105 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3106 mBytesWritten += mBytesRemaining;
3107 mFramesWritten += framesRemaining;
3108 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003109 mBytesRemaining = 0;
3110 }
Eric Laurent81784c32012-11-19 14:55:58 -08003111
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003113 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003114 for (size_t i = 0; i < effectChains.size(); i ++) {
3115 effectChains[i]->process_l();
3116 }
Eric Laurent81784c32012-11-19 14:55:58 -08003117 }
3118 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003119 // Process effect chains for offloaded thread even if no audio
3120 // was read from audio track: process only updates effect state
3121 // and thus does have to be synchronized with audio writes but may have
3122 // to be called while waiting for async write callback
3123 if (mType == OFFLOAD) {
3124 for (size_t i = 0; i < effectChains.size(); i ++) {
3125 effectChains[i]->process_l();
3126 }
3127 }
Eric Laurent81784c32012-11-19 14:55:58 -08003128
Andy Hung98ef9782014-03-04 14:46:50 -08003129 // Only if the Effects buffer is enabled and there is data in the
3130 // Effects buffer (buffer valid), we need to
3131 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003132 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003133 if (mEffectBufferValid) {
3134 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003135
3136 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003137 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3138 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003139 }
3140
Andy Hung98ef9782014-03-04 14:46:50 -08003141 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3142 mNormalFrameCount * mChannelCount);
3143 }
3144
Eric Laurent81784c32012-11-19 14:55:58 -08003145 // enable changes in effect chain
3146 unlockEffectChains(effectChains);
3147
Eric Laurentbfb1b832013-01-07 09:53:42 -08003148 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003149 // mSleepTimeUs == 0 means we must write to audio hardware
3150 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003151 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003152 // We save lastWriteFinished here, as previousLastWriteFinished,
3153 // for throttling. On thread start, previousLastWriteFinished will be
3154 // set to -1, which properly results in no throttling after the first write.
3155 nsecs_t previousLastWriteFinished = lastWriteFinished;
3156 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003157 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003158 // FIXME rewrite to reduce number of system calls
3159 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003160 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003161 lastWriteFinished = systemTime();
3162 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003163 if (ret < 0) {
3164 mBytesRemaining = 0;
3165 } else {
3166 mBytesWritten += ret;
3167 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003168 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169 }
3170 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3171 (mMixerStatus == MIXER_DRAIN_ALL)) {
3172 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003173 }
Andy Hung08fb1742015-05-31 23:22:10 -07003174 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003175 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003176 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003177 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003178 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003179 ATRACE_NAME("underrun");
3180 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003181 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003182 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003183 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003184 }
Andy Hung08fb1742015-05-31 23:22:10 -07003185
3186 if (mThreadThrottle
3187 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3188 && ret > 0) { // we wrote something
3189 // Limit MixerThread data processing to no more than twice the
3190 // expected processing rate.
3191 //
3192 // This helps prevent underruns with NuPlayer and other applications
3193 // which may set up buffers that are close to the minimum size, or use
3194 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3195 //
3196 // The throttle smooths out sudden large data drains from the device,
3197 // e.g. when it comes out of standby, which often causes problems with
3198 // (1) mixer threads without a fast mixer (which has its own warm-up)
3199 // (2) minimum buffer sized tracks (even if the track is full,
3200 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003201 //
3202 // Total time spent in last processing cycle equals time spent in
3203 // 1. threadLoop_write, as well as time spent in
3204 // 2. threadLoop_mix (significant for heavy mixing, especially
3205 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003206
Andy Hung69488c42016-05-16 18:43:33 -07003207 // it's OK if deltaMs is an overestimate.
3208 const int32_t deltaMs =
3209 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003210 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3211 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3212 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003213 // notify of throttle start on verbose log
3214 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3215 "mixer(%p) throttle begin:"
3216 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003217 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003218 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003219 // Throttle must be attributed to the previous mixer loop's write time
3220 // to allow back-to-back throttling.
3221 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003222 } else {
3223 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3224 if (diff > 0) {
3225 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003226 // but prevent spamming for bluetooth
3227 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3228 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003229 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3230 }
Andy Hung08fb1742015-05-31 23:22:10 -07003231 }
3232 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003233 }
Eric Laurent81784c32012-11-19 14:55:58 -08003234
Eric Laurentbfb1b832013-01-07 09:53:42 -08003235 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003236 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003237 Mutex::Autolock _l(mLock);
3238 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3239 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003240 }
Glenn Kastene7754022014-10-31 12:11:26 -07003241 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003242 }
Eric Laurent81784c32012-11-19 14:55:58 -08003243 }
3244
3245 // Finally let go of removed track(s), without the lock held
3246 // since we can't guarantee the destructors won't acquire that
3247 // same lock. This will also mutate and push a new fast mixer state.
3248 threadLoop_removeTracks(tracksToRemove);
3249 tracksToRemove.clear();
3250
3251 // FIXME I don't understand the need for this here;
3252 // it was in the original code but maybe the
3253 // assignment in saveOutputTracks() makes this unnecessary?
3254 clearOutputTracks();
3255
3256 // Effect chains will be actually deleted here if they were removed from
3257 // mEffectChains list during mixing or effects processing
3258 effectChains.clear();
3259
3260 // FIXME Note that the above .clear() is no longer necessary since effectChains
3261 // is now local to this block, but will keep it for now (at least until merge done).
3262 }
3263
Eric Laurentbfb1b832013-01-07 09:53:42 -08003264 threadLoop_exit();
3265
Eric Laurentcf817a22014-08-04 20:36:31 -07003266 if (!mStandby) {
3267 threadLoop_standby();
3268 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003269 }
3270
3271 releaseWakeLock();
Eric Laurent9cab7462016-11-10 13:05:20 -08003272 mWakeLockUids.clear();
3273 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003274
3275 ALOGV("Thread %p type %d exiting", this, mType);
3276 return false;
3277}
3278
Eric Laurentbfb1b832013-01-07 09:53:42 -08003279// removeTracks_l() must be called with ThreadBase::mLock held
3280void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3281{
3282 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003283 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003284 for (size_t i=0 ; i<count ; i++) {
3285 const sp<Track>& track = tracksToRemove.itemAt(i);
3286 mActiveTracks.remove(track);
Eric Laurent9cab7462016-11-10 13:05:20 -08003287 mWakeLockUids.remove(track->uid());
3288 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003289 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3290 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3291 if (chain != 0) {
3292 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3293 track->sessionId());
3294 chain->decActiveTrackCnt();
3295 }
3296 if (track->isTerminated()) {
3297 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003298 } else { // inactive but not terminated
3299 char buffer[256];
3300 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3301 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003302 }
3303 }
3304 }
3305
3306}
Eric Laurent81784c32012-11-19 14:55:58 -08003307
Eric Laurentaccc1472013-09-20 09:36:34 -07003308status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3309{
3310 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003311 ExtendedTimestamp ets;
3312 status_t status = mNormalSink->getTimestamp(ets);
3313 if (status == NO_ERROR) {
3314 status = ets.getBestTimestamp(&timestamp);
3315 }
3316 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003317 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003318 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003319 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003320 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003321 timestamp.mPosition = (uint32_t)position64;
3322 return NO_ERROR;
3323 }
3324 }
3325 return INVALID_OPERATION;
3326}
Eric Laurent1c333e22014-05-20 10:48:17 -07003327
Eric Laurent054d9d32015-04-24 08:48:48 -07003328status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3329 audio_patch_handle_t *handle)
3330{
Andy Hungf60abce2016-08-26 11:37:54 -07003331 status_t status;
3332 if (property_get_bool("af.patch_park", false /* default_value */)) {
3333 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3334 // or if HAL does not properly lock against access.
3335 AutoPark<FastMixer> park(mFastMixer);
3336 status = PlaybackThread::createAudioPatch_l(patch, handle);
3337 } else {
3338 status = PlaybackThread::createAudioPatch_l(patch, handle);
3339 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003340 return status;
3341}
3342
Eric Laurent1c333e22014-05-20 10:48:17 -07003343status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3344 audio_patch_handle_t *handle)
3345{
3346 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003347
3348 // store new device and send to effects
3349 audio_devices_t type = AUDIO_DEVICE_NONE;
3350 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3351 type |= patch->sinks[i].ext.device.type;
3352 }
3353
3354#ifdef ADD_BATTERY_DATA
3355 // when changing the audio output device, call addBatteryData to notify
3356 // the change
3357 if (mOutDevice != type) {
3358 uint32_t params = 0;
3359 // check whether speaker is on
3360 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3361 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003362 }
3363
Eric Laurent054d9d32015-04-24 08:48:48 -07003364 audio_devices_t deviceWithoutSpeaker
3365 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3366 // check if any other device (except speaker) is on
3367 if (type & deviceWithoutSpeaker) {
3368 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3369 }
3370
3371 if (params != 0) {
3372 addBatteryData(params);
3373 }
3374 }
3375#endif
3376
3377 for (size_t i = 0; i < mEffectChains.size(); i++) {
3378 mEffectChains[i]->setDevice_l(type);
3379 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003380
3381 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3382 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3383 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003384 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003385 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003386
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003387 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003388 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3389 status = hwDevice->createAudioPatch(patch->num_sources,
3390 patch->sources,
3391 patch->num_sinks,
3392 patch->sinks,
3393 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003394 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003395 char *address;
3396 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3397 //FIXME: we only support address on first sink with HAL version < 3.0
3398 address = audio_device_address_to_parameter(
3399 patch->sinks[0].ext.device.type,
3400 patch->sinks[0].ext.device.address);
3401 } else {
3402 address = (char *)calloc(1, 1);
3403 }
3404 AudioParameter param = AudioParameter(String8(address));
3405 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003406 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003407 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003408 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003409 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003410 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003411 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003412 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3413 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003414 return status;
3415}
3416
Eric Laurent054d9d32015-04-24 08:48:48 -07003417status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3418{
Andy Hungf60abce2016-08-26 11:37:54 -07003419 status_t status;
3420 if (property_get_bool("af.patch_park", false /* default_value */)) {
3421 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3422 // or if HAL does not properly lock against access.
3423 AutoPark<FastMixer> park(mFastMixer);
3424 status = PlaybackThread::releaseAudioPatch_l(handle);
3425 } else {
3426 status = PlaybackThread::releaseAudioPatch_l(handle);
3427 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003428 return status;
3429}
3430
Eric Laurent1c333e22014-05-20 10:48:17 -07003431status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3432{
3433 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003434
3435 mOutDevice = AUDIO_DEVICE_NONE;
3436
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003437 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003438 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3439 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003440 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003441 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003442 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003443 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003444 }
3445 return status;
3446}
3447
Eric Laurent83b88082014-06-20 18:31:16 -07003448void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3449{
3450 Mutex::Autolock _l(mLock);
3451 mTracks.add(track);
3452}
3453
3454void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3455{
3456 Mutex::Autolock _l(mLock);
3457 destroyTrack_l(track);
3458}
3459
3460void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3461{
3462 ThreadBase::getAudioPortConfig(config);
3463 config->role = AUDIO_PORT_ROLE_SOURCE;
3464 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3465 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3466}
3467
Eric Laurent81784c32012-11-19 14:55:58 -08003468// ----------------------------------------------------------------------------
3469
3470AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003471 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3472 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003473 // mAudioMixer below
3474 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003475 mFastMixerFutex(0),
3476 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003477 // mOutputSink below
3478 // mPipeSink below
3479 // mNormalSink below
3480{
3481 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003482 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3483 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003484 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3485 mNormalFrameCount);
3486 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3487
Andy Hungfbfc3952015-01-15 13:33:51 -08003488 if (type == DUPLICATING) {
3489 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3490 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3491 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3492 return;
3493 }
Eric Laurent81784c32012-11-19 14:55:58 -08003494 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003495 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003496 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003497 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003498#if !LOG_NDEBUG
3499 ssize_t index =
3500#else
3501 (void)
3502#endif
3503 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003504 ALOG_ASSERT(index == 0);
3505
3506 // initialize fast mixer depending on configuration
3507 bool initFastMixer;
3508 switch (kUseFastMixer) {
3509 case FastMixer_Never:
3510 initFastMixer = false;
3511 break;
3512 case FastMixer_Always:
3513 initFastMixer = true;
3514 break;
3515 case FastMixer_Static:
3516 case FastMixer_Dynamic:
3517 initFastMixer = mFrameCount < mNormalFrameCount;
3518 break;
3519 }
3520 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003521 audio_format_t fastMixerFormat;
3522 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3523 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3524 } else {
3525 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3526 }
3527 if (mFormat != fastMixerFormat) {
3528 // change our Sink format to accept our intermediate precision
3529 mFormat = fastMixerFormat;
3530 free(mSinkBuffer);
3531 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3532 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3533 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3534 }
Eric Laurent81784c32012-11-19 14:55:58 -08003535
3536 // create a MonoPipe to connect our submix to FastMixer
3537 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003538#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003539 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003540#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003541 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003542 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003543 format.mFormat = fastMixerFormat;
3544 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3545
Eric Laurent81784c32012-11-19 14:55:58 -08003546 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3547 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3548 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3549 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3550 const NBAIO_Format offers[1] = {format};
3551 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003552#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003553 ssize_t index =
3554#else
3555 (void)
3556#endif
3557 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003558 ALOG_ASSERT(index == 0);
3559 monoPipe->setAvgFrames((mScreenState & 1) ?
3560 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3561 mPipeSink = monoPipe;
3562
Glenn Kasten46909e72013-02-26 09:20:22 -08003563#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003564 if (mTeeSinkOutputEnabled) {
3565 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003566 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3567 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003568 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003569 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003570 ALOG_ASSERT(index == 0);
3571 mTeeSink = teeSink;
3572 PipeReader *teeSource = new PipeReader(*teeSink);
3573 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003574 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003575 ALOG_ASSERT(index == 0);
3576 mTeeSource = teeSource;
3577 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003578#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003579
3580 // create fast mixer and configure it initially with just one fast track for our submix
3581 mFastMixer = new FastMixer();
3582 FastMixerStateQueue *sq = mFastMixer->sq();
3583#ifdef STATE_QUEUE_DUMP
3584 sq->setObserverDump(&mStateQueueObserverDump);
3585 sq->setMutatorDump(&mStateQueueMutatorDump);
3586#endif
3587 FastMixerState *state = sq->begin();
3588 FastTrack *fastTrack = &state->mFastTracks[0];
3589 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3590 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3591 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003592 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3593 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003594 fastTrack->mGeneration++;
3595 state->mFastTracksGen++;
3596 state->mTrackMask = 1;
3597 // fast mixer will use the HAL output sink
3598 state->mOutputSink = mOutputSink.get();
3599 state->mOutputSinkGen++;
3600 state->mFrameCount = mFrameCount;
3601 state->mCommand = FastMixerState::COLD_IDLE;
3602 // already done in constructor initialization list
3603 //mFastMixerFutex = 0;
3604 state->mColdFutexAddr = &mFastMixerFutex;
3605 state->mColdGen++;
3606 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003607#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003608 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003609#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003610 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3611 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003612 sq->end();
3613 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3614
3615 // start the fast mixer
3616 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3617 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003618 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003619
3620#ifdef AUDIO_WATCHDOG
3621 // create and start the watchdog
3622 mAudioWatchdog = new AudioWatchdog();
3623 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3624 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3625 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003626 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003627#endif
3628
Eric Laurent81784c32012-11-19 14:55:58 -08003629 }
3630
3631 switch (kUseFastMixer) {
3632 case FastMixer_Never:
3633 case FastMixer_Dynamic:
3634 mNormalSink = mOutputSink;
3635 break;
3636 case FastMixer_Always:
3637 mNormalSink = mPipeSink;
3638 break;
3639 case FastMixer_Static:
3640 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3641 break;
3642 }
3643}
3644
3645AudioFlinger::MixerThread::~MixerThread()
3646{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003647 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003648 FastMixerStateQueue *sq = mFastMixer->sq();
3649 FastMixerState *state = sq->begin();
3650 if (state->mCommand == FastMixerState::COLD_IDLE) {
3651 int32_t old = android_atomic_inc(&mFastMixerFutex);
3652 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003653 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003654 }
3655 }
3656 state->mCommand = FastMixerState::EXIT;
3657 sq->end();
3658 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3659 mFastMixer->join();
3660 // Though the fast mixer thread has exited, it's state queue is still valid.
3661 // We'll use that extract the final state which contains one remaining fast track
3662 // corresponding to our sub-mix.
3663 state = sq->begin();
3664 ALOG_ASSERT(state->mTrackMask == 1);
3665 FastTrack *fastTrack = &state->mFastTracks[0];
3666 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3667 delete fastTrack->mBufferProvider;
3668 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003669 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003670#ifdef AUDIO_WATCHDOG
3671 if (mAudioWatchdog != 0) {
3672 mAudioWatchdog->requestExit();
3673 mAudioWatchdog->requestExitAndWait();
3674 mAudioWatchdog.clear();
3675 }
3676#endif
3677 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003678 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003679 delete mAudioMixer;
3680}
3681
3682
3683uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3684{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003685 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003686 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3687 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3688 }
3689 return latency;
3690}
3691
3692
3693void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3694{
3695 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3696}
3697
Eric Laurentbfb1b832013-01-07 09:53:42 -08003698ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003699{
3700 // FIXME we should only do one push per cycle; confirm this is true
3701 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003702 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003703 FastMixerStateQueue *sq = mFastMixer->sq();
3704 FastMixerState *state = sq->begin();
3705 if (state->mCommand != FastMixerState::MIX_WRITE &&
3706 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3707 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003708
3709 // FIXME workaround for first HAL write being CPU bound on some devices
3710 ATRACE_BEGIN("write");
3711 mOutput->write((char *)mSinkBuffer, 0);
3712 ATRACE_END();
3713
Eric Laurent81784c32012-11-19 14:55:58 -08003714 int32_t old = android_atomic_inc(&mFastMixerFutex);
3715 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003716 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003717 }
3718#ifdef AUDIO_WATCHDOG
3719 if (mAudioWatchdog != 0) {
3720 mAudioWatchdog->resume();
3721 }
3722#endif
3723 }
3724 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003725#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003726 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003727 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003728#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003729 sq->end();
3730 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3731 if (kUseFastMixer == FastMixer_Dynamic) {
3732 mNormalSink = mPipeSink;
3733 }
3734 } else {
3735 sq->end(false /*didModify*/);
3736 }
3737 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003738 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003739}
3740
3741void AudioFlinger::MixerThread::threadLoop_standby()
3742{
3743 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003744 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003745 FastMixerStateQueue *sq = mFastMixer->sq();
3746 FastMixerState *state = sq->begin();
3747 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003748 // Report any frames trapped in the Monopipe
3749 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3750 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3751 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3752 "monoPipeWritten:%lld monoPipeLeft:%lld",
3753 (long long)mFramesWritten, (long long)mSuspendedFrames,
3754 (long long)mPipeSink->framesWritten(), pipeFrames);
3755 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3756
Eric Laurent81784c32012-11-19 14:55:58 -08003757 state->mCommand = FastMixerState::COLD_IDLE;
3758 state->mColdFutexAddr = &mFastMixerFutex;
3759 state->mColdGen++;
3760 mFastMixerFutex = 0;
3761 sq->end();
3762 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3763 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3764 if (kUseFastMixer == FastMixer_Dynamic) {
3765 mNormalSink = mOutputSink;
3766 }
3767#ifdef AUDIO_WATCHDOG
3768 if (mAudioWatchdog != 0) {
3769 mAudioWatchdog->pause();
3770 }
3771#endif
3772 } else {
3773 sq->end(false /*didModify*/);
3774 }
3775 }
3776 PlaybackThread::threadLoop_standby();
3777}
3778
Eric Laurentbfb1b832013-01-07 09:53:42 -08003779bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3780{
3781 return false;
3782}
3783
3784bool AudioFlinger::PlaybackThread::shouldStandby_l()
3785{
3786 return !mStandby;
3787}
3788
3789bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3790{
3791 Mutex::Autolock _l(mLock);
3792 return waitingAsyncCallback_l();
3793}
3794
Eric Laurent81784c32012-11-19 14:55:58 -08003795// shared by MIXER and DIRECT, overridden by DUPLICATING
3796void AudioFlinger::PlaybackThread::threadLoop_standby()
3797{
3798 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003799 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003800 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003801 // discard any pending drain or write ack by incrementing sequence
3802 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3803 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003804 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003805 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3806 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003807 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003808 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003809}
3810
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003811void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3812{
3813 ALOGV("signal playback thread");
3814 broadcast_l();
3815}
3816
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003817void AudioFlinger::PlaybackThread::onAsyncError()
3818{
3819 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3820 invalidateTracks((audio_stream_type_t)i);
3821 }
3822}
3823
Eric Laurent81784c32012-11-19 14:55:58 -08003824void AudioFlinger::MixerThread::threadLoop_mix()
3825{
Eric Laurent81784c32012-11-19 14:55:58 -08003826 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003827 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003828 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003829 // increase sleep time progressively when application underrun condition clears.
3830 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3831 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3832 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003833 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003834 sleepTimeShift--;
3835 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003836 mSleepTimeUs = 0;
3837 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003838 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003839
Eric Laurent81784c32012-11-19 14:55:58 -08003840}
3841
3842void AudioFlinger::MixerThread::threadLoop_sleepTime()
3843{
3844 // If no tracks are ready, sleep once for the duration of an output
3845 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003846 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003847 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003848 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3849 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3850 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003851 }
3852 // reduce sleep time in case of consecutive application underruns to avoid
3853 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3854 // duration we would end up writing less data than needed by the audio HAL if
3855 // the condition persists.
3856 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3857 sleepTimeShift++;
3858 }
3859 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003860 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003861 }
3862 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003863 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3864 // before effects processing or output.
3865 if (mMixerBufferValid) {
3866 memset(mMixerBuffer, 0, mMixerBufferSize);
3867 } else {
3868 memset(mSinkBuffer, 0, mSinkBufferSize);
3869 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003870 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003871 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3872 "anticipated start");
3873 }
3874 // TODO add standby time extension fct of effect tail
3875}
3876
3877// prepareTracks_l() must be called with ThreadBase::mLock held
3878AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3879 Vector< sp<Track> > *tracksToRemove)
3880{
3881
3882 mixer_state mixerStatus = MIXER_IDLE;
3883 // find out which tracks need to be processed
3884 size_t count = mActiveTracks.size();
3885 size_t mixedTracks = 0;
3886 size_t tracksWithEffect = 0;
3887 // counts only _active_ fast tracks
3888 size_t fastTracks = 0;
3889 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3890
3891 float masterVolume = mMasterVolume;
3892 bool masterMute = mMasterMute;
3893
3894 if (masterMute) {
3895 masterVolume = 0;
3896 }
3897 // Delegate master volume control to effect in output mix effect chain if needed
3898 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3899 if (chain != 0) {
3900 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3901 chain->setVolume_l(&v, &v);
3902 masterVolume = (float)((v + (1 << 23)) >> 24);
3903 chain.clear();
3904 }
3905
3906 // prepare a new state to push
3907 FastMixerStateQueue *sq = NULL;
3908 FastMixerState *state = NULL;
3909 bool didModify = false;
3910 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003911 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003912 sq = mFastMixer->sq();
3913 state = sq->begin();
3914 }
3915
Andy Hung69aed5f2014-02-25 17:24:40 -08003916 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003917 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003918
Eric Laurent81784c32012-11-19 14:55:58 -08003919 for (size_t i=0 ; i<count ; i++) {
Eric Laurent9cab7462016-11-10 13:05:20 -08003920 const sp<Track> t = mActiveTracks[i].promote();
3921 if (t == 0) {
3922 continue;
3923 }
Eric Laurent81784c32012-11-19 14:55:58 -08003924
3925 // this const just means the local variable doesn't change
3926 Track* const track = t.get();
3927
3928 // process fast tracks
3929 if (track->isFastTrack()) {
3930
3931 // It's theoretically possible (though unlikely) for a fast track to be created
3932 // and then removed within the same normal mix cycle. This is not a problem, as
3933 // the track never becomes active so it's fast mixer slot is never touched.
3934 // The converse, of removing an (active) track and then creating a new track
3935 // at the identical fast mixer slot within the same normal mix cycle,
3936 // is impossible because the slot isn't marked available until the end of each cycle.
3937 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003938 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003939 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3940 FastTrack *fastTrack = &state->mFastTracks[j];
3941
3942 // Determine whether the track is currently in underrun condition,
3943 // and whether it had a recent underrun.
3944 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3945 FastTrackUnderruns underruns = ftDump->mUnderruns;
3946 uint32_t recentFull = (underruns.mBitFields.mFull -
3947 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3948 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3949 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3950 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3951 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3952 uint32_t recentUnderruns = recentPartial + recentEmpty;
3953 track->mObservedUnderruns = underruns;
3954 // don't count underruns that occur while stopping or pausing
3955 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003956 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3957 recentUnderruns > 0) {
3958 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3959 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003960 } else {
3961 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003962 }
3963
3964 // This is similar to the state machine for normal tracks,
3965 // with a few modifications for fast tracks.
3966 bool isActive = true;
3967 switch (track->mState) {
3968 case TrackBase::STOPPING_1:
3969 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003970 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003971 track->mState = TrackBase::STOPPING_2;
3972 }
3973 break;
3974 case TrackBase::PAUSING:
3975 // ramp down is not yet implemented
3976 track->setPaused();
3977 break;
3978 case TrackBase::RESUMING:
3979 // ramp up is not yet implemented
3980 track->mState = TrackBase::ACTIVE;
3981 break;
3982 case TrackBase::ACTIVE:
3983 if (recentFull > 0 || recentPartial > 0) {
3984 // track has provided at least some frames recently: reset retry count
3985 track->mRetryCount = kMaxTrackRetries;
3986 }
3987 if (recentUnderruns == 0) {
3988 // no recent underruns: stay active
3989 break;
3990 }
3991 // there has recently been an underrun of some kind
3992 if (track->sharedBuffer() == 0) {
3993 // were any of the recent underruns "empty" (no frames available)?
3994 if (recentEmpty == 0) {
3995 // no, then ignore the partial underruns as they are allowed indefinitely
3996 break;
3997 }
3998 // there has recently been an "empty" underrun: decrement the retry counter
3999 if (--(track->mRetryCount) > 0) {
4000 break;
4001 }
4002 // indicate to client process that the track was disabled because of underrun;
4003 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004004 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004005 // remove from active list, but state remains ACTIVE [confusing but true]
4006 isActive = false;
4007 break;
4008 }
4009 // fall through
4010 case TrackBase::STOPPING_2:
4011 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004012 case TrackBase::STOPPED:
4013 case TrackBase::FLUSHED: // flush() while active
4014 // Check for presentation complete if track is inactive
4015 // We have consumed all the buffers of this track.
4016 // This would be incomplete if we auto-paused on underrun
4017 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004018 uint32_t latency = 0;
4019 status_t result = mOutput->stream->getLatency(&latency);
4020 ALOGE_IF(result != OK,
4021 "Error when retrieving output stream latency: %d", result);
4022 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004023 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004024 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4025 // track stays in active list until presentation is complete
4026 break;
4027 }
4028 }
4029 if (track->isStopping_2()) {
4030 track->mState = TrackBase::STOPPED;
4031 }
4032 if (track->isStopped()) {
4033 // Can't reset directly, as fast mixer is still polling this track
4034 // track->reset();
4035 // So instead mark this track as needing to be reset after push with ack
4036 resetMask |= 1 << i;
4037 }
4038 isActive = false;
4039 break;
4040 case TrackBase::IDLE:
4041 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004042 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004043 }
4044
4045 if (isActive) {
4046 // was it previously inactive?
4047 if (!(state->mTrackMask & (1 << j))) {
4048 ExtendedAudioBufferProvider *eabp = track;
4049 VolumeProvider *vp = track;
4050 fastTrack->mBufferProvider = eabp;
4051 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004052 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004053 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004054 fastTrack->mGeneration++;
4055 state->mTrackMask |= 1 << j;
4056 didModify = true;
4057 // no acknowledgement required for newly active tracks
4058 }
4059 // cache the combined master volume and stream type volume for fast mixer; this
4060 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004061 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004062 ++fastTracks;
4063 } else {
4064 // was it previously active?
4065 if (state->mTrackMask & (1 << j)) {
4066 fastTrack->mBufferProvider = NULL;
4067 fastTrack->mGeneration++;
4068 state->mTrackMask &= ~(1 << j);
4069 didModify = true;
4070 // If any fast tracks were removed, we must wait for acknowledgement
4071 // because we're about to decrement the last sp<> on those tracks.
4072 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4073 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004074 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4075 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4076 j, track->mState, state->mTrackMask, recentUnderruns,
4077 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004078 }
4079 tracksToRemove->add(track);
4080 // Avoids a misleading display in dumpsys
4081 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4082 }
4083 continue;
4084 }
4085
4086 { // local variable scope to avoid goto warning
4087
4088 audio_track_cblk_t* cblk = track->cblk();
4089
4090 // The first time a track is added we wait
4091 // for all its buffers to be filled before processing it
4092 int name = track->name();
4093 // make sure that we have enough frames to mix one full buffer.
4094 // enforce this condition only once to enable draining the buffer in case the client
4095 // app does not call stop() and relies on underrun to stop:
4096 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4097 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004098 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004099 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004100 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004101
4102 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004103 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004104 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4105 // add frames already consumed but not yet released by the resampler
4106 // because mAudioTrackServerProxy->framesReady() will include these frames
4107 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4108
Eric Laurent81784c32012-11-19 14:55:58 -08004109 uint32_t minFrames = 1;
4110 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4111 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004112 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004113 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004114
4115 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004116 if (ATRACE_ENABLED()) {
4117 // I wish we had formatted trace names
4118 char traceName[16];
4119 strcpy(traceName, "nRdy");
4120 int name = track->name();
4121 if (AudioMixer::TRACK0 <= name &&
4122 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4123 name -= AudioMixer::TRACK0;
4124 traceName[4] = (name / 10) + '0';
4125 traceName[5] = (name % 10) + '0';
4126 } else {
4127 traceName[4] = '?';
4128 traceName[5] = '?';
4129 }
4130 traceName[6] = '\0';
4131 ATRACE_INT(traceName, framesReady);
4132 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004133 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004134 !track->isPaused() && !track->isTerminated())
4135 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004136 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004137
4138 mixedTracks++;
4139
Andy Hung69aed5f2014-02-25 17:24:40 -08004140 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4141 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004142 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004143 if (track->mainBuffer() != mSinkBuffer &&
4144 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004145 if (mEffectBufferEnabled) {
4146 mEffectBufferValid = true; // Later can set directly.
4147 }
Eric Laurent81784c32012-11-19 14:55:58 -08004148 chain = getEffectChain_l(track->sessionId());
4149 // Delegate volume control to effect in track effect chain if needed
4150 if (chain != 0) {
4151 tracksWithEffect++;
4152 } else {
4153 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4154 "session %d",
4155 name, track->sessionId());
4156 }
4157 }
4158
4159
4160 int param = AudioMixer::VOLUME;
4161 if (track->mFillingUpStatus == Track::FS_FILLED) {
4162 // no ramp for the first volume setting
4163 track->mFillingUpStatus = Track::FS_ACTIVE;
4164 if (track->mState == TrackBase::RESUMING) {
4165 track->mState = TrackBase::ACTIVE;
4166 param = AudioMixer::RAMP_VOLUME;
4167 }
4168 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004169 // FIXME should not make a decision based on mServer
4170 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004171 // If the track is stopped before the first frame was mixed,
4172 // do not apply ramp
4173 param = AudioMixer::RAMP_VOLUME;
4174 }
4175
4176 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004177 uint32_t vl, vr; // in U8.24 integer format
4178 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004179 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004180 vl = vr = 0;
4181 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004182 if (track->isPausing()) {
4183 track->setPaused();
4184 }
4185 } else {
4186
4187 // read original volumes with volume control
4188 float typeVolume = mStreamTypes[track->streamType()].volume;
4189 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004190 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004191 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004192 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4193 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004194 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004195 if (vlf > GAIN_FLOAT_UNITY) {
4196 ALOGV("Track left volume out of range: %.3g", vlf);
4197 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004198 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004199 if (vrf > GAIN_FLOAT_UNITY) {
4200 ALOGV("Track right volume out of range: %.3g", vrf);
4201 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004202 }
4203 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004204 vlf *= v;
4205 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004206 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004207 // then derive vl and vr as U8.24 versions for the effect chain
4208 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4209 vl = (uint32_t) (scaleto8_24 * vlf);
4210 vr = (uint32_t) (scaleto8_24 * vrf);
4211 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004212 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004213 // send level comes from shared memory and so may be corrupt
4214 if (sendLevel > MAX_GAIN_INT) {
4215 ALOGV("Track send level out of range: %04X", sendLevel);
4216 sendLevel = MAX_GAIN_INT;
4217 }
Andy Hung6be49402014-05-30 10:42:03 -07004218 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4219 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004220 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004221
Eric Laurent81784c32012-11-19 14:55:58 -08004222 // Delegate volume control to effect in track effect chain if needed
4223 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4224 // Do not ramp volume if volume is controlled by effect
4225 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004226 // Update remaining floating point volume levels
4227 vlf = (float)vl / (1 << 24);
4228 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004229 track->mHasVolumeController = true;
4230 } else {
4231 // force no volume ramp when volume controller was just disabled or removed
4232 // from effect chain to avoid volume spike
4233 if (track->mHasVolumeController) {
4234 param = AudioMixer::VOLUME;
4235 }
4236 track->mHasVolumeController = false;
4237 }
4238
Eric Laurent81784c32012-11-19 14:55:58 -08004239 // XXX: these things DON'T need to be done each time
4240 mAudioMixer->setBufferProvider(name, track);
4241 mAudioMixer->enable(name);
4242
Andy Hung6be49402014-05-30 10:42:03 -07004243 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4244 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4245 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004246 mAudioMixer->setParameter(
4247 name,
4248 AudioMixer::TRACK,
4249 AudioMixer::FORMAT, (void *)track->format());
4250 mAudioMixer->setParameter(
4251 name,
4252 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004253 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004254 mAudioMixer->setParameter(
4255 name,
4256 AudioMixer::TRACK,
4257 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004258 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004259 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004260 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004261 if (reqSampleRate == 0) {
4262 reqSampleRate = mSampleRate;
4263 } else if (reqSampleRate > maxSampleRate) {
4264 reqSampleRate = maxSampleRate;
4265 }
Eric Laurent81784c32012-11-19 14:55:58 -08004266 mAudioMixer->setParameter(
4267 name,
4268 AudioMixer::RESAMPLE,
4269 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004270 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004271
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004272 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004273 mAudioMixer->setParameter(
4274 name,
4275 AudioMixer::TIMESTRETCH,
4276 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004277 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004278
Andy Hung69aed5f2014-02-25 17:24:40 -08004279 /*
4280 * Select the appropriate output buffer for the track.
4281 *
Andy Hung98ef9782014-03-04 14:46:50 -08004282 * Tracks with effects go into their own effects chain buffer
4283 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004284 *
4285 * Other tracks can use mMixerBuffer for higher precision
4286 * channel accumulation. If this buffer is enabled
4287 * (mMixerBufferEnabled true), then selected tracks will accumulate
4288 * into it.
4289 *
4290 */
4291 if (mMixerBufferEnabled
4292 && (track->mainBuffer() == mSinkBuffer
4293 || track->mainBuffer() == mMixerBuffer)) {
4294 mAudioMixer->setParameter(
4295 name,
4296 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004297 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004298 mAudioMixer->setParameter(
4299 name,
4300 AudioMixer::TRACK,
4301 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4302 // TODO: override track->mainBuffer()?
4303 mMixerBufferValid = true;
4304 } else {
4305 mAudioMixer->setParameter(
4306 name,
4307 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004308 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004309 mAudioMixer->setParameter(
4310 name,
4311 AudioMixer::TRACK,
4312 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4313 }
Eric Laurent81784c32012-11-19 14:55:58 -08004314 mAudioMixer->setParameter(
4315 name,
4316 AudioMixer::TRACK,
4317 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4318
4319 // reset retry count
4320 track->mRetryCount = kMaxTrackRetries;
4321
4322 // If one track is ready, set the mixer ready if:
4323 // - the mixer was not ready during previous round OR
4324 // - no other track is not ready
4325 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4326 mixerStatus != MIXER_TRACKS_ENABLED) {
4327 mixerStatus = MIXER_TRACKS_READY;
4328 }
4329 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004330 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004331 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4332 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004333 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004334 } else {
4335 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004336 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004337
Eric Laurent81784c32012-11-19 14:55:58 -08004338 // clear effect chain input buffer if an active track underruns to avoid sending
4339 // previous audio buffer again to effects
4340 chain = getEffectChain_l(track->sessionId());
4341 if (chain != 0) {
4342 chain->clearInputBuffer();
4343 }
4344
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004345 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004346 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4347 track->isStopped() || track->isPaused()) {
4348 // We have consumed all the buffers of this track.
4349 // Remove it from the list of active tracks.
4350 // TODO: use actual buffer filling status instead of latency when available from
4351 // audio HAL
4352 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004353 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004354 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4355 if (track->isStopped()) {
4356 track->reset();
4357 }
4358 tracksToRemove->add(track);
4359 }
4360 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004361 // No buffers for this track. Give it a few chances to
4362 // fill a buffer, then remove it from active list.
4363 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004364 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004365 tracksToRemove->add(track);
4366 // indicate to client process that the track was disabled because of underrun;
4367 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004368 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004369 // If one track is not ready, mark the mixer also not ready if:
4370 // - the mixer was ready during previous round OR
4371 // - no other track is ready
4372 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4373 mixerStatus != MIXER_TRACKS_READY) {
4374 mixerStatus = MIXER_TRACKS_ENABLED;
4375 }
4376 }
4377 mAudioMixer->disable(name);
4378 }
4379
4380 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004381
4382 }
4383
4384 // Push the new FastMixer state if necessary
4385 bool pauseAudioWatchdog = false;
4386 if (didModify) {
4387 state->mFastTracksGen++;
4388 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4389 if (kUseFastMixer == FastMixer_Dynamic &&
4390 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4391 state->mCommand = FastMixerState::COLD_IDLE;
4392 state->mColdFutexAddr = &mFastMixerFutex;
4393 state->mColdGen++;
4394 mFastMixerFutex = 0;
4395 if (kUseFastMixer == FastMixer_Dynamic) {
4396 mNormalSink = mOutputSink;
4397 }
4398 // If we go into cold idle, need to wait for acknowledgement
4399 // so that fast mixer stops doing I/O.
4400 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4401 pauseAudioWatchdog = true;
4402 }
Eric Laurent81784c32012-11-19 14:55:58 -08004403 }
4404 if (sq != NULL) {
4405 sq->end(didModify);
4406 sq->push(block);
4407 }
4408#ifdef AUDIO_WATCHDOG
4409 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4410 mAudioWatchdog->pause();
4411 }
4412#endif
4413
4414 // Now perform the deferred reset on fast tracks that have stopped
4415 while (resetMask != 0) {
4416 size_t i = __builtin_ctz(resetMask);
4417 ALOG_ASSERT(i < count);
4418 resetMask &= ~(1 << i);
Eric Laurent9cab7462016-11-10 13:05:20 -08004419 sp<Track> t = mActiveTracks[i].promote();
4420 if (t == 0) {
4421 continue;
4422 }
4423 Track* track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004424 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4425 track->reset();
4426 }
4427
4428 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004429 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004430
Eric Laurent97d547d2014-09-02 14:45:53 -07004431 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4432 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004433 }
4434
4435 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004436 // as long as there are effects we should clear the effects buffer, to avoid
4437 // passing a non-clean buffer to the effect chain
4438 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004439 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004440 // sink or mix buffer must be cleared if all tracks are connected to an
4441 // effect chain as in this case the mixer will not write to the sink or mix buffer
4442 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004443 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4444 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004445 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004446 if (mMixerBufferValid) {
4447 memset(mMixerBuffer, 0, mMixerBufferSize);
4448 // TODO: In testing, mSinkBuffer below need not be cleared because
4449 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4450 // after mixing.
4451 //
4452 // To enforce this guarantee:
4453 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4454 // (mixedTracks == 0 && fastTracks > 0))
4455 // must imply MIXER_TRACKS_READY.
4456 // Later, we may clear buffers regardless, and skip much of this logic.
4457 }
Andy Hung98ef9782014-03-04 14:46:50 -08004458 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004459 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004460 }
4461
4462 // if any fast tracks, then status is ready
4463 mMixerStatusIgnoringFastTracks = mixerStatus;
4464 if (fastTracks > 0) {
4465 mixerStatus = MIXER_TRACKS_READY;
4466 }
4467 return mixerStatus;
4468}
4469
Eric Laurentad7dd962016-09-22 12:38:37 -07004470// trackCountForUid_l() must be called with ThreadBase::mLock held
4471uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4472{
4473 uint32_t trackCount = 0;
4474 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004475 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004476 trackCount++;
4477 }
4478 }
4479 return trackCount;
4480}
4481
Eric Laurent81784c32012-11-19 14:55:58 -08004482// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004483int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004484 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004485{
Eric Laurentad7dd962016-09-22 12:38:37 -07004486 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4487 return -1;
4488 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004489 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004490}
4491
4492// deleteTrackName_l() must be called with ThreadBase::mLock held
4493void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4494{
4495 ALOGV("remove track (%d) and delete from mixer", name);
4496 mAudioMixer->deleteTrackName(name);
4497}
4498
Eric Laurent10351942014-05-08 18:49:52 -07004499// checkForNewParameter_l() must be called with ThreadBase::mLock held
4500bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4501 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004502{
Eric Laurent81784c32012-11-19 14:55:58 -08004503 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004504 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004505
Eric Laurent10351942014-05-08 18:49:52 -07004506 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004507
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004508 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004509
Eric Laurent10351942014-05-08 18:49:52 -07004510 AudioParameter param = AudioParameter(keyValuePair);
4511 int value;
4512 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4513 reconfig = true;
4514 }
4515 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004516 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004517 status = BAD_VALUE;
4518 } else {
4519 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004520 reconfig = true;
4521 }
Eric Laurent10351942014-05-08 18:49:52 -07004522 }
4523 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004524 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004525 status = BAD_VALUE;
4526 } else {
4527 // no need to save value, since it's constant
4528 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004529 }
Eric Laurent10351942014-05-08 18:49:52 -07004530 }
4531 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4532 // do not accept frame count changes if tracks are open as the track buffer
4533 // size depends on frame count and correct behavior would not be guaranteed
4534 // if frame count is changed after track creation
4535 if (!mTracks.isEmpty()) {
4536 status = INVALID_OPERATION;
4537 } else {
4538 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004539 }
Eric Laurent10351942014-05-08 18:49:52 -07004540 }
4541 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004542#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004543 // when changing the audio output device, call addBatteryData to notify
4544 // the change
4545 if (mOutDevice != value) {
4546 uint32_t params = 0;
4547 // check whether speaker is on
4548 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4549 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004550 }
Eric Laurent10351942014-05-08 18:49:52 -07004551
4552 audio_devices_t deviceWithoutSpeaker
4553 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4554 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004555 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004556 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4557 }
4558
4559 if (params != 0) {
4560 addBatteryData(params);
4561 }
4562 }
Eric Laurent81784c32012-11-19 14:55:58 -08004563#endif
4564
Eric Laurent10351942014-05-08 18:49:52 -07004565 // forward device change to effects that have requested to be
4566 // aware of attached audio device.
4567 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004568 a2dpDeviceChanged =
4569 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004570 mOutDevice = value;
4571 for (size_t i = 0; i < mEffectChains.size(); i++) {
4572 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004573 }
4574 }
Eric Laurent10351942014-05-08 18:49:52 -07004575 }
Eric Laurent81784c32012-11-19 14:55:58 -08004576
Eric Laurent10351942014-05-08 18:49:52 -07004577 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004578 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004579 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004580 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004581 mStandby = true;
4582 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004583 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004584 }
Eric Laurent10351942014-05-08 18:49:52 -07004585 if (status == NO_ERROR && reconfig) {
4586 readOutputParameters_l();
4587 delete mAudioMixer;
4588 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4589 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004590 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004591 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004592 if (name < 0) {
4593 break;
4594 }
4595 mTracks[i]->mName = name;
4596 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004597 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004598 }
Eric Laurent81784c32012-11-19 14:55:58 -08004599 }
4600
Eric Laurent42537be2016-01-08 17:16:42 -08004601 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004602}
4603
4604
4605void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4606{
Eric Laurent81784c32012-11-19 14:55:58 -08004607 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004608 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004609 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004610 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004611
4612 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004613 // while we are dumping it. It may be inconsistent, but it won't mutate!
4614 // This is a large object so we place it on the heap.
4615 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4616 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4617 copy->dump(fd);
4618 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004619
4620#ifdef STATE_QUEUE_DUMP
4621 // Similar for state queue
4622 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4623 observerCopy.dump(fd);
4624 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4625 mutatorCopy.dump(fd);
4626#endif
4627
Glenn Kasten46909e72013-02-26 09:20:22 -08004628#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004629 // Write the tee output to a .wav file
4630 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004631#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004632
4633#ifdef AUDIO_WATCHDOG
4634 if (mAudioWatchdog != 0) {
4635 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4636 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4637 wdCopy.dump(fd);
4638 }
4639#endif
4640}
4641
4642uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4643{
4644 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4645}
4646
4647uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4648{
4649 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4650}
4651
4652void AudioFlinger::MixerThread::cacheParameters_l()
4653{
4654 PlaybackThread::cacheParameters_l();
4655
4656 // FIXME: Relaxed timing because of a certain device that can't meet latency
4657 // Should be reduced to 2x after the vendor fixes the driver issue
4658 // increase threshold again due to low power audio mode. The way this warning
4659 // threshold is calculated and its usefulness should be reconsidered anyway.
4660 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4661}
4662
4663// ----------------------------------------------------------------------------
4664
4665AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004666 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4667 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004668 // mLeftVolFloat, mRightVolFloat
4669{
4670}
4671
Eric Laurentbfb1b832013-01-07 09:53:42 -08004672AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4673 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004674 ThreadBase::type_t type, bool systemReady)
4675 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004676 // mLeftVolFloat, mRightVolFloat
4677{
4678}
4679
Eric Laurent81784c32012-11-19 14:55:58 -08004680AudioFlinger::DirectOutputThread::~DirectOutputThread()
4681{
4682}
4683
Eric Laurent5850c4c2016-11-10 13:04:31 -08004684void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004685{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004686 float left, right;
4687
4688 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4689 left = right = 0;
4690 } else {
4691 float typeVolume = mStreamTypes[track->streamType()].volume;
4692 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004693 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004694 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4695 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4696 if (left > GAIN_FLOAT_UNITY) {
4697 left = GAIN_FLOAT_UNITY;
4698 }
4699 left *= v;
4700 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4701 if (right > GAIN_FLOAT_UNITY) {
4702 right = GAIN_FLOAT_UNITY;
4703 }
4704 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004705 }
4706
4707 if (lastTrack) {
4708 if (left != mLeftVolFloat || right != mRightVolFloat) {
4709 mLeftVolFloat = left;
4710 mRightVolFloat = right;
4711
4712 // Convert volumes from float to 8.24
4713 uint32_t vl = (uint32_t)(left * (1 << 24));
4714 uint32_t vr = (uint32_t)(right * (1 << 24));
4715
4716 // Delegate volume control to effect in track effect chain if needed
4717 // only one effect chain can be present on DirectOutputThread, so if
4718 // there is one, the track is connected to it
4719 if (!mEffectChains.isEmpty()) {
4720 mEffectChains[0]->setVolume_l(&vl, &vr);
4721 left = (float)vl / (1 << 24);
4722 right = (float)vr / (1 << 24);
4723 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004724 status_t result = mOutput->stream->setVolume(left, right);
4725 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004726 }
4727 }
4728}
4729
Phil Burk43b4dcc2015-06-09 16:53:44 -07004730void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4731{
4732 sp<Track> previousTrack = mPreviousTrack.promote();
Eric Laurent9cab7462016-11-10 13:05:20 -08004733 sp<Track> latestTrack = mLatestActiveTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004734
Eric Laurent0f0631e2015-07-06 18:01:25 -07004735 if (previousTrack != 0 && latestTrack != 0) {
4736 if (mType == DIRECT) {
4737 if (previousTrack.get() != latestTrack.get()) {
4738 mFlushPending = true;
4739 }
4740 } else /* mType == OFFLOAD */ {
4741 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4742 mFlushPending = true;
4743 }
4744 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004745 }
4746 PlaybackThread::onAddNewTrack_l();
4747}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004748
Eric Laurent81784c32012-11-19 14:55:58 -08004749AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4750 Vector< sp<Track> > *tracksToRemove
4751)
4752{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004753 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004754 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004755 bool doHwPause = false;
4756 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004757
4758 // find out which tracks need to be processed
Eric Laurent9cab7462016-11-10 13:05:20 -08004759 for (size_t i = 0; i < count; i++) {
4760 sp<Track> t = mActiveTracks[i].promote();
4761 // The track died recently
4762 if (t == 0) {
4763 continue;
4764 }
4765
Eric Laurent5850c4c2016-11-10 13:04:31 -08004766 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004767 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004768 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004769 continue;
4770 }
4771
Eric Laurent5850c4c2016-11-10 13:04:31 -08004772 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004773#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004774 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004775#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004776 // Only consider last track started for volume and mixer state control.
4777 // In theory an older track could underrun and restart after the new one starts
4778 // but as we only care about the transition phase between two tracks on a
4779 // direct output, it is not a problem to ignore the underrun case.
Eric Laurent9cab7462016-11-10 13:05:20 -08004780 sp<Track> l = mLatestActiveTrack.promote();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004781 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004782
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004783 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004784 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004785 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004786 doHwPause = true;
4787 mHwPaused = true;
4788 }
4789 tracksToRemove->add(track);
4790 } else if (track->isFlushPending()) {
4791 track->flushAck();
4792 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004793 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004794 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004795 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004796 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004797 if (last) {
4798 mLeftVolFloat = mRightVolFloat = -1.0;
4799 if (mHwPaused) {
4800 doHwResume = true;
4801 mHwPaused = false;
4802 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004803 }
4804 }
4805
Eric Laurent81784c32012-11-19 14:55:58 -08004806 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004807 // for all its buffers to be filled before processing it.
4808 // Allow draining the buffer in case the client
4809 // app does not call stop() and relies on underrun to stop:
4810 // hence the test on (track->mRetryCount > 1).
4811 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004812 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004813 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004814 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004815 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004816 minFrames = mNormalFrameCount;
4817 } else {
4818 minFrames = 1;
4819 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004820
Eric Laurentab5cdba2014-06-09 17:22:27 -07004821 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4822 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004823 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004824 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004825
4826 if (track->mFillingUpStatus == Track::FS_FILLED) {
4827 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004828 if (last) {
4829 // make sure processVolume_l() will apply new volume even if 0
4830 mLeftVolFloat = mRightVolFloat = -1.0;
4831 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004832 if (!mHwSupportsPause) {
4833 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004834 }
4835 }
4836
4837 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004838 processVolume_l(track, last);
4839 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004840 sp<Track> previousTrack = mPreviousTrack.promote();
4841 if (previousTrack != 0) {
4842 if (track != previousTrack.get()) {
4843 // Flush any data still being written from last track
4844 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004845 // Invalidate previous track to force a seek when resuming.
4846 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004847 }
4848 }
4849 mPreviousTrack = track;
4850
Eric Laurentd595b7c2013-04-03 17:27:56 -07004851 // reset retry count
4852 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004853 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004854 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004855 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004856 doHwResume = true;
4857 mHwPaused = false;
4858 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004859 }
Eric Laurent81784c32012-11-19 14:55:58 -08004860 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004861 // clear effect chain input buffer if the last active track started underruns
4862 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004863 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004864 mEffectChains[0]->clearInputBuffer();
4865 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004866 if (track->isStopping_1()) {
4867 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004868 if (last && mHwPaused) {
4869 doHwResume = true;
4870 mHwPaused = false;
4871 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004872 }
4873 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4874 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004875 // We have consumed all the buffers of this track.
4876 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004877 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004878 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004879 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4880 } else {
4881 audioHALFrames = 0;
4882 }
4883
Andy Hung818e7a32016-02-16 18:08:07 -08004884 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004885 if (mStandby || !last ||
4886 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004887 if (track->isStopping_2()) {
4888 track->mState = TrackBase::STOPPED;
4889 }
Eric Laurent81784c32012-11-19 14:55:58 -08004890 if (track->isStopped()) {
4891 track->reset();
4892 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004893 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004894 }
4895 } else {
4896 // No buffers for this track. Give it a few chances to
4897 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004898 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004899 if (--(track->mRetryCount) <= 0) {
4900 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004901 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004902 // indicate to client process that the track was disabled because of underrun;
4903 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004904 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004905 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004906 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4907 "minFrames = %u, mFormat = %#x",
4908 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004909 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004910 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004911 doHwPause = true;
4912 mHwPaused = true;
4913 }
Eric Laurent81784c32012-11-19 14:55:58 -08004914 }
4915 }
4916 }
4917 }
4918
Eric Laurentd1f69b02014-12-15 14:33:13 -08004919 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004920 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004921 for (size_t i = 0; i < mTracks.size(); i++) {
4922 if (mTracks[i]->isFlushPending()) {
4923 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004924 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004925 }
4926 }
4927 }
4928
4929 // make sure the pause/flush/resume sequence is executed in the right order.
4930 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4931 // before flush and then resume HW. This can happen in case of pause/flush/resume
4932 // if resume is received before pause is executed.
4933 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004934 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004935 status_t result = mOutput->stream->pause();
4936 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004937 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004938 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004939 flushHw_l();
4940 }
4941 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004942 status_t result = mOutput->stream->resume();
4943 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004944 }
Eric Laurent81784c32012-11-19 14:55:58 -08004945 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004946 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004947
4948 return mixerStatus;
4949}
4950
4951void AudioFlinger::DirectOutputThread::threadLoop_mix()
4952{
Eric Laurent81784c32012-11-19 14:55:58 -08004953 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004954 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004955 // output audio to hardware
4956 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004957 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004958 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004959 status_t status = mActiveTrack->getNextBuffer(&buffer);
4960 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004961 // no need to pad with 0 for compressed audio
4962 if (audio_has_proportional_frames(mFormat)) {
4963 memset(curBuf, 0, frameCount * mFrameSize);
4964 }
Eric Laurent81784c32012-11-19 14:55:58 -08004965 break;
4966 }
4967 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4968 frameCount -= buffer.frameCount;
4969 curBuf += buffer.frameCount * mFrameSize;
4970 mActiveTrack->releaseBuffer(&buffer);
4971 }
Andy Hung2098f272014-02-27 14:00:06 -08004972 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004973 mSleepTimeUs = 0;
4974 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004975 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004976}
4977
4978void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4979{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004980 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004981 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004982 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004983 return;
4984 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004985 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004986 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07004987 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004988 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004989 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004990 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004991 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004992 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004993 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004994 }
4995}
4996
Eric Laurentd1f69b02014-12-15 14:33:13 -08004997void AudioFlinger::DirectOutputThread::threadLoop_exit()
4998{
4999 {
5000 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005001 for (size_t i = 0; i < mTracks.size(); i++) {
5002 if (mTracks[i]->isFlushPending()) {
5003 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005004 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005005 }
5006 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005007 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005008 flushHw_l();
5009 }
5010 }
5011 PlaybackThread::threadLoop_exit();
5012}
5013
5014// must be called with thread mutex locked
5015bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5016{
5017 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005018 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005019
vivek mehta9cd7ad12016-03-17 00:18:29 -07005020 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5021 return !mStandby;
5022 }
5023
Eric Laurentd1f69b02014-12-15 14:33:13 -08005024 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5025 // after a timeout and we will enter standby then.
5026 if (mTracks.size() > 0) {
5027 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005028 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5029 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005030 }
5031
Eric Laurent5cff4032015-05-26 13:49:58 -07005032 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005033}
5034
Eric Laurent81784c32012-11-19 14:55:58 -08005035// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005036int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005037 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005038{
Eric Laurentad7dd962016-09-22 12:38:37 -07005039 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5040 return -1;
5041 }
Eric Laurent81784c32012-11-19 14:55:58 -08005042 return 0;
5043}
5044
5045// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005046void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005047{
5048}
5049
Eric Laurent10351942014-05-08 18:49:52 -07005050// checkForNewParameter_l() must be called with ThreadBase::mLock held
5051bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5052 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005053{
5054 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005055 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005056
Eric Laurent10351942014-05-08 18:49:52 -07005057 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005058
Eric Laurent10351942014-05-08 18:49:52 -07005059 AudioParameter param = AudioParameter(keyValuePair);
5060 int value;
5061 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5062 // forward device change to effects that have requested to be
5063 // aware of attached audio device.
5064 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005065 a2dpDeviceChanged =
5066 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005067 mOutDevice = value;
5068 for (size_t i = 0; i < mEffectChains.size(); i++) {
5069 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005070 }
5071 }
Eric Laurent81784c32012-11-19 14:55:58 -08005072 }
Eric Laurent10351942014-05-08 18:49:52 -07005073 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5074 // do not accept frame count changes if tracks are open as the track buffer
5075 // size depends on frame count and correct behavior would not be garantied
5076 // if frame count is changed after track creation
5077 if (!mTracks.isEmpty()) {
5078 status = INVALID_OPERATION;
5079 } else {
5080 reconfig = true;
5081 }
5082 }
5083 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005084 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005085 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005086 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005087 mStandby = true;
5088 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005089 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005090 }
5091 if (status == NO_ERROR && reconfig) {
5092 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005093 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005094 }
5095 }
5096
Eric Laurent42537be2016-01-08 17:16:42 -08005097 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005098}
5099
5100uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5101{
5102 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005103 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005104 time = PlaybackThread::activeSleepTimeUs();
5105 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005106 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005107 }
5108 return time;
5109}
5110
5111uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5112{
5113 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005114 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005115 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5116 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005117 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005118 }
5119 return time;
5120}
5121
5122uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5123{
5124 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005125 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005126 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5127 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005128 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005129 }
5130 return time;
5131}
5132
5133void AudioFlinger::DirectOutputThread::cacheParameters_l()
5134{
5135 PlaybackThread::cacheParameters_l();
5136
5137 // use shorter standby delay as on normal output to release
5138 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005139 // no delay on outputs with HW A/V sync
5140 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005141 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005142 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005143 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005144 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005145 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005146 }
Eric Laurent81784c32012-11-19 14:55:58 -08005147}
5148
Eric Laurente659ef42014-09-29 13:06:46 -07005149void AudioFlinger::DirectOutputThread::flushHw_l()
5150{
Phil Burk062e67a2015-02-11 13:40:50 -08005151 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005152 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005153 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005154}
5155
Eric Laurent81784c32012-11-19 14:55:58 -08005156// ----------------------------------------------------------------------------
5157
Eric Laurentbfb1b832013-01-07 09:53:42 -08005158AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005159 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005160 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005161 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005162 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005163 mDrainSequence(0),
5164 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005165{
5166}
5167
5168AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5169{
5170}
5171
5172void AudioFlinger::AsyncCallbackThread::onFirstRef()
5173{
5174 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5175}
5176
5177bool AudioFlinger::AsyncCallbackThread::threadLoop()
5178{
5179 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005180 uint32_t writeAckSequence;
5181 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005182 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005183
5184 {
5185 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005186 while (!((mWriteAckSequence & 1) ||
5187 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005188 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005189 exitPending())) {
5190 mWaitWorkCV.wait(mLock);
5191 }
5192
Eric Laurentbfb1b832013-01-07 09:53:42 -08005193 if (exitPending()) {
5194 break;
5195 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005196 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5197 mWriteAckSequence, mDrainSequence);
5198 writeAckSequence = mWriteAckSequence;
5199 mWriteAckSequence &= ~1;
5200 drainSequence = mDrainSequence;
5201 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005202 asyncError = mAsyncError;
5203 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005204 }
5205 {
Eric Laurent4de95592013-09-26 15:28:21 -07005206 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5207 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005208 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005209 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005210 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005211 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005212 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005213 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005214 if (asyncError) {
5215 playbackThread->onAsyncError();
5216 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005217 }
5218 }
5219 }
5220 return false;
5221}
5222
5223void AudioFlinger::AsyncCallbackThread::exit()
5224{
5225 ALOGV("AsyncCallbackThread::exit");
5226 Mutex::Autolock _l(mLock);
5227 requestExit();
5228 mWaitWorkCV.broadcast();
5229}
5230
Eric Laurent3b4529e2013-09-05 18:09:19 -07005231void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005232{
5233 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005234 // bit 0 is cleared
5235 mWriteAckSequence = sequence << 1;
5236}
5237
5238void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5239{
5240 Mutex::Autolock _l(mLock);
5241 // ignore unexpected callbacks
5242 if (mWriteAckSequence & 2) {
5243 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005244 mWaitWorkCV.signal();
5245 }
5246}
5247
Eric Laurent3b4529e2013-09-05 18:09:19 -07005248void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005249{
5250 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005251 // bit 0 is cleared
5252 mDrainSequence = sequence << 1;
5253}
5254
5255void AudioFlinger::AsyncCallbackThread::resetDraining()
5256{
5257 Mutex::Autolock _l(mLock);
5258 // ignore unexpected callbacks
5259 if (mDrainSequence & 2) {
5260 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005261 mWaitWorkCV.signal();
5262 }
5263}
5264
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005265void AudioFlinger::AsyncCallbackThread::setAsyncError()
5266{
5267 Mutex::Autolock _l(mLock);
5268 mAsyncError = true;
5269 mWaitWorkCV.signal();
5270}
5271
Eric Laurentbfb1b832013-01-07 09:53:42 -08005272
5273// ----------------------------------------------------------------------------
5274AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005275 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5276 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005277 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5278 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005279{
Eric Laurentfd477972013-10-25 18:10:40 -07005280 //FIXME: mStandby should be set to true by ThreadBase constructor
5281 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005282 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005283}
5284
Eric Laurentbfb1b832013-01-07 09:53:42 -08005285void AudioFlinger::OffloadThread::threadLoop_exit()
5286{
5287 if (mFlushPending || mHwPaused) {
5288 // If a flush is pending or track was paused, just discard buffered data
5289 flushHw_l();
5290 } else {
5291 mMixerStatus = MIXER_DRAIN_ALL;
5292 threadLoop_drain();
5293 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005294 if (mUseAsyncWrite) {
5295 ALOG_ASSERT(mCallbackThread != 0);
5296 mCallbackThread->exit();
5297 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005298 PlaybackThread::threadLoop_exit();
5299}
5300
5301AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5302 Vector< sp<Track> > *tracksToRemove
5303)
5304{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005305 size_t count = mActiveTracks.size();
5306
5307 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005308 bool doHwPause = false;
5309 bool doHwResume = false;
5310
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005311 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005312
Eric Laurentbfb1b832013-01-07 09:53:42 -08005313 // find out which tracks need to be processed
Eric Laurent9cab7462016-11-10 13:05:20 -08005314 for (size_t i = 0; i < count; i++) {
5315 sp<Track> t = mActiveTracks[i].promote();
5316 // The track died recently
5317 if (t == 0) {
5318 continue;
5319 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005320 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005321#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005322 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005323#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005324 // Only consider last track started for volume and mixer state control.
5325 // In theory an older track could underrun and restart after the new one starts
5326 // but as we only care about the transition phase between two tracks on a
5327 // direct output, it is not a problem to ignore the underrun case.
Eric Laurent9cab7462016-11-10 13:05:20 -08005328 sp<Track> l = mLatestActiveTrack.promote();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005329 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005330
Haynes Mathew George7844f672014-01-15 12:32:55 -08005331 if (track->isInvalid()) {
5332 ALOGW("An invalidated track shouldn't be in active list");
5333 tracksToRemove->add(track);
5334 continue;
5335 }
5336
5337 if (track->mState == TrackBase::IDLE) {
5338 ALOGW("An idle track shouldn't be in active list");
5339 continue;
5340 }
5341
Eric Laurentbfb1b832013-01-07 09:53:42 -08005342 if (track->isPausing()) {
5343 track->setPaused();
5344 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005345 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005346 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005347 mHwPaused = true;
5348 }
5349 // If we were part way through writing the mixbuffer to
5350 // the HAL we must save this until we resume
5351 // BUG - this will be wrong if a different track is made active,
5352 // in that case we want to discard the pending data in the
5353 // mixbuffer and tell the client to present it again when the
5354 // track is resumed
5355 mPausedWriteLength = mCurrentWriteLength;
5356 mPausedBytesRemaining = mBytesRemaining;
5357 mBytesRemaining = 0; // stop writing
5358 }
5359 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005360 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005361 if (track->isStopping_1()) {
5362 track->mRetryCount = kMaxTrackStopRetriesOffload;
5363 } else {
5364 track->mRetryCount = kMaxTrackRetriesOffload;
5365 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005366 track->flushAck();
5367 if (last) {
5368 mFlushPending = true;
5369 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005370 } else if (track->isResumePending()){
5371 track->resumeAck();
5372 if (last) {
5373 if (mPausedBytesRemaining) {
5374 // Need to continue write that was interrupted
5375 mCurrentWriteLength = mPausedWriteLength;
5376 mBytesRemaining = mPausedBytesRemaining;
5377 mPausedBytesRemaining = 0;
5378 }
5379 if (mHwPaused) {
5380 doHwResume = true;
5381 mHwPaused = false;
5382 // threadLoop_mix() will handle the case that we need to
5383 // resume an interrupted write
5384 }
5385 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005386 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005387
Eric Laurent3df841a2016-07-15 15:15:40 -07005388 mLeftVolFloat = mRightVolFloat = -1.0;
5389
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005390 // Do not handle new data in this iteration even if track->framesReady()
5391 mixerStatus = MIXER_TRACKS_ENABLED;
5392 }
5393 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005394 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005395 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005396 if (track->mFillingUpStatus == Track::FS_FILLED) {
5397 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005398 if (last) {
5399 // make sure processVolume_l() will apply new volume even if 0
5400 mLeftVolFloat = mRightVolFloat = -1.0;
5401 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005402 }
5403
5404 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005405 sp<Track> previousTrack = mPreviousTrack.promote();
5406 if (previousTrack != 0) {
5407 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005408 // Flush any data still being written from last track
5409 mBytesRemaining = 0;
5410 if (mPausedBytesRemaining) {
5411 // Last track was paused so we also need to flush saved
5412 // mixbuffer state and invalidate track so that it will
5413 // re-submit that unwritten data when it is next resumed
5414 mPausedBytesRemaining = 0;
5415 // Invalidate is a bit drastic - would be more efficient
5416 // to have a flag to tell client that some of the
5417 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005418 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005419 }
5420 // flush data already sent to the DSP if changing audio session as audio
5421 // comes from a different source. Also invalidate previous track to force a
5422 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005423 if (previousTrack->sessionId() != track->sessionId()) {
5424 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005425 }
5426 }
5427 }
5428 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005429 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005430 if (track->isStopping_1()) {
5431 track->mRetryCount = kMaxTrackStopRetriesOffload;
5432 } else {
5433 track->mRetryCount = kMaxTrackRetriesOffload;
5434 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005435 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005436 mixerStatus = MIXER_TRACKS_READY;
5437 }
5438 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005439 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005440 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005441 if (--(track->mRetryCount) <= 0) {
5442 // Hardware buffer can hold a large amount of audio so we must
5443 // wait for all current track's data to drain before we say
5444 // that the track is stopped.
5445 if (mBytesRemaining == 0) {
5446 // Only start draining when all data in mixbuffer
5447 // has been written
5448 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5449 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5450 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5451 if (last && !mStandby) {
5452 // do not modify drain sequence if we are already draining. This happens
5453 // when resuming from pause after drain.
5454 if ((mDrainSequence & 1) == 0) {
5455 mSleepTimeUs = 0;
5456 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5457 mixerStatus = MIXER_DRAIN_TRACK;
5458 mDrainSequence += 2;
5459 }
5460 if (mHwPaused) {
5461 // It is possible to move from PAUSED to STOPPING_1 without
5462 // a resume so we must ensure hardware is running
5463 doHwResume = true;
5464 mHwPaused = false;
5465 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005466 }
5467 }
Eric Laurente93cc032016-05-05 10:15:10 -07005468 } else if (last) {
5469 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5470 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005471 }
5472 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005473 // Drain has completed or we are in standby, signal presentation complete
5474 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005475 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005476 uint32_t latency = 0;
5477 status_t result = mOutput->stream->getLatency(&latency);
5478 ALOGE_IF(result != OK,
5479 "Error when retrieving output stream latency: %d", result);
5480 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005481 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005482 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005483 track->presentationComplete(framesWritten, audioHALFrames);
5484 track->reset();
5485 tracksToRemove->add(track);
5486 }
5487 } else {
5488 // No buffers for this track. Give it a few chances to
5489 // fill a buffer, then remove it from active list.
5490 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005491 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005492 uint64_t position = 0;
5493 struct timespec unused;
5494 // The running check restarts the retry counter at least once.
5495 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5496 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5497 running = true;
5498 mOffloadUnderrunPosition = position;
5499 }
5500 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005501 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5502 (long long)position, (long long)mOffloadUnderrunPosition);
5503 }
5504 if (running) { // still running, give us more time.
5505 track->mRetryCount = kMaxTrackRetriesOffload;
5506 } else {
5507 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5508 track->name());
5509 tracksToRemove->add(track);
5510 // indicate to client process that the track was disabled because of underrun;
5511 // it will then automatically call start() when data is available
5512 track->disable();
5513 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005514 } else if (last){
5515 mixerStatus = MIXER_TRACKS_ENABLED;
5516 }
5517 }
5518 }
5519 // compute volume for this track
5520 processVolume_l(track, last);
5521 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005522
Eric Laurentea0fade2013-10-04 16:23:48 -07005523 // make sure the pause/flush/resume sequence is executed in the right order.
5524 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5525 // before flush and then resume HW. This can happen in case of pause/flush/resume
5526 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005527 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005528 status_t result = mOutput->stream->pause();
5529 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005530 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005531 if (mFlushPending) {
5532 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005533 }
Eric Laurentfd477972013-10-25 18:10:40 -07005534 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005535 status_t result = mOutput->stream->resume();
5536 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005537 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005538
Eric Laurentbfb1b832013-01-07 09:53:42 -08005539 // remove all the tracks that need to be...
5540 removeTracks_l(*tracksToRemove);
5541
5542 return mixerStatus;
5543}
5544
Eric Laurentbfb1b832013-01-07 09:53:42 -08005545// must be called with thread mutex locked
5546bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5547{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005548 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5549 mWriteAckSequence, mDrainSequence);
5550 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005551 return true;
5552 }
5553 return false;
5554}
5555
Eric Laurentbfb1b832013-01-07 09:53:42 -08005556bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5557{
5558 Mutex::Autolock _l(mLock);
5559 return waitingAsyncCallback_l();
5560}
5561
5562void AudioFlinger::OffloadThread::flushHw_l()
5563{
Eric Laurente659ef42014-09-29 13:06:46 -07005564 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005565 // Flush anything still waiting in the mixbuffer
5566 mCurrentWriteLength = 0;
5567 mBytesRemaining = 0;
5568 mPausedWriteLength = 0;
5569 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005570 // reset bytes written count to reflect that DSP buffers are empty after flush.
5571 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005572 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005573
Eric Laurentbfb1b832013-01-07 09:53:42 -08005574 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005575 // discard any pending drain or write ack by incrementing sequence
5576 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5577 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005578 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005579 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5580 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581 }
5582}
5583
Haynes Mathew George05317d22016-05-03 16:34:26 -07005584void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5585{
5586 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005587 if (PlaybackThread::invalidateTracks_l(streamType)) {
5588 mFlushPending = true;
5589 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005590}
5591
Eric Laurentbfb1b832013-01-07 09:53:42 -08005592// ----------------------------------------------------------------------------
5593
Eric Laurent81784c32012-11-19 14:55:58 -08005594AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005595 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005596 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005597 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005598 mWaitTimeMs(UINT_MAX)
5599{
5600 addOutputTrack(mainThread);
5601}
5602
5603AudioFlinger::DuplicatingThread::~DuplicatingThread()
5604{
5605 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5606 mOutputTracks[i]->destroy();
5607 }
5608}
5609
5610void AudioFlinger::DuplicatingThread::threadLoop_mix()
5611{
5612 // mix buffers...
5613 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005614 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005615 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005616 if (mMixerBufferValid) {
5617 memset(mMixerBuffer, 0, mMixerBufferSize);
5618 } else {
5619 memset(mSinkBuffer, 0, mSinkBufferSize);
5620 }
Eric Laurent81784c32012-11-19 14:55:58 -08005621 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005622 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005623 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005624 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005625 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005626}
5627
5628void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5629{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005630 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005631 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005632 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005633 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005634 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005635 }
5636 } else if (mBytesWritten != 0) {
5637 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5638 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005639 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005640 } else {
5641 // flush remaining overflow buffers in output tracks
5642 writeFrames = 0;
5643 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005644 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005645 }
5646}
5647
Eric Laurentbfb1b832013-01-07 09:53:42 -08005648ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005649{
5650 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005651 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005652 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005653 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005654 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005655}
5656
5657void AudioFlinger::DuplicatingThread::threadLoop_standby()
5658{
5659 // DuplicatingThread implements standby by stopping all tracks
5660 for (size_t i = 0; i < outputTracks.size(); i++) {
5661 outputTracks[i]->stop();
5662 }
5663}
5664
5665void AudioFlinger::DuplicatingThread::saveOutputTracks()
5666{
5667 outputTracks = mOutputTracks;
5668}
5669
5670void AudioFlinger::DuplicatingThread::clearOutputTracks()
5671{
5672 outputTracks.clear();
5673}
5674
5675void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5676{
5677 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005678 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5679 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5680 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5681 const size_t frameCount =
5682 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5683 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5684 // from different OutputTracks and their associated MixerThreads (e.g. one may
5685 // nearly empty and the other may be dropping data).
5686
5687 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005688 this,
5689 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005690 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005691 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005692 frameCount,
5693 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005694 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5695 if (status != NO_ERROR) {
5696 ALOGE("addOutputTrack() initCheck failed %d", status);
5697 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005698 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005699 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5700 mOutputTracks.add(outputTrack);
5701 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5702 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005703}
5704
5705void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5706{
5707 Mutex::Autolock _l(mLock);
5708 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5709 if (mOutputTracks[i]->thread() == thread) {
5710 mOutputTracks[i]->destroy();
5711 mOutputTracks.removeAt(i);
5712 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005713 if (thread->getOutput() == mOutput) {
5714 mOutput = NULL;
5715 }
Eric Laurent81784c32012-11-19 14:55:58 -08005716 return;
5717 }
5718 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005719 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005720}
5721
5722// caller must hold mLock
5723void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5724{
5725 mWaitTimeMs = UINT_MAX;
5726 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5727 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5728 if (strong != 0) {
5729 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5730 if (waitTimeMs < mWaitTimeMs) {
5731 mWaitTimeMs = waitTimeMs;
5732 }
5733 }
5734 }
5735}
5736
5737
5738bool AudioFlinger::DuplicatingThread::outputsReady(
5739 const SortedVector< sp<OutputTrack> > &outputTracks)
5740{
5741 for (size_t i = 0; i < outputTracks.size(); i++) {
5742 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5743 if (thread == 0) {
5744 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5745 outputTracks[i].get());
5746 return false;
5747 }
5748 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5749 // see note at standby() declaration
5750 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5751 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5752 thread.get());
5753 return false;
5754 }
5755 }
5756 return true;
5757}
5758
5759uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5760{
5761 return (mWaitTimeMs * 1000) / 2;
5762}
5763
5764void AudioFlinger::DuplicatingThread::cacheParameters_l()
5765{
5766 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5767 updateWaitTime_l();
5768
5769 MixerThread::cacheParameters_l();
5770}
5771
5772// ----------------------------------------------------------------------------
5773// Record
5774// ----------------------------------------------------------------------------
5775
5776AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5777 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005778 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005779 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005780 audio_devices_t inDevice,
5781 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005782#ifdef TEE_SINK
5783 , const sp<NBAIO_Sink>& teeSink
5784#endif
5785 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005786 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Eric Laurent9cab7462016-11-10 13:05:20 -08005787 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005788 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005789 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005790#ifdef TEE_SINK
5791 , mTeeSink(teeSink)
5792#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005793 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5794 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005795 // mFastCapture below
5796 , mFastCaptureFutex(0)
5797 // mInputSource
5798 // mPipeSink
5799 // mPipeSource
5800 , mPipeFramesP2(0)
5801 // mPipeMemory
5802 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005803 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005804{
Glenn Kastend7dca052015-03-05 16:05:54 -08005805 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5806 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005807
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005808 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005809
5810 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005811 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005812 size_t numCounterOffers = 0;
5813 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005814#if !LOG_NDEBUG
5815 ssize_t index =
5816#else
5817 (void)
5818#endif
5819 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005820 ALOG_ASSERT(index == 0);
5821
5822 // initialize fast capture depending on configuration
5823 bool initFastCapture;
5824 switch (kUseFastCapture) {
5825 case FastCapture_Never:
5826 initFastCapture = false;
5827 break;
5828 case FastCapture_Always:
5829 initFastCapture = true;
5830 break;
5831 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005832 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005833 break;
5834 // case FastCapture_Dynamic:
5835 }
5836
5837 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005838 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005839 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005840 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5841 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005842 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5843 void *pipeBuffer;
5844 const sp<MemoryDealer> roHeap(readOnlyHeap());
5845 sp<IMemory> pipeMemory;
5846 if ((roHeap == 0) ||
5847 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5848 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5849 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5850 goto failed;
5851 }
5852 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5853 memset(pipeBuffer, 0, pipeSize);
5854 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5855 const NBAIO_Format offers[1] = {format};
5856 size_t numCounterOffers = 0;
5857 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5858 ALOG_ASSERT(index == 0);
5859 mPipeSink = pipe;
5860 PipeReader *pipeReader = new PipeReader(*pipe);
5861 numCounterOffers = 0;
5862 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5863 ALOG_ASSERT(index == 0);
5864 mPipeSource = pipeReader;
5865 mPipeFramesP2 = pipeFramesP2;
5866 mPipeMemory = pipeMemory;
5867
5868 // create fast capture
5869 mFastCapture = new FastCapture();
5870 FastCaptureStateQueue *sq = mFastCapture->sq();
5871#ifdef STATE_QUEUE_DUMP
5872 // FIXME
5873#endif
5874 FastCaptureState *state = sq->begin();
5875 state->mCblk = NULL;
5876 state->mInputSource = mInputSource.get();
5877 state->mInputSourceGen++;
5878 state->mPipeSink = pipe;
5879 state->mPipeSinkGen++;
5880 state->mFrameCount = mFrameCount;
5881 state->mCommand = FastCaptureState::COLD_IDLE;
5882 // already done in constructor initialization list
5883 //mFastCaptureFutex = 0;
5884 state->mColdFutexAddr = &mFastCaptureFutex;
5885 state->mColdGen++;
5886 state->mDumpState = &mFastCaptureDumpState;
5887#ifdef TEE_SINK
5888 // FIXME
5889#endif
5890 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5891 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5892 sq->end();
5893 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5894
5895 // start the fast capture
5896 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5897 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005898 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005899#ifdef AUDIO_WATCHDOG
5900 // FIXME
5901#endif
5902
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005903 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005904 }
5905failed: ;
5906
5907 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005908}
5909
Eric Laurent81784c32012-11-19 14:55:58 -08005910AudioFlinger::RecordThread::~RecordThread()
5911{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005912 if (mFastCapture != 0) {
5913 FastCaptureStateQueue *sq = mFastCapture->sq();
5914 FastCaptureState *state = sq->begin();
5915 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5916 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5917 if (old == -1) {
5918 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5919 }
5920 }
5921 state->mCommand = FastCaptureState::EXIT;
5922 sq->end();
5923 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5924 mFastCapture->join();
5925 mFastCapture.clear();
5926 }
5927 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005928 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005929 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005930}
5931
5932void AudioFlinger::RecordThread::onFirstRef()
5933{
Glenn Kastend7dca052015-03-05 16:05:54 -08005934 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005935}
5936
Eric Laurent81784c32012-11-19 14:55:58 -08005937bool AudioFlinger::RecordThread::threadLoop()
5938{
Eric Laurent81784c32012-11-19 14:55:58 -08005939 nsecs_t lastWarning = 0;
5940
5941 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005942
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005943reacquire_wakelock:
5944 sp<RecordTrack> activeTrack;
Eric Laurent9cab7462016-11-10 13:05:20 -08005945 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005946 {
5947 Mutex::Autolock _l(mLock);
Eric Laurent9cab7462016-11-10 13:05:20 -08005948 size_t size = mActiveTracks.size();
5949 activeTracksGen = mActiveTracksGen;
5950 if (size > 0) {
5951 // FIXME an arbitrary choice
5952 activeTrack = mActiveTracks[0];
5953 acquireWakeLock_l(activeTrack->uid());
5954 if (size > 1) {
5955 SortedVector<int> tmp;
5956 for (size_t i = 0; i < size; i++) {
5957 tmp.add(mActiveTracks[i]->uid());
5958 }
5959 updateWakeLockUids_l(tmp);
5960 }
5961 } else {
5962 acquireWakeLock_l(-1);
5963 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005964 }
5965
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005966 // used to request a deferred sleep, to be executed later while mutex is unlocked
5967 uint32_t sleepUs = 0;
5968
5969 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005970 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005971 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005972
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005973 // activeTracks accumulates a copy of a subset of mActiveTracks
5974 Vector< sp<RecordTrack> > activeTracks;
5975
Glenn Kasten735f45f2014-08-18 15:51:59 -07005976 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005977 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005978
Glenn Kasten735f45f2014-08-18 15:51:59 -07005979 // reference to a fast track which is about to be removed
5980 sp<RecordTrack> fastTrackToRemove;
5981
Eric Laurent81784c32012-11-19 14:55:58 -08005982 { // scope for mLock
5983 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005984
Eric Laurent021cf962014-05-13 10:18:14 -07005985 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005986
Eric Laurent000a4192014-01-29 15:17:32 -08005987 // check exitPending here because checkForNewParameters_l() and
5988 // checkForNewParameters_l() can temporarily release mLock
5989 if (exitPending()) {
5990 break;
5991 }
5992
Eric Laurent5c25d562016-07-13 17:17:45 -07005993 // sleep with mutex unlocked
5994 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07005995 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07005996 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
5997 ATRACE_END();
5998 sleepUs = 0;
5999 continue;
6000 }
6001
Glenn Kasten2b806402013-11-20 16:37:38 -08006002 // if no active track(s), then standby and release wakelock
6003 size_t size = mActiveTracks.size();
6004 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006005 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006006 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006007 releaseWakeLock_l();
6008 ALOGV("RecordThread: loop stopping");
6009 // go to sleep
6010 mWaitWorkCV.wait(mLock);
6011 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006012 goto reacquire_wakelock;
6013 }
6014
Eric Laurent9cab7462016-11-10 13:05:20 -08006015 if (mActiveTracksGen != activeTracksGen) {
6016 activeTracksGen = mActiveTracksGen;
6017 SortedVector<int> tmp;
6018 for (size_t i = 0; i < size; i++) {
6019 tmp.add(mActiveTracks[i]->uid());
6020 }
6021 updateWakeLockUids_l(tmp);
6022 }
6023
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006024 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006025 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006026 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006027
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006028 activeTrack = mActiveTracks[i];
6029 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006030 if (activeTrack->isFastTrack()) {
6031 ALOG_ASSERT(fastTrackToRemove == 0);
6032 fastTrackToRemove = activeTrack;
6033 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006034 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006035 mActiveTracks.remove(activeTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006036 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006037 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006038 continue;
6039 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006040
6041 TrackBase::track_state activeTrackState = activeTrack->mState;
6042 switch (activeTrackState) {
6043
6044 case TrackBase::PAUSING:
6045 mActiveTracks.remove(activeTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006046 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006047 doBroadcast = true;
6048 size--;
6049 continue;
6050
6051 case TrackBase::STARTING_1:
6052 sleepUs = 10000;
6053 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006054 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006055 continue;
6056
6057 case TrackBase::STARTING_2:
6058 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006059 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006060 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006061 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006062 break;
6063
6064 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006065 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006066 break;
6067
6068 case TrackBase::IDLE:
6069 i++;
6070 continue;
6071
6072 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006073 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006074 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006075
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006076 activeTracks.add(activeTrack);
6077 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006078
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006079 if (activeTrack->isFastTrack()) {
6080 ALOG_ASSERT(!mFastTrackAvail);
6081 ALOG_ASSERT(fastTrack == 0);
6082 fastTrack = activeTrack;
6083 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006084 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006085
6086 if (allStopped) {
6087 standbyIfNotAlreadyInStandby();
6088 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006089 if (doBroadcast) {
6090 mStartStopCond.broadcast();
6091 }
6092
6093 // sleep if there are no active tracks to process
6094 if (activeTracks.size() == 0) {
6095 if (sleepUs == 0) {
6096 sleepUs = kRecordThreadSleepUs;
6097 }
6098 continue;
6099 }
6100 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006101
Eric Laurent81784c32012-11-19 14:55:58 -08006102 lockEffectChains_l(effectChains);
6103 }
6104
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006105 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006106
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006107 size_t size = effectChains.size();
6108 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006109 // thread mutex is not locked, but effect chain is locked
6110 effectChains[i]->process_l();
6111 }
6112
Glenn Kasten735f45f2014-08-18 15:51:59 -07006113 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006114 if (mFastCapture != 0) {
6115 FastCaptureStateQueue *sq = mFastCapture->sq();
6116 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006117 bool didModify = false;
6118 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006119 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6120 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6121 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6122 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6123 if (old == -1) {
6124 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6125 }
6126 }
6127 state->mCommand = FastCaptureState::READ_WRITE;
6128#if 0 // FIXME
6129 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006130 FastThreadDumpState::kSamplingNforLowRamDevice :
6131 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006132#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006133 didModify = true;
6134 }
6135 audio_track_cblk_t *cblkOld = state->mCblk;
6136 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6137 if (cblkNew != cblkOld) {
6138 state->mCblk = cblkNew;
6139 // block until acked if removing a fast track
6140 if (cblkOld != NULL) {
6141 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6142 }
6143 didModify = true;
6144 }
6145 sq->end(didModify);
6146 if (didModify) {
6147 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006148#if 0
6149 if (kUseFastCapture == FastCapture_Dynamic) {
6150 mNormalSource = mPipeSource;
6151 }
6152#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006153 }
6154 }
6155
Glenn Kasten735f45f2014-08-18 15:51:59 -07006156 // now run the fast track destructor with thread mutex unlocked
6157 fastTrackToRemove.clear();
6158
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006159 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6160 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6161 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6162 // If destination is non-contiguous, first read past the nominal end of buffer, then
6163 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006164
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006165 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006166 ssize_t framesRead;
6167
6168 // If an NBAIO source is present, use it to read the normal capture's data
6169 if (mPipeSource != 0) {
6170 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006171 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006172 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006173 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006174 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6175 // buffer size or at least for 20ms.
6176 size_t sleepFrames = max(
6177 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6178 if (framesRead <= (ssize_t) sleepFrames) {
6179 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6180 }
6181 if (framesRead < 0) {
6182 status_t status = (status_t) framesRead;
6183 switch (status) {
6184 case OVERRUN:
6185 ALOGW("overrun on read from pipe");
6186 framesRead = 0;
6187 break;
6188 case NEGOTIATE:
6189 ALOGE("re-negotiation is needed");
6190 framesRead = -1; // Will cause an attempt to recover.
6191 break;
6192 default:
6193 ALOGE("unknown error %d on read from pipe", status);
6194 break;
6195 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006196 }
6197 // otherwise use the HAL / AudioStreamIn directly
6198 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006199 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006200 size_t bytesRead;
6201 status_t result = mInput->stream->read(
6202 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006203 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006204 if (result < 0) {
6205 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006206 } else {
6207 framesRead = bytesRead / mFrameSize;
6208 }
6209 }
6210
Andy Hung3f0c9022016-01-15 17:49:46 -08006211 // Update server timestamp with server stats
6212 // systemTime() is optional if the hardware supports timestamps.
6213 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6214 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6215
6216 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006217 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006218 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006219 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006220 if (ret == NO_ERROR) {
6221 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6222 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6223 // Note: In general record buffers should tend to be empty in
6224 // a properly running pipeline.
6225 //
6226 // Also, it is not advantageous to call get_presentation_position during the read
6227 // as the read obtains a lock, preventing the timestamp call from executing.
6228 }
6229 }
6230 // Use this to track timestamp information
6231 // ALOGD("%s", mTimestamp.toString().c_str());
6232
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006233 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006234 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006235 // Force input into standby so that it tries to recover at next read attempt
6236 inputStandBy();
6237 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006238 }
6239 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006240 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006241 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006242 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006243
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006244 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006245 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006246 }
6247 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006248 {
6249 size_t part1 = mRsmpInFramesP2 - rear;
6250 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006251 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006252 (framesRead - part1) * mFrameSize);
6253 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006254 }
6255 rear = mRsmpInRear += framesRead;
6256
6257 size = activeTracks.size();
6258 // loop over each active track
6259 for (size_t i = 0; i < size; i++) {
6260 activeTrack = activeTracks[i];
6261
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006262 // skip fast tracks, as those are handled directly by FastCapture
6263 if (activeTrack->isFastTrack()) {
6264 continue;
6265 }
6266
Andy Hung73c02e42015-03-29 01:13:58 -07006267 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006268 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6269
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006270 enum {
6271 OVERRUN_UNKNOWN,
6272 OVERRUN_TRUE,
6273 OVERRUN_FALSE
6274 } overrun = OVERRUN_UNKNOWN;
6275
6276 // loop over getNextBuffer to handle circular sink
6277 for (;;) {
6278
6279 activeTrack->mSink.frameCount = ~0;
6280 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6281 size_t framesOut = activeTrack->mSink.frameCount;
6282 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6283
Andy Hung73c02e42015-03-29 01:13:58 -07006284 // check available frames and handle overrun conditions
6285 // if the record track isn't draining fast enough.
6286 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006287 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006288 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6289 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006290 overrun = OVERRUN_TRUE;
6291 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006292 if (framesOut == 0 || framesIn == 0) {
6293 break;
6294 }
6295
Andy Hung6770c6f2015-04-07 13:43:36 -07006296 // Don't allow framesOut to be larger than what is possible with resampling
6297 // from framesIn.
6298 // This isn't strictly necessary but helps limit buffer resizing in
6299 // RecordBufferConverter. TODO: remove when no longer needed.
6300 framesOut = min(framesOut,
6301 destinationFramesPossible(
6302 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006303 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6304 framesOut = activeTrack->mRecordBufferConverter->convert(
6305 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006306
6307 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6308 overrun = OVERRUN_FALSE;
6309 }
6310
6311 if (activeTrack->mFramesToDrop == 0) {
6312 if (framesOut > 0) {
6313 activeTrack->mSink.frameCount = framesOut;
6314 activeTrack->releaseBuffer(&activeTrack->mSink);
6315 }
6316 } else {
6317 // FIXME could do a partial drop of framesOut
6318 if (activeTrack->mFramesToDrop > 0) {
6319 activeTrack->mFramesToDrop -= framesOut;
6320 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006321 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006322 }
6323 } else {
6324 activeTrack->mFramesToDrop += framesOut;
6325 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6326 activeTrack->mSyncStartEvent->isCancelled()) {
6327 ALOGW("Synced record %s, session %d, trigger session %d",
6328 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6329 activeTrack->sessionId(),
6330 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006331 activeTrack->mSyncStartEvent->triggerSession() :
6332 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006333 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334 }
6335 }
6336 }
6337
6338 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006339 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006340 }
6341 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006342
6343 switch (overrun) {
6344 case OVERRUN_TRUE:
6345 // client isn't retrieving buffers fast enough
6346 if (!activeTrack->setOverflow()) {
6347 nsecs_t now = systemTime();
6348 // FIXME should lastWarning per track?
6349 if ((now - lastWarning) > kWarningThrottleNs) {
6350 ALOGW("RecordThread: buffer overflow");
6351 lastWarning = now;
6352 }
6353 }
6354 break;
6355 case OVERRUN_FALSE:
6356 activeTrack->clearOverflow();
6357 break;
6358 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006359 break;
6360 }
6361
Andy Hung3f0c9022016-01-15 17:49:46 -08006362 // update frame information and push timestamp out
6363 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006364 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006365 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6366 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006367 }
6368
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006369unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006370 // enable changes in effect chain
6371 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006372 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006373 }
6374
Glenn Kasten93e471f2013-08-19 08:40:07 -07006375 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006376
6377 {
6378 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006379 for (size_t i = 0; i < mTracks.size(); i++) {
6380 sp<RecordTrack> track = mTracks[i];
6381 track->invalidate();
6382 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006383 mActiveTracks.clear();
Eric Laurent9cab7462016-11-10 13:05:20 -08006384 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006385 mStartStopCond.broadcast();
6386 }
6387
6388 releaseWakeLock();
6389
6390 ALOGV("RecordThread %p exiting", this);
6391 return false;
6392}
6393
Glenn Kasten93e471f2013-08-19 08:40:07 -07006394void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006395{
6396 if (!mStandby) {
6397 inputStandBy();
6398 mStandby = true;
6399 }
6400}
6401
6402void AudioFlinger::RecordThread::inputStandBy()
6403{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006404 // Idle the fast capture if it's currently running
6405 if (mFastCapture != 0) {
6406 FastCaptureStateQueue *sq = mFastCapture->sq();
6407 FastCaptureState *state = sq->begin();
6408 if (!(state->mCommand & FastCaptureState::IDLE)) {
6409 state->mCommand = FastCaptureState::COLD_IDLE;
6410 state->mColdFutexAddr = &mFastCaptureFutex;
6411 state->mColdGen++;
6412 mFastCaptureFutex = 0;
6413 sq->end();
6414 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6415 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6416#if 0
6417 if (kUseFastCapture == FastCapture_Dynamic) {
6418 // FIXME
6419 }
6420#endif
6421#ifdef AUDIO_WATCHDOG
6422 // FIXME
6423#endif
6424 } else {
6425 sq->end(false /*didModify*/);
6426 }
6427 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006428 status_t result = mInput->stream->standby();
6429 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006430
6431 // If going into standby, flush the pipe source.
6432 if (mPipeSource.get() != nullptr) {
6433 const ssize_t flushed = mPipeSource->flush();
6434 if (flushed > 0) {
6435 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6436 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6437 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6438 }
6439 }
Eric Laurent81784c32012-11-19 14:55:58 -08006440}
6441
Glenn Kasten05997e22014-03-13 15:08:33 -07006442// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006443sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006444 const sp<AudioFlinger::Client>& client,
6445 uint32_t sampleRate,
6446 audio_format_t format,
6447 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006448 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006449 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006450 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006451 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006452 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006453 pid_t tid,
6454 status_t *status)
6455{
Glenn Kasten74935e42013-12-19 08:56:45 -08006456 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006457 sp<RecordTrack> track;
6458 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006459 audio_input_flags_t inputFlags = mInput->flags;
6460
6461 // special case for FAST flag considered OK if fast capture is present
6462 if (hasFastCapture()) {
6463 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6464 }
6465
6466 // Check if requested flags are compatible with output stream flags
6467 if ((*flags & inputFlags) != *flags) {
6468 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6469 " input flags (%08x)",
6470 *flags, inputFlags);
6471 *flags = (audio_input_flags_t)(*flags & inputFlags);
6472 }
Eric Laurent81784c32012-11-19 14:55:58 -08006473
Glenn Kasten90e58b12013-07-31 16:16:02 -07006474 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006475 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006476 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006477 // we formerly checked for a callback handler (non-0 tid),
6478 // but that is no longer required for TRANSFER_OBTAIN mode
6479 //
Glenn Kasten74105912014-07-03 12:28:53 -07006480 // frame count is not specified, or is exactly the pipe depth
6481 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006482 // PCM data
6483 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006484 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006485 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006486 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006487 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006488 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006489 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006490 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006491 hasFastCapture() &&
6492 // there are sufficient fast track slots available
6493 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006494 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006495 // check compatibility with audio effects.
6496 Mutex::Autolock _l(mLock);
6497 // Do not accept FAST flag if the session has software effects
6498 sp<EffectChain> chain = getEffectChain_l(sessionId);
6499 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006500 audio_input_flags_t old = *flags;
6501 chain->checkInputFlagCompatibility(flags);
6502 if (old != *flags) {
6503 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6504 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006505 }
6506 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006507 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006508 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6509 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006510 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006511 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006512 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006513 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006514 frameCount, mFrameCount, mPipeFramesP2,
6515 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6516 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006517 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006518 }
6519 }
6520
6521 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006522 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006523 // fast track: frame count is exactly the pipe depth
6524 frameCount = mPipeFramesP2;
6525 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6526 *notificationFrames = mFrameCount;
6527 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006528 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6529 // or 20 ms if there is a fast capture
6530 // TODO This could be a roundupRatio inline, and const
6531 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6532 * sampleRate + mSampleRate - 1) / mSampleRate;
6533 // minimum number of notification periods is at least kMinNotifications,
6534 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6535 static const size_t kMinNotifications = 3;
6536 static const uint32_t kMinMs = 30;
6537 // TODO This could be a roundupRatio inline
6538 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6539 // TODO This could be a roundupRatio inline
6540 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6541 maxNotificationFrames;
6542 const size_t minFrameCount = maxNotificationFrames *
6543 max(kMinNotifications, minNotificationsByMs);
6544 frameCount = max(frameCount, minFrameCount);
6545 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6546 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006547 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006548 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006549 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006550
Glenn Kasten15e57982013-09-24 11:52:37 -07006551 lStatus = initCheck();
6552 if (lStatus != NO_ERROR) {
6553 ALOGE("createRecordTrack_l() audio driver not initialized");
6554 goto Exit;
6555 }
Eric Laurent81784c32012-11-19 14:55:58 -08006556
6557 { // scope for mLock
6558 Mutex::Autolock _l(mLock);
6559
6560 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006561 format, channelMask, frameCount, NULL, sessionId, uid,
6562 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006563
Glenn Kasten03003332013-08-06 15:40:54 -07006564 lStatus = track->initCheck();
6565 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006566 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006567 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006568 goto Exit;
6569 }
6570 mTracks.add(track);
6571
6572 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6573 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6574 mAudioFlinger->btNrecIsOff();
6575 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6576 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006577
Eric Laurent05067782016-06-01 18:27:28 -07006578 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006579 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6580 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6581 // so ask activity manager to do this on our behalf
6582 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6583 }
Eric Laurent81784c32012-11-19 14:55:58 -08006584 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006585
Eric Laurent81784c32012-11-19 14:55:58 -08006586 lStatus = NO_ERROR;
6587
6588Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006589 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006590 return track;
6591}
6592
6593status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6594 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006595 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006596{
6597 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6598 sp<ThreadBase> strongMe = this;
6599 status_t status = NO_ERROR;
6600
6601 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006602 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006603 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006604 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006605 triggerSession,
6606 recordTrack->sessionId(),
6607 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006608 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006609 // Sync event can be cancelled by the trigger session if the track is not in a
6610 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006611 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006612 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006613 } else {
6614 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006615 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006616 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006617 }
6618 }
6619
6620 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006621 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006622 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006623 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6624 if (recordTrack->mState == TrackBase::PAUSING) {
6625 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006626 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006627 } else {
6628 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006629 }
6630 return status;
6631 }
6632
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006633 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6634 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6635 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006636 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006637 mActiveTracks.add(recordTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006638 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006639 status_t status = NO_ERROR;
6640 if (recordTrack->isExternalTrack()) {
6641 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006642 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006643 mLock.lock();
6644 // FIXME should verify that recordTrack is still in mActiveTracks
6645 if (status != NO_ERROR) {
6646 mActiveTracks.remove(recordTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006647 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006648 recordTrack->clearSyncStartEvent();
6649 ALOGV("RecordThread::start error %d", status);
6650 return status;
6651 }
Eric Laurent81784c32012-11-19 14:55:58 -08006652 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006653 // Catch up with current buffer indices if thread is already running.
6654 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6655 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6656 // see previously buffered data before it called start(), but with greater risk of overrun.
6657
Andy Hung73c02e42015-03-29 01:13:58 -07006658 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006659 // clear any converter state as new data will be discontinuous
6660 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006661 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006662 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006663 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006664 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006665 ALOGV("Record failed to start");
6666 status = BAD_VALUE;
6667 goto startError;
6668 }
Eric Laurent81784c32012-11-19 14:55:58 -08006669 return status;
6670 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006671
Eric Laurent81784c32012-11-19 14:55:58 -08006672startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006673 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006674 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006675 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006676 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006677 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006678 return status;
6679}
6680
Eric Laurent81784c32012-11-19 14:55:58 -08006681void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6682{
6683 sp<SyncEvent> strongEvent = event.promote();
6684
6685 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006686 sp<RefBase> ptr = strongEvent->cookie().promote();
6687 if (ptr != 0) {
6688 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6689 recordTrack->handleSyncStartEvent(strongEvent);
6690 }
Eric Laurent81784c32012-11-19 14:55:58 -08006691 }
6692}
6693
Glenn Kastena8356f62013-07-25 14:37:52 -07006694bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006695 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006696 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006697 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006698 return false;
6699 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006700 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006701 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006702 // signal thread to stop
6703 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006704 // do not wait for mStartStopCond if exiting
6705 if (exitPending()) {
6706 return true;
6707 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006708 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006709 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006710 // if we have been restarted, recordTrack is in mActiveTracks here
6711 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006712 ALOGV("Record stopped OK");
6713 return true;
6714 }
6715 return false;
6716}
6717
Glenn Kasten0f11b512014-01-31 16:18:54 -08006718bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006719{
6720 return false;
6721}
6722
Glenn Kasten0f11b512014-01-31 16:18:54 -08006723status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006724{
6725#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6726 if (!isValidSyncEvent(event)) {
6727 return BAD_VALUE;
6728 }
6729
Glenn Kastend848eb42016-03-08 13:42:11 -08006730 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006731 status_t ret = NAME_NOT_FOUND;
6732
6733 Mutex::Autolock _l(mLock);
6734
6735 for (size_t i = 0; i < mTracks.size(); i++) {
6736 sp<RecordTrack> track = mTracks[i];
6737 if (eventSession == track->sessionId()) {
6738 (void) track->setSyncEvent(event);
6739 ret = NO_ERROR;
6740 }
6741 }
6742 return ret;
6743#else
6744 return BAD_VALUE;
6745#endif
6746}
6747
6748// destroyTrack_l() must be called with ThreadBase::mLock held
6749void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6750{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006751 track->terminate();
6752 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006753 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006754 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006755 removeTrack_l(track);
6756 }
6757}
6758
6759void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6760{
6761 mTracks.remove(track);
6762 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006763 if (track->isFastTrack()) {
6764 ALOG_ASSERT(!mFastTrackAvail);
6765 mFastTrackAvail = true;
6766 }
Eric Laurent81784c32012-11-19 14:55:58 -08006767}
6768
6769void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6770{
6771 dumpInternals(fd, args);
6772 dumpTracks(fd, args);
6773 dumpEffectChains(fd, args);
6774}
6775
6776void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6777{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006778 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006779
Glenn Kasten44182c22015-03-05 17:12:23 -08006780 dumpBase(fd, args);
6781
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006782 AudioStreamIn *input = mInput;
6783 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6784 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6785 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006786 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006787 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006788 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006789 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006790 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006791
Glenn Kasten2f90c512015-12-02 11:40:09 -08006792 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6793 // while we are dumping it. It may be inconsistent, but it won't mutate!
6794 // This is a large object so we place it on the heap.
6795 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6796 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6797 copy->dump(fd);
6798 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006799}
6800
Glenn Kasten0f11b512014-01-31 16:18:54 -08006801void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006802{
6803 const size_t SIZE = 256;
6804 char buffer[SIZE];
6805 String8 result;
6806
Marco Nelissenb2208842014-02-07 14:00:50 -08006807 size_t numtracks = mTracks.size();
6808 size_t numactive = mActiveTracks.size();
6809 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006810 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006811 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006812 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006813 RecordTrack::appendDumpHeader(result);
6814 for (size_t i = 0; i < numtracks ; ++i) {
6815 sp<RecordTrack> track = mTracks[i];
6816 if (track != 0) {
6817 bool active = mActiveTracks.indexOf(track) >= 0;
6818 if (active) {
6819 numactiveseen++;
6820 }
6821 track->dump(buffer, SIZE, active);
6822 result.append(buffer);
6823 }
Eric Laurent81784c32012-11-19 14:55:58 -08006824 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006825 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006826 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006827 }
6828
Marco Nelissenb2208842014-02-07 14:00:50 -08006829 if (numactiveseen != numactive) {
6830 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6831 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006832 result.append(buffer);
6833 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006834 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006835 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006836 if (mTracks.indexOf(track) < 0) {
6837 track->dump(buffer, SIZE, true);
6838 result.append(buffer);
6839 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006840 }
Eric Laurent81784c32012-11-19 14:55:58 -08006841
6842 }
6843 write(fd, result.string(), result.size());
6844}
6845
Andy Hung73c02e42015-03-29 01:13:58 -07006846
6847void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6848{
6849 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6850 RecordThread *recordThread = (RecordThread *) threadBase.get();
6851 mRsmpInFront = recordThread->mRsmpInRear;
6852 mRsmpInUnrel = 0;
6853}
6854
6855void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6856 size_t *framesAvailable, bool *hasOverrun)
6857{
6858 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6859 RecordThread *recordThread = (RecordThread *) threadBase.get();
6860 const int32_t rear = recordThread->mRsmpInRear;
6861 const int32_t front = mRsmpInFront;
6862 const ssize_t filled = rear - front;
6863
6864 size_t framesIn;
6865 bool overrun = false;
6866 if (filled < 0) {
6867 // should not happen, but treat like a massive overrun and re-sync
6868 framesIn = 0;
6869 mRsmpInFront = rear;
6870 overrun = true;
6871 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6872 framesIn = (size_t) filled;
6873 } else {
6874 // client is not keeping up with server, but give it latest data
6875 framesIn = recordThread->mRsmpInFrames;
6876 mRsmpInFront = /* front = */ rear - framesIn;
6877 overrun = true;
6878 }
6879 if (framesAvailable != NULL) {
6880 *framesAvailable = framesIn;
6881 }
6882 if (hasOverrun != NULL) {
6883 *hasOverrun = overrun;
6884 }
6885}
6886
Eric Laurent81784c32012-11-19 14:55:58 -08006887// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006888status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006889 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006890{
Andy Hung73c02e42015-03-29 01:13:58 -07006891 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006892 if (threadBase == 0) {
6893 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006894 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006895 return NOT_ENOUGH_DATA;
6896 }
6897 RecordThread *recordThread = (RecordThread *) threadBase.get();
6898 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006899 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006900 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006901 // FIXME should not be P2 (don't want to increase latency)
6902 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006903 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006904 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006905 front &= recordThread->mRsmpInFramesP2 - 1;
6906 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006907 if (part1 > (size_t) filled) {
6908 part1 = filled;
6909 }
6910 size_t ask = buffer->frameCount;
6911 ALOG_ASSERT(ask > 0);
6912 if (part1 > ask) {
6913 part1 = ask;
6914 }
6915 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006916 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006917 buffer->raw = NULL;
6918 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006919 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006920 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006921 }
6922
Andy Hung57446612015-04-19 23:56:46 -07006923 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006924 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006925 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006926 return NO_ERROR;
6927}
6928
6929// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006930void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6931 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006932{
Glenn Kasten85948432013-08-19 12:09:05 -07006933 size_t stepCount = buffer->frameCount;
6934 if (stepCount == 0) {
6935 return;
6936 }
Andy Hung73c02e42015-03-29 01:13:58 -07006937 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6938 mRsmpInUnrel -= stepCount;
6939 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006940 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006941 buffer->frameCount = 0;
6942}
6943
Andy Hung97a893e2015-03-29 01:03:07 -07006944AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6945 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6946 uint32_t srcSampleRate,
6947 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6948 uint32_t dstSampleRate) :
6949 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6950 // mSrcFormat
6951 // mSrcSampleRate
6952 // mDstChannelMask
6953 // mDstFormat
6954 // mDstSampleRate
6955 // mSrcChannelCount
6956 // mDstChannelCount
6957 // mDstFrameSize
6958 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006959 mResampler(NULL),
6960 mIsLegacyDownmix(false),
6961 mIsLegacyUpmix(false),
6962 mRequiresFloat(false),
6963 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006964{
6965 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6966 dstChannelMask, dstFormat, dstSampleRate);
6967}
6968
6969AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6970 free(mBuf);
6971 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006972 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006973}
6974
6975size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6976 AudioBufferProvider *provider, size_t frames)
6977{
Andy Hungd330ee42015-04-20 13:23:41 -07006978 if (mInputConverterProvider != NULL) {
6979 mInputConverterProvider->setBufferProvider(provider);
6980 provider = mInputConverterProvider;
6981 }
6982
6983 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006984 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6985 mSrcSampleRate, mSrcFormat, mDstFormat);
6986
6987 AudioBufferProvider::Buffer buffer;
6988 for (size_t i = frames; i > 0; ) {
6989 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006990 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006991 if (status != OK || buffer.frameCount == 0) {
6992 frames -= i; // cannot fill request.
6993 break;
6994 }
Andy Hungd330ee42015-04-20 13:23:41 -07006995 // format convert to destination buffer
6996 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006997
6998 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6999 i -= buffer.frameCount;
7000 provider->releaseBuffer(&buffer);
7001 }
7002 } else {
7003 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7004 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7005
Andy Hungd330ee42015-04-20 13:23:41 -07007006 // reallocate buffer if needed
7007 if (mBufFrameSize != 0 && mBufFrames < frames) {
7008 free(mBuf);
7009 mBufFrames = frames;
7010 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7011 }
Andy Hung97a893e2015-03-29 01:03:07 -07007012 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007013 memset(mBuf, 0, frames * mBufFrameSize);
7014 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7015 // format convert to destination buffer
7016 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007017 }
7018 return frames;
7019}
7020
7021status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7022 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7023 uint32_t srcSampleRate,
7024 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7025 uint32_t dstSampleRate)
7026{
7027 // quick evaluation if there is any change.
7028 if (mSrcFormat == srcFormat
7029 && mSrcChannelMask == srcChannelMask
7030 && mSrcSampleRate == srcSampleRate
7031 && mDstFormat == dstFormat
7032 && mDstChannelMask == dstChannelMask
7033 && mDstSampleRate == dstSampleRate) {
7034 return NO_ERROR;
7035 }
7036
Andy Hungdb4c0312015-05-06 08:46:52 -07007037 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7038 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7039 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007040 const bool valid =
7041 audio_is_input_channel(srcChannelMask)
7042 && audio_is_input_channel(dstChannelMask)
7043 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7044 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7045 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7046 ; // no upsampling checks for now
7047 if (!valid) {
7048 return BAD_VALUE;
7049 }
7050
7051 mSrcFormat = srcFormat;
7052 mSrcChannelMask = srcChannelMask;
7053 mSrcSampleRate = srcSampleRate;
7054 mDstFormat = dstFormat;
7055 mDstChannelMask = dstChannelMask;
7056 mDstSampleRate = dstSampleRate;
7057
7058 // compute derived parameters
7059 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7060 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7061 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7062
Andy Hungd330ee42015-04-20 13:23:41 -07007063 // do we need to resample?
7064 delete mResampler;
7065 mResampler = NULL;
7066 if (mSrcSampleRate != mDstSampleRate) {
7067 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7068 mSrcChannelCount, mDstSampleRate);
7069 mResampler->setSampleRate(mSrcSampleRate);
7070 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7071 }
7072
7073 // are we running legacy channel conversion modes?
7074 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7075 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7076 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7077 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7078 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7079 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7080
7081 // do we need to process in float?
7082 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7083
7084 // do we need a staging buffer to convert for destination (we can still optimize this)?
7085 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7086 if (mResampler != NULL) {
7087 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7088 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007089 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007090 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7091 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007092 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7093 } else {
7094 mBufFrameSize = 0;
7095 }
7096 mBufFrames = 0; // force the buffer to be resized.
7097
Andy Hungd330ee42015-04-20 13:23:41 -07007098 // do we need an input converter buffer provider to give us float?
7099 delete mInputConverterProvider;
7100 mInputConverterProvider = NULL;
7101 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7102 mInputConverterProvider = new ReformatBufferProvider(
7103 audio_channel_count_from_in_mask(mSrcChannelMask),
7104 mSrcFormat,
7105 AUDIO_FORMAT_PCM_FLOAT,
7106 256 /* provider buffer frame count */);
7107 }
7108
7109 // do we need a remixer to do channel mask conversion
7110 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7111 (void) memcpy_by_index_array_initialization_from_channel_mask(
7112 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007113 }
7114 return NO_ERROR;
7115}
7116
Andy Hungd330ee42015-04-20 13:23:41 -07007117void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7118 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007119{
Andy Hungd330ee42015-04-20 13:23:41 -07007120 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007121 if (mBufFrameSize != 0 && mBufFrames < frames) {
7122 free(mBuf);
7123 mBufFrames = frames;
7124 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7125 }
Andy Hungd330ee42015-04-20 13:23:41 -07007126 // do we need to do legacy upmix and downmix?
7127 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007128 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007129 if (mIsLegacyUpmix) {
7130 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7131 (const float *)src, frames);
7132 } else /*mIsLegacyDownmix */ {
7133 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7134 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007135 }
Andy Hungd330ee42015-04-20 13:23:41 -07007136 if (mBuf != NULL) {
7137 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7138 frames * mDstChannelCount);
7139 }
7140 return;
7141 }
7142 // do we need to do channel mask conversion?
7143 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007144 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007145 memcpy_by_index_array(dstBuf, mDstChannelCount,
7146 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7147 if (dstBuf == dst) {
7148 return; // format is the same
7149 }
7150 }
7151 // convert to destination buffer
7152 const void *convertBuf = mBuf != NULL ? mBuf : src;
7153 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7154 frames * mDstChannelCount);
7155}
7156
7157void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7158 void *dst, /*not-a-const*/ void *src, size_t frames)
7159{
7160 // src buffer format is ALWAYS float when entering this routine
7161 if (mIsLegacyUpmix) {
7162 ; // mono to stereo already handled by resampler
7163 } else if (mIsLegacyDownmix
7164 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7165 // the resampler outputs stereo for mono input channel (a feature?)
7166 // must convert to mono
7167 downmix_to_mono_float_from_stereo_float((float *)src,
7168 (const float *)src, frames);
7169 } else if (mSrcChannelMask != mDstChannelMask) {
7170 // convert to mono channel again for channel mask conversion (could be skipped
7171 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007172 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007173 downmix_to_mono_float_from_stereo_float((float *)src,
7174 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007175 }
Andy Hungd330ee42015-04-20 13:23:41 -07007176 // convert to destination format (in place, OK as float is larger than other types)
7177 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7178 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7179 frames * mSrcChannelCount);
7180 }
7181 // channel convert and save to dst
7182 memcpy_by_index_array(dst, mDstChannelCount,
7183 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7184 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007185 }
Andy Hungd330ee42015-04-20 13:23:41 -07007186 // convert to destination format and save to dst
7187 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7188 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007189}
7190
Eric Laurent10351942014-05-08 18:49:52 -07007191bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7192 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007193{
7194 bool reconfig = false;
7195
Eric Laurent10351942014-05-08 18:49:52 -07007196 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007197
Eric Laurent10351942014-05-08 18:49:52 -07007198 audio_format_t reqFormat = mFormat;
7199 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007200 // 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 -07007201 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7202
7203 AudioParameter param = AudioParameter(keyValuePair);
7204 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007205
7206 // scope for AutoPark extends to end of method
7207 AutoPark<FastCapture> park(mFastCapture);
7208
Eric Laurent10351942014-05-08 18:49:52 -07007209 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7210 // channel count change can be requested. Do we mandate the first client defines the
7211 // HAL sampling rate and channel count or do we allow changes on the fly?
7212 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7213 samplingRate = value;
7214 reconfig = true;
7215 }
7216 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007217 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007218 status = BAD_VALUE;
7219 } else {
7220 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007221 reconfig = true;
7222 }
Eric Laurent10351942014-05-08 18:49:52 -07007223 }
7224 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7225 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007226 if (!audio_is_input_channel(mask) ||
7227 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007228 status = BAD_VALUE;
7229 } else {
7230 channelMask = mask;
7231 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007232 }
Eric Laurent10351942014-05-08 18:49:52 -07007233 }
7234 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7235 // do not accept frame count changes if tracks are open as the track buffer
7236 // size depends on frame count and correct behavior would not be guaranteed
7237 // if frame count is changed after track creation
7238 if (mActiveTracks.size() > 0) {
7239 status = INVALID_OPERATION;
7240 } else {
7241 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007242 }
Eric Laurent10351942014-05-08 18:49:52 -07007243 }
7244 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7245 // forward device change to effects that have requested to be
7246 // aware of attached audio device.
7247 for (size_t i = 0; i < mEffectChains.size(); i++) {
7248 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007249 }
Eric Laurent81784c32012-11-19 14:55:58 -08007250
Eric Laurent10351942014-05-08 18:49:52 -07007251 // store input device and output device but do not forward output device to audio HAL.
7252 // Note that status is ignored by the caller for output device
7253 // (see AudioFlinger::setParameters()
7254 if (audio_is_output_devices(value)) {
7255 mOutDevice = value;
7256 status = BAD_VALUE;
7257 } else {
7258 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007259 if (value != AUDIO_DEVICE_NONE) {
7260 mPrevInDevice = value;
7261 }
Eric Laurent10351942014-05-08 18:49:52 -07007262 // disable AEC and NS if the device is a BT SCO headset supporting those
7263 // pre processings
7264 if (mTracks.size() > 0) {
7265 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7266 mAudioFlinger->btNrecIsOff();
7267 for (size_t i = 0; i < mTracks.size(); i++) {
7268 sp<RecordTrack> track = mTracks[i];
7269 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7270 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007271 }
7272 }
7273 }
Eric Laurent10351942014-05-08 18:49:52 -07007274 }
7275 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7276 mAudioSource != (audio_source_t)value) {
7277 // forward device change to effects that have requested to be
7278 // aware of attached audio device.
7279 for (size_t i = 0; i < mEffectChains.size(); i++) {
7280 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007281 }
Eric Laurent10351942014-05-08 18:49:52 -07007282 mAudioSource = (audio_source_t)value;
7283 }
Glenn Kastene198c362013-08-13 09:13:36 -07007284
Eric Laurent10351942014-05-08 18:49:52 -07007285 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007286 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007287 if (status == INVALID_OPERATION) {
7288 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007289 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007290 }
7291 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007292 if (status == BAD_VALUE) {
7293 uint32_t sRate;
7294 audio_channel_mask_t channelMask;
7295 audio_format_t format;
7296 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7297 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7298 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7299 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7300 status = NO_ERROR;
7301 }
Eric Laurent81784c32012-11-19 14:55:58 -08007302 }
Eric Laurent10351942014-05-08 18:49:52 -07007303 if (status == NO_ERROR) {
7304 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007305 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007306 }
7307 }
Eric Laurent81784c32012-11-19 14:55:58 -08007308 }
Eric Laurent10351942014-05-08 18:49:52 -07007309
Eric Laurent81784c32012-11-19 14:55:58 -08007310 return reconfig;
7311}
7312
7313String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7314{
Eric Laurent81784c32012-11-19 14:55:58 -08007315 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007316 if (initCheck() == NO_ERROR) {
7317 String8 out_s8;
7318 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7319 return out_s8;
7320 }
Eric Laurent81784c32012-11-19 14:55:58 -08007321 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007322 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007323}
7324
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007325void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007326 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7327
7328 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007329
7330 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007331 case AUDIO_INPUT_OPENED:
7332 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007333 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007334 desc->mChannelMask = mChannelMask;
7335 desc->mSamplingRate = mSampleRate;
7336 desc->mFormat = mFormat;
7337 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007338 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007339 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007340 break;
7341
Eric Laurent73e26b62015-04-27 16:55:58 -07007342 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007343 default:
7344 break;
7345 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007346 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007347}
7348
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007349void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007350{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007351 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7352 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007353 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007354 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007355 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007356 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7357 result = mInput->stream->getFrameSize(&mFrameSize);
7358 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7359 result = mInput->stream->getBufferSize(&mBufferSize);
7360 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007361 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007362 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007363 // 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 -07007364 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007365 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007366 // A larger value should allow more old data to be read after a track calls start(),
7367 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007368 //
7369 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007370 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007371 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007372 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007373 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007374
7375 // TODO optimize audio capture buffer sizes ...
7376 // Here we calculate the size of the sliding buffer used as a source
7377 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7378 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7379 // be better to have it derived from the pipe depth in the long term.
7380 // The current value is higher than necessary. However it should not add to latency.
7381
Glenn Kasten85948432013-08-19 12:09:05 -07007382 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007383 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7384 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7385 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007386
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007387 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7388 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007389}
7390
Glenn Kasten5f972c02014-01-13 09:59:31 -08007391uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007392{
7393 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007394 uint32_t result;
7395 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7396 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007397 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007398 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007399}
7400
Eric Laurent4c415062016-06-17 16:14:16 -07007401// hasAudioSession_l() must be called with ThreadBase::mLock held
7402uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007403{
Eric Laurent81784c32012-11-19 14:55:58 -08007404 uint32_t result = 0;
7405 if (getEffectChain_l(sessionId) != 0) {
7406 result = EFFECT_SESSION;
7407 }
7408
7409 for (size_t i = 0; i < mTracks.size(); ++i) {
7410 if (sessionId == mTracks[i]->sessionId()) {
7411 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007412 if (mTracks[i]->isFastTrack()) {
7413 result |= FAST_SESSION;
7414 }
Eric Laurent81784c32012-11-19 14:55:58 -08007415 break;
7416 }
7417 }
7418
7419 return result;
7420}
7421
Glenn Kastend848eb42016-03-08 13:42:11 -08007422KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007423{
Glenn Kastend848eb42016-03-08 13:42:11 -08007424 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007425 Mutex::Autolock _l(mLock);
7426 for (size_t j = 0; j < mTracks.size(); ++j) {
7427 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007428 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007429 if (ids.indexOfKey(sessionId) < 0) {
7430 ids.add(sessionId, true);
7431 }
7432 }
7433 return ids;
7434}
7435
7436AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7437{
7438 Mutex::Autolock _l(mLock);
7439 AudioStreamIn *input = mInput;
7440 mInput = NULL;
7441 return input;
7442}
7443
7444// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007445sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007446{
7447 if (mInput == NULL) {
7448 return NULL;
7449 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007450 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007451}
7452
7453status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7454{
7455 // only one chain per input thread
7456 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007457 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007458 return INVALID_OPERATION;
7459 }
7460 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007461 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007462 chain->setInBuffer(NULL);
7463 chain->setOutBuffer(NULL);
7464
7465 checkSuspendOnAddEffectChain_l(chain);
7466
Eric Laurent1b928682014-10-02 19:41:47 -07007467 // make sure enabled pre processing effects state is communicated to the HAL as we
7468 // just moved them to a new input stream.
7469 chain->syncHalEffectsState();
7470
Eric Laurent81784c32012-11-19 14:55:58 -08007471 mEffectChains.add(chain);
7472
7473 return NO_ERROR;
7474}
7475
7476size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7477{
7478 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7479 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007480 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007481 chain.get(), mEffectChains.size(), this);
7482 if (mEffectChains.size() == 1) {
7483 mEffectChains.removeAt(0);
7484 }
7485 return 0;
7486}
7487
Eric Laurent1c333e22014-05-20 10:48:17 -07007488status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7489 audio_patch_handle_t *handle)
7490{
7491 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007492
7493 // store new device and send to effects
7494 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007495 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007496 for (size_t i = 0; i < mEffectChains.size(); i++) {
7497 mEffectChains[i]->setDevice_l(mInDevice);
7498 }
7499
7500 // disable AEC and NS if the device is a BT SCO headset supporting those
7501 // pre processings
7502 if (mTracks.size() > 0) {
7503 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7504 mAudioFlinger->btNrecIsOff();
7505 for (size_t i = 0; i < mTracks.size(); i++) {
7506 sp<RecordTrack> track = mTracks[i];
7507 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7508 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7509 }
7510 }
7511
7512 // store new source and send to effects
7513 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7514 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007515 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007516 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007517 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007518 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007519
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007520 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007521 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7522 status = hwDevice->createAudioPatch(patch->num_sources,
7523 patch->sources,
7524 patch->num_sinks,
7525 patch->sinks,
7526 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007527 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007528 char *address;
7529 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7530 address = audio_device_address_to_parameter(
7531 patch->sources[0].ext.device.type,
7532 patch->sources[0].ext.device.address);
7533 } else {
7534 address = (char *)calloc(1, 1);
7535 }
7536 AudioParameter param = AudioParameter(String8(address));
7537 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007538 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007539 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007540 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007541 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007542 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007543 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007544 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007545
Eric Laurente8726fe2015-06-26 09:39:24 -07007546 if (mInDevice != mPrevInDevice) {
7547 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7548 mPrevInDevice = mInDevice;
7549 }
Eric Laurent296fb132015-05-01 11:38:42 -07007550
Eric Laurent1c333e22014-05-20 10:48:17 -07007551 return status;
7552}
7553
7554status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7555{
7556 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007557
7558 mInDevice = AUDIO_DEVICE_NONE;
7559
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007560 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007561 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7562 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007563 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007564 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007565 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007566 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007567 }
7568 return status;
7569}
7570
Eric Laurent83b88082014-06-20 18:31:16 -07007571void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7572{
7573 Mutex::Autolock _l(mLock);
7574 mTracks.add(record);
7575}
7576
7577void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7578{
7579 Mutex::Autolock _l(mLock);
7580 destroyTrack_l(record);
7581}
7582
7583void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7584{
7585 ThreadBase::getAudioPortConfig(config);
7586 config->role = AUDIO_PORT_ROLE_SINK;
7587 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7588 config->ext.mix.usecase.source = mAudioSource;
7589}
Eric Laurent1c333e22014-05-20 10:48:17 -07007590
Glenn Kasten63238ef2015-03-02 15:50:29 -08007591} // namespace android