blob: 50520945b1b0ded473e3dc8e92ad3d43c09eaae4 [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)),
Andy Hung2f366df2016-10-31 14:01:16 -0700511 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800512{
Eric Laurent296fb132015-05-01 11:38:42 -0700513 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800514}
515
516AudioFlinger::ThreadBase::~ThreadBase()
517{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700518 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 mConfigEvents.clear();
520
Eric Laurent81784c32012-11-19 14:55:58 -0800521 // do not lock the mutex in destructor
522 releaseWakeLock_l();
523 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800524 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800525 binder->unlinkToDeath(mDeathRecipient);
526 }
527}
528
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700529status_t AudioFlinger::ThreadBase::readyToRun()
530{
531 status_t status = initCheck();
532 if (status == NO_ERROR) {
533 ALOGI("AudioFlinger's thread %p ready to run", this);
534 } else {
535 ALOGE("No working audio driver found.");
536 }
537 return status;
538}
539
Eric Laurent81784c32012-11-19 14:55:58 -0800540void AudioFlinger::ThreadBase::exit()
541{
542 ALOGV("ThreadBase::exit");
543 // do any cleanup required for exit to succeed
544 preExit();
545 {
546 // This lock prevents the following race in thread (uniprocessor for illustration):
547 // if (!exitPending()) {
548 // // context switch from here to exit()
549 // // exit() calls requestExit(), what exitPending() observes
550 // // exit() calls signal(), which is dropped since no waiters
551 // // context switch back from exit() to here
552 // mWaitWorkCV.wait(...);
553 // // now thread is hung
554 // }
555 AutoMutex lock(mLock);
556 requestExit();
557 mWaitWorkCV.broadcast();
558 }
559 // When Thread::requestExitAndWait is made virtual and this method is renamed to
560 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
561 requestExitAndWait();
562}
563
564status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
565{
Eric Laurent81784c32012-11-19 14:55:58 -0800566 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
567 Mutex::Autolock _l(mLock);
568
Eric Laurent10351942014-05-08 18:49:52 -0700569 return sendSetParameterConfigEvent_l(keyValuePairs);
570}
571
572// sendConfigEvent_l() must be called with ThreadBase::mLock held
573// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
574status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
575{
576 status_t status = NO_ERROR;
577
Eric Laurent72e3f392015-05-20 14:43:50 -0700578 if (event->mRequiresSystemReady && !mSystemReady) {
579 event->mWaitStatus = false;
580 mPendingConfigEvents.add(event);
581 return status;
582 }
Eric Laurent10351942014-05-08 18:49:52 -0700583 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700584 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800585 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700586 mLock.unlock();
587 {
588 Mutex::Autolock _l(event->mLock);
589 while (event->mWaitStatus) {
590 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
591 event->mStatus = TIMED_OUT;
592 event->mWaitStatus = false;
593 }
594 }
595 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800596 }
Eric Laurent10351942014-05-08 18:49:52 -0700597 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800598 return status;
599}
600
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700601void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800602{
603 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700604 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800605}
606
607// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700608void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800609{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700610 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700611 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800612}
613
Eric Laurent72e3f392015-05-20 14:43:50 -0700614void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
615{
616 Mutex::Autolock _l(mLock);
617 sendPrioConfigEvent_l(pid, tid, prio);
618}
619
Eric Laurent81784c32012-11-19 14:55:58 -0800620// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
621void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
622{
Eric Laurent10351942014-05-08 18:49:52 -0700623 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
624 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800625}
626
Eric Laurent10351942014-05-08 18:49:52 -0700627// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
628status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800629{
Andy Hung2ddee192015-12-18 17:34:44 -0800630 sp<ConfigEvent> configEvent;
631 AudioParameter param(keyValuePair);
632 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700633 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800634 setMasterMono_l(value != 0);
635 if (param.size() == 1) {
636 return NO_ERROR; // should be a solo parameter - we don't pass down
637 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700638 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800639 configEvent = new SetParameterConfigEvent(param.toString());
640 } else {
641 configEvent = new SetParameterConfigEvent(keyValuePair);
642 }
Eric Laurent10351942014-05-08 18:49:52 -0700643 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700644}
645
Eric Laurent1c333e22014-05-20 10:48:17 -0700646status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
647 const struct audio_patch *patch,
648 audio_patch_handle_t *handle)
649{
650 Mutex::Autolock _l(mLock);
651 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
652 status_t status = sendConfigEvent_l(configEvent);
653 if (status == NO_ERROR) {
654 CreateAudioPatchConfigEventData *data =
655 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
656 *handle = data->mHandle;
657 }
658 return status;
659}
660
661status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
662 const audio_patch_handle_t handle)
663{
664 Mutex::Autolock _l(mLock);
665 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
666 return sendConfigEvent_l(configEvent);
667}
668
669
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700670// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700671void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700672{
Eric Laurent10351942014-05-08 18:49:52 -0700673 bool configChanged = false;
674
Eric Laurent81784c32012-11-19 14:55:58 -0800675 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700676 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700677 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800678 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700679 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700680 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700681 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
682 // FIXME Need to understand why this has to be done asynchronously
683 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700684 true /*asynchronous*/);
685 if (err != 0) {
686 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700687 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700688 }
689 } break;
690 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700691 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700692 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700693 } break;
694 case CFG_EVENT_SET_PARAMETER: {
695 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
696 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
697 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700698 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700699 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700700 case CFG_EVENT_CREATE_AUDIO_PATCH: {
701 CreateAudioPatchConfigEventData *data =
702 (CreateAudioPatchConfigEventData *)event->mData.get();
703 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
704 } break;
705 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
706 ReleaseAudioPatchConfigEventData *data =
707 (ReleaseAudioPatchConfigEventData *)event->mData.get();
708 event->mStatus = releaseAudioPatch_l(data->mHandle);
709 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700710 default:
Eric Laurent10351942014-05-08 18:49:52 -0700711 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700712 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800713 }
Eric Laurent10351942014-05-08 18:49:52 -0700714 {
715 Mutex::Autolock _l(event->mLock);
716 if (event->mWaitStatus) {
717 event->mWaitStatus = false;
718 event->mCond.signal();
719 }
720 }
721 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
722 }
723
724 if (configChanged) {
725 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800726 }
Eric Laurent81784c32012-11-19 14:55:58 -0800727}
728
Marco Nelissenb2208842014-02-07 14:00:50 -0800729String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
730 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700731 const audio_channel_representation_t representation =
732 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700733
734 switch (representation) {
735 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
736 if (output) {
737 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
738 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
739 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
740 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
741 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
742 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
743 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
744 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
745 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
746 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
747 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
748 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
749 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
750 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
751 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
753 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
754 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
755 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
756 } else {
757 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
758 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
759 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
760 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
761 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
762 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
763 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
764 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
765 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
766 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
767 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
768 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
769 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
770 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
771 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
772 }
773 const int len = s.length();
774 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700775 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700776 s.unlockBuffer(len - 2); // remove trailing ", "
777 }
778 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800779 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700780 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
781 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
782 return s;
783 default:
784 s.appendFormat("unknown mask, representation:%d bits:%#x",
785 representation, audio_channel_mask_get_bits(mask));
786 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800787 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800788}
789
Glenn Kasten0f11b512014-01-31 16:18:54 -0800790void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800791{
792 const size_t SIZE = 256;
793 char buffer[SIZE];
794 String8 result;
795
796 bool locked = AudioFlinger::dumpTryLock(mLock);
797 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700798 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800799 }
800
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800801 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700802 dprintf(fd, " I/O handle: %d\n", mId);
803 dprintf(fd, " TID: %d\n", getTid());
804 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700805 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700806 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700807 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700808 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700809 dprintf(fd, " Channel count: %u\n", mChannelCount);
810 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800811 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700812 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700813 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700814 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800815 size_t numConfig = mConfigEvents.size();
816 if (numConfig) {
817 for (size_t i = 0; i < numConfig; i++) {
818 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800820 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800822 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800824 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700825 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
826 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800827 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800828
829 if (locked) {
830 mLock.unlock();
831 }
832}
833
834void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
835{
836 const size_t SIZE = 256;
837 char buffer[SIZE];
838 String8 result;
839
Marco Nelissenb2208842014-02-07 14:00:50 -0800840 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000841 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800842 write(fd, buffer, strlen(buffer));
843
Marco Nelissenb2208842014-02-07 14:00:50 -0800844 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800845 sp<EffectChain> chain = mEffectChains[i];
846 if (chain != 0) {
847 chain->dump(fd, args);
848 }
849 }
850}
851
Andy Hung2f366df2016-10-31 14:01:16 -0700852void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800853{
854 Mutex::Autolock _l(mLock);
Andy Hung2f366df2016-10-31 14:01:16 -0700855 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800856}
857
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100858String16 AudioFlinger::ThreadBase::getWakeLockTag()
859{
860 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800861 case MIXER:
862 return String16("AudioMix");
863 case DIRECT:
864 return String16("AudioDirectOut");
865 case DUPLICATING:
866 return String16("AudioDup");
867 case RECORD:
868 return String16("AudioIn");
869 case OFFLOAD:
870 return String16("AudioOffload");
871 default:
872 ALOG_ASSERT(false);
873 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100874 }
875}
876
Andy Hung2f366df2016-10-31 14:01:16 -0700877void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800878{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800879 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800880 if (mPowerManager != 0) {
881 sp<IBinder> binder = new BBinder();
Andy Hung2f366df2016-10-31 14:01:16 -0700882 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
883 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700884 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100885 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700886 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700887 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800888 if (status == NO_ERROR) {
889 mWakeLockToken = binder;
890 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800891 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800892 }
Wei Jia3f273d12015-11-24 09:06:49 -0800893
Andy Hung3f0c9022016-01-15 17:49:46 -0800894 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800895 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
896 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800897}
898
899void AudioFlinger::ThreadBase::releaseWakeLock()
900{
901 Mutex::Autolock _l(mLock);
902 releaseWakeLock_l();
903}
904
905void AudioFlinger::ThreadBase::releaseWakeLock_l()
906{
Andy Hung3f0c9022016-01-15 17:49:46 -0800907 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800908 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800909 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700911 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
912 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800913 }
914 mWakeLockToken.clear();
915 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800916}
917
918void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700919 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800920 // use checkService() to avoid blocking if power service is not up yet
921 sp<IBinder> binder =
922 defaultServiceManager()->checkService(String16("power"));
923 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800924 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800925 } else {
926 mPowerManager = interface_cast<IPowerManager>(binder);
927 binder->linkToDeath(mDeathRecipient);
928 }
929 }
930}
931
Andy Hung1f12a8a2016-11-07 16:10:30 -0800932void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800933 getPowerManager_l();
Andy Hung2f366df2016-10-31 14:01:16 -0700934
935#if !LOG_NDEBUG
936 std::stringstream s;
Andy Hung1f12a8a2016-11-07 16:10:30 -0800937 for (uid_t uid : uids) {
Andy Hung2f366df2016-10-31 14:01:16 -0700938 s << uid << " ";
939 }
940 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
941#endif
942
Andy Hung438e7572015-12-14 15:51:17 -0800943 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
944 if (mSystemReady) {
945 ALOGE("no wake lock to update, but system ready!");
946 } else {
947 ALOGW("no wake lock to update, system not ready yet");
948 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800949 return;
950 }
951 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800952 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
953 status_t status = mPowerManager->updateWakeLockUids(
954 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
955 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800956 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957 }
958}
959
Eric Laurent81784c32012-11-19 14:55:58 -0800960void AudioFlinger::ThreadBase::clearPowerManager()
961{
962 Mutex::Autolock _l(mLock);
963 releaseWakeLock_l();
964 mPowerManager.clear();
965}
966
Glenn Kasten0f11b512014-01-31 16:18:54 -0800967void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800968{
969 sp<ThreadBase> thread = mThread.promote();
970 if (thread != 0) {
971 thread->clearPowerManager();
972 }
973 ALOGW("power manager service died !!!");
974}
975
976void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800977 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800978{
979 Mutex::Autolock _l(mLock);
980 setEffectSuspended_l(type, suspend, sessionId);
981}
982
983void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800984 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800985{
986 sp<EffectChain> chain = getEffectChain_l(sessionId);
987 if (chain != 0) {
988 if (type != NULL) {
989 chain->setEffectSuspended_l(type, suspend);
990 } else {
991 chain->setEffectSuspendedAll_l(suspend);
992 }
993 }
994
995 updateSuspendedSessions_l(type, suspend, sessionId);
996}
997
998void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
999{
1000 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1001 if (index < 0) {
1002 return;
1003 }
1004
1005 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1006 mSuspendedSessions.valueAt(index);
1007
1008 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001009 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001010 for (int j = 0; j < desc->mRefCount; j++) {
1011 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1012 chain->setEffectSuspendedAll_l(true);
1013 } else {
1014 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1015 desc->mType.timeLow);
1016 chain->setEffectSuspended_l(&desc->mType, true);
1017 }
1018 }
1019 }
1020}
1021
1022void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1023 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001024 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001025{
1026 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1027
1028 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1029
1030 if (suspend) {
1031 if (index >= 0) {
1032 sessionEffects = mSuspendedSessions.valueAt(index);
1033 } else {
1034 mSuspendedSessions.add(sessionId, sessionEffects);
1035 }
1036 } else {
1037 if (index < 0) {
1038 return;
1039 }
1040 sessionEffects = mSuspendedSessions.valueAt(index);
1041 }
1042
1043
1044 int key = EffectChain::kKeyForSuspendAll;
1045 if (type != NULL) {
1046 key = type->timeLow;
1047 }
1048 index = sessionEffects.indexOfKey(key);
1049
1050 sp<SuspendedSessionDesc> desc;
1051 if (suspend) {
1052 if (index >= 0) {
1053 desc = sessionEffects.valueAt(index);
1054 } else {
1055 desc = new SuspendedSessionDesc();
1056 if (type != NULL) {
1057 desc->mType = *type;
1058 }
1059 sessionEffects.add(key, desc);
1060 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1061 }
1062 desc->mRefCount++;
1063 } else {
1064 if (index < 0) {
1065 return;
1066 }
1067 desc = sessionEffects.valueAt(index);
1068 if (--desc->mRefCount == 0) {
1069 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1070 sessionEffects.removeItemsAt(index);
1071 if (sessionEffects.isEmpty()) {
1072 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1073 sessionId);
1074 mSuspendedSessions.removeItem(sessionId);
1075 }
1076 }
1077 }
1078 if (!sessionEffects.isEmpty()) {
1079 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1080 }
1081}
1082
1083void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1084 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001085 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001086{
1087 Mutex::Autolock _l(mLock);
1088 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1089}
1090
1091void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1092 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001093 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001094{
1095 if (mType != RECORD) {
1096 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1097 // another session. This gives the priority to well behaved effect control panels
1098 // and applications not using global effects.
1099 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1100 // global effects
1101 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1102 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1103 }
1104 }
1105
1106 sp<EffectChain> chain = getEffectChain_l(sessionId);
1107 if (chain != 0) {
1108 chain->checkSuspendOnEffectEnabled(effect, enabled);
1109 }
1110}
1111
Eric Laurent4c415062016-06-17 16:14:16 -07001112// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1113status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1114 const effect_descriptor_t *desc, audio_session_t sessionId)
1115{
1116 // No global effect sessions on record threads
1117 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1118 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1119 desc->name, mThreadName);
1120 return BAD_VALUE;
1121 }
1122 // only pre processing effects on record thread
1123 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1124 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1125 desc->name, mThreadName);
1126 return BAD_VALUE;
1127 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001128
1129 // always allow effects without processing load or latency
1130 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1131 return NO_ERROR;
1132 }
1133
Eric Laurent4c415062016-06-17 16:14:16 -07001134 audio_input_flags_t flags = mInput->flags;
1135 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1136 if (flags & AUDIO_INPUT_FLAG_RAW) {
1137 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1138 desc->name, mThreadName);
1139 return BAD_VALUE;
1140 }
1141 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1142 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1143 desc->name, mThreadName);
1144 return BAD_VALUE;
1145 }
1146 }
1147 return NO_ERROR;
1148}
1149
1150// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1151status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1152 const effect_descriptor_t *desc, audio_session_t sessionId)
1153{
1154 // no preprocessing on playback threads
1155 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1156 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1157 " thread %s", desc->name, mThreadName);
1158 return BAD_VALUE;
1159 }
1160
1161 switch (mType) {
1162 case MIXER: {
1163 // Reject any effect on mixer multichannel sinks.
1164 // TODO: fix both format and multichannel issues with effects.
1165 if (mChannelCount != FCC_2) {
1166 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1167 " thread %s", desc->name, mChannelCount, mThreadName);
1168 return BAD_VALUE;
1169 }
1170 audio_output_flags_t flags = mOutput->flags;
1171 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1172 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1173 // global effects are applied only to non fast tracks if they are SW
1174 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1175 break;
1176 }
1177 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1178 // only post processing on output stage session
1179 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1180 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1181 " on output stage session", desc->name);
1182 return BAD_VALUE;
1183 }
1184 } else {
1185 // no restriction on effects applied on non fast tracks
1186 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1187 break;
1188 }
1189 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001190
1191 // always allow effects without processing load or latency
1192 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1193 break;
1194 }
Eric Laurent4c415062016-06-17 16:14:16 -07001195 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1196 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1197 desc->name);
1198 return BAD_VALUE;
1199 }
1200 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1201 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1202 " in fast mode", desc->name);
1203 return BAD_VALUE;
1204 }
1205 }
1206 } break;
1207 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001208 // nothing actionable on offload threads, if the effect:
1209 // - is offloadable: the effect can be created
1210 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1211 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001212 break;
1213 case DIRECT:
1214 // Reject any effect on Direct output threads for now, since the format of
1215 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1216 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1217 desc->name, mThreadName);
1218 return BAD_VALUE;
1219 case DUPLICATING:
1220 // Reject any effect on mixer multichannel sinks.
1221 // TODO: fix both format and multichannel issues with effects.
1222 if (mChannelCount != FCC_2) {
1223 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1224 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1225 return BAD_VALUE;
1226 }
1227 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1228 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1229 " thread %s", desc->name, mThreadName);
1230 return BAD_VALUE;
1231 }
1232 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1233 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1234 " DUPLICATING thread %s", desc->name, mThreadName);
1235 return BAD_VALUE;
1236 }
1237 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1238 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1239 " DUPLICATING thread %s", desc->name, mThreadName);
1240 return BAD_VALUE;
1241 }
1242 break;
1243 default:
1244 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1245 }
1246
1247 return NO_ERROR;
1248}
1249
Eric Laurent81784c32012-11-19 14:55:58 -08001250// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1251sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1252 const sp<AudioFlinger::Client>& client,
1253 const sp<IEffectClient>& effectClient,
1254 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001255 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001256 effect_descriptor_t *desc,
1257 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001258 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001259{
1260 sp<EffectModule> effect;
1261 sp<EffectHandle> handle;
1262 status_t lStatus;
1263 sp<EffectChain> chain;
1264 bool chainCreated = false;
1265 bool effectCreated = false;
1266 bool effectRegistered = false;
1267
1268 lStatus = initCheck();
1269 if (lStatus != NO_ERROR) {
1270 ALOGW("createEffect_l() Audio driver not initialized.");
1271 goto Exit;
1272 }
1273
Eric Laurent81784c32012-11-19 14:55:58 -08001274 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1275
1276 { // scope for mLock
1277 Mutex::Autolock _l(mLock);
1278
Eric Laurent4c415062016-06-17 16:14:16 -07001279 lStatus = checkEffectCompatibility_l(desc, sessionId);
1280 if (lStatus != NO_ERROR) {
1281 goto Exit;
1282 }
1283
Eric Laurent81784c32012-11-19 14:55:58 -08001284 // check for existing effect chain with the requested audio session
1285 chain = getEffectChain_l(sessionId);
1286 if (chain == 0) {
1287 // create a new chain for this session
1288 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1289 chain = new EffectChain(this, sessionId);
1290 addEffectChain_l(chain);
1291 chain->setStrategy(getStrategyForSession_l(sessionId));
1292 chainCreated = true;
1293 } else {
1294 effect = chain->getEffectFromDesc_l(desc);
1295 }
1296
1297 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1298
1299 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001300 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001301 // Check CPU and memory usage
1302 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1303 if (lStatus != NO_ERROR) {
1304 goto Exit;
1305 }
1306 effectRegistered = true;
1307 // create a new effect module if none present in the chain
1308 effect = new EffectModule(this, chain, desc, id, sessionId);
1309 lStatus = effect->status();
1310 if (lStatus != NO_ERROR) {
1311 goto Exit;
1312 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001313 effect->setOffloaded(mType == OFFLOAD, mId);
1314
Eric Laurent81784c32012-11-19 14:55:58 -08001315 lStatus = chain->addEffect_l(effect);
1316 if (lStatus != NO_ERROR) {
1317 goto Exit;
1318 }
1319 effectCreated = true;
1320
1321 effect->setDevice(mOutDevice);
1322 effect->setDevice(mInDevice);
1323 effect->setMode(mAudioFlinger->getMode());
1324 effect->setAudioSource(mAudioSource);
1325 }
1326 // create effect handle and connect it to effect module
1327 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001328 lStatus = handle->initCheck();
1329 if (lStatus == OK) {
1330 lStatus = effect->addHandle(handle.get());
1331 }
Eric Laurent81784c32012-11-19 14:55:58 -08001332 if (enabled != NULL) {
1333 *enabled = (int)effect->isEnabled();
1334 }
1335 }
1336
1337Exit:
1338 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1339 Mutex::Autolock _l(mLock);
1340 if (effectCreated) {
1341 chain->removeEffect_l(effect);
1342 }
1343 if (effectRegistered) {
1344 AudioSystem::unregisterEffect(effect->id());
1345 }
1346 if (chainCreated) {
1347 removeEffectChain_l(chain);
1348 }
1349 handle.clear();
1350 }
1351
Glenn Kasten9156ef32013-08-06 15:39:08 -07001352 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001353 return handle;
1354}
1355
Glenn Kastend848eb42016-03-08 13:42:11 -08001356sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1357 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001358{
1359 Mutex::Autolock _l(mLock);
1360 return getEffect_l(sessionId, effectId);
1361}
1362
Glenn Kastend848eb42016-03-08 13:42:11 -08001363sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1364 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001365{
1366 sp<EffectChain> chain = getEffectChain_l(sessionId);
1367 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1368}
1369
1370// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1371// PlaybackThread::mLock held
1372status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1373{
1374 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001375 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001376 sp<EffectChain> chain = getEffectChain_l(sessionId);
1377 bool chainCreated = false;
1378
Eric Laurent5baf2af2013-09-12 17:37:00 -07001379 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1380 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1381 this, effect->desc().name, effect->desc().flags);
1382
Eric Laurent81784c32012-11-19 14:55:58 -08001383 if (chain == 0) {
1384 // create a new chain for this session
1385 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1386 chain = new EffectChain(this, sessionId);
1387 addEffectChain_l(chain);
1388 chain->setStrategy(getStrategyForSession_l(sessionId));
1389 chainCreated = true;
1390 }
1391 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1392
1393 if (chain->getEffectFromId_l(effect->id()) != 0) {
1394 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1395 this, effect->desc().name, chain.get());
1396 return BAD_VALUE;
1397 }
1398
Eric Laurent5baf2af2013-09-12 17:37:00 -07001399 effect->setOffloaded(mType == OFFLOAD, mId);
1400
Eric Laurent81784c32012-11-19 14:55:58 -08001401 status_t status = chain->addEffect_l(effect);
1402 if (status != NO_ERROR) {
1403 if (chainCreated) {
1404 removeEffectChain_l(chain);
1405 }
1406 return status;
1407 }
1408
1409 effect->setDevice(mOutDevice);
1410 effect->setDevice(mInDevice);
1411 effect->setMode(mAudioFlinger->getMode());
1412 effect->setAudioSource(mAudioSource);
1413 return NO_ERROR;
1414}
1415
1416void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1417
1418 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1419 effect_descriptor_t desc = effect->desc();
1420 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1421 detachAuxEffect_l(effect->id());
1422 }
1423
1424 sp<EffectChain> chain = effect->chain().promote();
1425 if (chain != 0) {
1426 // remove effect chain if removing last effect
1427 if (chain->removeEffect_l(effect) == 0) {
1428 removeEffectChain_l(chain);
1429 }
1430 } else {
1431 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1432 }
1433}
1434
1435void AudioFlinger::ThreadBase::lockEffectChains_l(
1436 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1437{
1438 effectChains = mEffectChains;
1439 for (size_t i = 0; i < mEffectChains.size(); i++) {
1440 mEffectChains[i]->lock();
1441 }
1442}
1443
1444void AudioFlinger::ThreadBase::unlockEffectChains(
1445 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1446{
1447 for (size_t i = 0; i < effectChains.size(); i++) {
1448 effectChains[i]->unlock();
1449 }
1450}
1451
Glenn Kastend848eb42016-03-08 13:42:11 -08001452sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001453{
1454 Mutex::Autolock _l(mLock);
1455 return getEffectChain_l(sessionId);
1456}
1457
Glenn Kastend848eb42016-03-08 13:42:11 -08001458sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1459 const
Eric Laurent81784c32012-11-19 14:55:58 -08001460{
1461 size_t size = mEffectChains.size();
1462 for (size_t i = 0; i < size; i++) {
1463 if (mEffectChains[i]->sessionId() == sessionId) {
1464 return mEffectChains[i];
1465 }
1466 }
1467 return 0;
1468}
1469
1470void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1471{
1472 Mutex::Autolock _l(mLock);
1473 size_t size = mEffectChains.size();
1474 for (size_t i = 0; i < size; i++) {
1475 mEffectChains[i]->setMode_l(mode);
1476 }
1477}
1478
Eric Laurent83b88082014-06-20 18:31:16 -07001479void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1480{
1481 config->type = AUDIO_PORT_TYPE_MIX;
1482 config->ext.mix.handle = mId;
1483 config->sample_rate = mSampleRate;
1484 config->format = mFormat;
1485 config->channel_mask = mChannelMask;
1486 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1487 AUDIO_PORT_CONFIG_FORMAT;
1488}
1489
Eric Laurent72e3f392015-05-20 14:43:50 -07001490void AudioFlinger::ThreadBase::systemReady()
1491{
1492 Mutex::Autolock _l(mLock);
1493 if (mSystemReady) {
1494 return;
1495 }
1496 mSystemReady = true;
1497
1498 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1499 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1500 }
1501 mPendingConfigEvents.clear();
1502}
1503
Andy Hung2f366df2016-10-31 14:01:16 -07001504template <typename T>
1505ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1506 ssize_t index = mActiveTracks.indexOf(track);
1507 if (index >= 0) {
1508 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1509 return index;
1510 }
1511 mActiveTracksGeneration++;
1512 mLatestActiveTrack = track;
1513 BatteryNotifier::getInstance().noteStartAudio(track->uid());
1514 return mActiveTracks.add(track);
1515}
1516
1517template <typename T>
1518ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1519 ssize_t index = mActiveTracks.remove(track);
1520 if (index < 0) {
1521 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1522 return index;
1523 }
1524 mActiveTracksGeneration++;
1525 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1526 // mLatestActiveTrack is not cleared even if is the same as track.
1527 return index;
1528}
1529
1530template <typename T>
1531void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1532 for (const sp<T> &track : mActiveTracks) {
1533 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1534 }
1535 mLastActiveTracksGeneration = mActiveTracksGeneration;
1536 mActiveTracks.clear();
1537 mLatestActiveTrack.clear();
1538}
Eric Laurent83b88082014-06-20 18:31:16 -07001539
Eric Laurent81784c32012-11-19 14:55:58 -08001540// ----------------------------------------------------------------------------
1541// Playback
1542// ----------------------------------------------------------------------------
1543
1544AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1545 AudioStreamOut* output,
1546 audio_io_handle_t id,
1547 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001548 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001549 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001550 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001551 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001552 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001553 mMixerBuffer(NULL),
1554 mMixerBufferSize(0),
1555 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1556 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001557 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001558 mEffectBuffer(NULL),
1559 mEffectBufferSize(0),
1560 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1561 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001562 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001563 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001564 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001565 // mStreamTypes[] initialized in constructor body
1566 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001567 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001568 mMixerStatus(MIXER_IDLE),
1569 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001570 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001571 mBytesRemaining(0),
1572 mCurrentWriteLength(0),
1573 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001574 mWriteAckSequence(0),
1575 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001576 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001577 mScreenState(AudioFlinger::mScreenState),
1578 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001579 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001580 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001581{
Glenn Kastend7dca052015-03-05 16:05:54 -08001582 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1583 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001584
1585 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1586 // it would be safer to explicitly pass initial masterVolume/masterMute as
1587 // parameter.
1588 //
1589 // If the HAL we are using has support for master volume or master mute,
1590 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1591 // and the mute set to false).
1592 mMasterVolume = audioFlinger->masterVolume_l();
1593 mMasterMute = audioFlinger->masterMute_l();
1594 if (mOutput && mOutput->audioHwDev) {
1595 if (mOutput->audioHwDev->canSetMasterVolume()) {
1596 mMasterVolume = 1.0;
1597 }
1598
1599 if (mOutput->audioHwDev->canSetMasterMute()) {
1600 mMasterMute = false;
1601 }
1602 }
1603
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001604 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001605
Eric Laurent223fd5c2014-11-11 13:43:36 -08001606 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001607 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001608 stream = (audio_stream_type_t) (stream + 1)) {
1609 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1610 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1611 }
Eric Laurent81784c32012-11-19 14:55:58 -08001612}
1613
1614AudioFlinger::PlaybackThread::~PlaybackThread()
1615{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001616 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001617 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001618 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001619 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001620}
1621
1622void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1623{
1624 dumpInternals(fd, args);
1625 dumpTracks(fd, args);
1626 dumpEffectChains(fd, args);
1627}
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) {
Andy Hung2f366df2016-10-31 14:01:16 -07001683 sp<Track> track = mActiveTracks[i];
1684 if (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 Laurentd0107bc2013-06-11 14:38:48 -07002087 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2088 if (chain != 0) {
2089 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2090 track->sessionId());
2091 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002092 }
2093
2094 status = NO_ERROR;
2095 }
2096
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002097 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002098 return status;
2099}
2100
Eric Laurentbfb1b832013-01-07 09:53:42 -08002101bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002102{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002103 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002104 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002105 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2106 track->mState = TrackBase::STOPPED;
2107 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002108 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002109 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002110 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002111 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002112
2113 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002114}
2115
2116void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2117{
2118 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2119 mTracks.remove(track);
2120 deleteTrackName_l(track->name());
2121 // redundant as track is about to be destroyed, for dumpsys only
2122 track->mName = -1;
2123 if (track->isFastTrack()) {
2124 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002125 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002126 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2127 mFastTrackAvailMask |= 1 << index;
2128 // redundant as track is about to be destroyed, for dumpsys only
2129 track->mFastIndex = -1;
2130 }
2131 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2132 if (chain != 0) {
2133 chain->decTrackCnt();
2134 }
2135}
2136
Eric Laurentede6c3b2013-09-19 14:37:46 -07002137void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002138{
2139 // Thread could be blocked waiting for async
2140 // so signal it to handle state changes immediately
2141 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2142 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2143 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002144 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002145}
2146
Eric Laurent81784c32012-11-19 14:55:58 -08002147String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2148{
Eric Laurent81784c32012-11-19 14:55:58 -08002149 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002150 String8 out_s8;
2151 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2152 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002153 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002154 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002155}
2156
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002157void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002158 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2159 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002160
Eric Laurent73e26b62015-04-27 16:55:58 -07002161 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002162
2163 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002164 case AUDIO_OUTPUT_OPENED:
2165 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002166 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002167 desc->mChannelMask = mChannelMask;
2168 desc->mSamplingRate = mSampleRate;
2169 desc->mFormat = mFormat;
2170 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002171 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002172 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002173 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002174 break;
2175
Eric Laurent73e26b62015-04-27 16:55:58 -07002176 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002177 default:
2178 break;
2179 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002180 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002181}
2182
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002183void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002184{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002185 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002186}
2187
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002188void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002189{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002190 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002191}
2192
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002193void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002194{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002195 mCallbackThread->setAsyncError();
2196}
2197
Eric Laurent3b4529e2013-09-05 18:09:19 -07002198void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002199{
2200 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002201 // reject out of sequence requests
2202 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2203 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204 mWaitWorkCV.signal();
2205 }
2206}
2207
Eric Laurent3b4529e2013-09-05 18:09:19 -07002208void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002209{
2210 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002211 // reject out of sequence requests
2212 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2213 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002214 mWaitWorkCV.signal();
2215 }
2216}
2217
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002218void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002219{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002220 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002221 mSampleRate = mOutput->getSampleRate();
2222 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002223 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002224 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002225 }
Andy Hung9a592762014-07-21 21:56:01 -07002226 if ((mType == MIXER || mType == DUPLICATING)
2227 && !isValidPcmSinkChannelMask(mChannelMask)) {
2228 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2229 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002230 }
Andy Hunge5412692014-05-16 11:25:07 -07002231 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002232
2233 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002234 status_t result = mOutput->stream->getFormat(&mHALFormat);
2235 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002236 // Get format from the shim, which will be different than the HAL format
2237 // if playing compressed audio over HDMI passthrough.
2238 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002239 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002240 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002241 }
Andy Hung6146c082014-03-18 11:56:15 -07002242 if ((mType == MIXER || mType == DUPLICATING)
2243 && !isValidPcmSinkFormat(mFormat)) {
2244 LOG_FATAL("HAL format %#x not supported for mixed output",
2245 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002246 }
Phil Burk062e67a2015-02-11 13:40:50 -08002247 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002248 result = mOutput->stream->getBufferSize(&mBufferSize);
2249 LOG_ALWAYS_FATAL_IF(result != OK,
2250 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002251 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002252 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002253 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002254 mFrameCount);
2255 }
2256
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002257 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2258 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002259 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002260 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002261 }
2262 }
2263
Eric Laurentd1f69b02014-12-15 14:33:13 -08002264 mHwSupportsPause = false;
2265 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002266 bool supportsPause = false, supportsResume = false;
2267 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2268 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002269 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002270 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002271 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002272 } else if (supportsResume) {
2273 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002274 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002275 }
2276 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002277 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2278 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2279 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002280
Andy Hungfbfc3952015-01-15 13:33:51 -08002281 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2282 // For best precision, we use float instead of the associated output
2283 // device format (typically PCM 16 bit).
2284
2285 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2286 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2287 mBufferSize = mFrameSize * mFrameCount;
2288
2289 // TODO: We currently use the associated output device channel mask and sample rate.
2290 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2291 // (if a valid mask) to avoid premature downmix.
2292 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2293 // instead of the output device sample rate to avoid loss of high frequency information.
2294 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2295 }
2296
Andy Hung09a50072014-02-27 14:30:47 -08002297 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002298 double multiplier = 1.0;
2299 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2300 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002301 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2302 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002303
Eric Laurent81784c32012-11-19 14:55:58 -08002304 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2305 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2306 maxNormalFrameCount = maxNormalFrameCount & ~15;
2307 if (maxNormalFrameCount < minNormalFrameCount) {
2308 maxNormalFrameCount = minNormalFrameCount;
2309 }
2310 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2311 if (multiplier <= 1.0) {
2312 multiplier = 1.0;
2313 } else if (multiplier <= 2.0) {
2314 if (2 * mFrameCount <= maxNormalFrameCount) {
2315 multiplier = 2.0;
2316 } else {
2317 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2318 }
2319 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002320 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002321 }
2322 }
2323 mNormalFrameCount = multiplier * mFrameCount;
2324 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002325 if (mType == MIXER || mType == DUPLICATING) {
2326 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2327 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002328 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002329 mNormalFrameCount);
2330
Andy Hung08fb1742015-05-31 23:22:10 -07002331 // Check if we want to throttle the processing to no more than 2x normal rate
2332 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002333 mThreadThrottleTimeMs = 0;
2334 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002335 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2336
Andy Hung010a1a12014-03-13 13:57:33 -07002337 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2338 // Originally this was int16_t[] array, need to remove legacy implications.
2339 free(mSinkBuffer);
2340 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002341 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2342 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2343 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002344 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002345
Andy Hung69aed5f2014-02-25 17:24:40 -08002346 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2347 // drives the output.
2348 free(mMixerBuffer);
2349 mMixerBuffer = NULL;
2350 if (mMixerBufferEnabled) {
2351 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2352 mMixerBufferSize = mNormalFrameCount * mChannelCount
2353 * audio_bytes_per_sample(mMixerBufferFormat);
2354 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2355 }
Andy Hung98ef9782014-03-04 14:46:50 -08002356 free(mEffectBuffer);
2357 mEffectBuffer = NULL;
2358 if (mEffectBufferEnabled) {
2359 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2360 mEffectBufferSize = mNormalFrameCount * mChannelCount
2361 * audio_bytes_per_sample(mEffectBufferFormat);
2362 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2363 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002364
Eric Laurent81784c32012-11-19 14:55:58 -08002365 // force reconfiguration of effect chains and engines to take new buffer size and audio
2366 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002367 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002368 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2369 // matter.
2370 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2371 Vector< sp<EffectChain> > effectChains = mEffectChains;
2372 for (size_t i = 0; i < effectChains.size(); i ++) {
2373 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2374 }
2375}
2376
2377
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002378status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002379{
2380 if (halFrames == NULL || dspFrames == NULL) {
2381 return BAD_VALUE;
2382 }
2383 Mutex::Autolock _l(mLock);
2384 if (initCheck() != NO_ERROR) {
2385 return INVALID_OPERATION;
2386 }
Andy Hung818e7a32016-02-16 18:08:07 -08002387 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002388 *halFrames = framesWritten;
2389
2390 if (isSuspended()) {
2391 // return an estimation of rendered frames when the output is suspended
2392 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002393 *dspFrames = (uint32_t)
2394 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002395 return NO_ERROR;
2396 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002397 status_t status;
2398 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002399 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002400 *dspFrames = (size_t)frames;
2401 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002402 }
2403}
2404
Eric Laurent4c415062016-06-17 16:14:16 -07002405// hasAudioSession_l() must be called with ThreadBase::mLock held
2406uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002407{
Eric Laurent81784c32012-11-19 14:55:58 -08002408 uint32_t result = 0;
2409 if (getEffectChain_l(sessionId) != 0) {
2410 result = EFFECT_SESSION;
2411 }
2412
2413 for (size_t i = 0; i < mTracks.size(); ++i) {
2414 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002415 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002416 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002417 if (track->isFastTrack()) {
2418 result |= FAST_SESSION;
2419 }
Eric Laurent81784c32012-11-19 14:55:58 -08002420 break;
2421 }
2422 }
2423
2424 return result;
2425}
2426
Glenn Kastend848eb42016-03-08 13:42:11 -08002427uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002428{
2429 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2430 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2431 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2432 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2433 }
2434 for (size_t i = 0; i < mTracks.size(); i++) {
2435 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002436 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002437 return AudioSystem::getStrategyForStream(track->streamType());
2438 }
2439 }
2440 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2441}
2442
2443
Phil Burk062e67a2015-02-11 13:40:50 -08002444AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002445{
2446 Mutex::Autolock _l(mLock);
2447 return mOutput;
2448}
2449
Phil Burk062e67a2015-02-11 13:40:50 -08002450AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002451{
2452 Mutex::Autolock _l(mLock);
2453 AudioStreamOut *output = mOutput;
2454 mOutput = NULL;
2455 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2456 // must push a NULL and wait for ack
2457 mOutputSink.clear();
2458 mPipeSink.clear();
2459 mNormalSink.clear();
2460 return output;
2461}
2462
2463// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002464sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002465{
2466 if (mOutput == NULL) {
2467 return NULL;
2468 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002469 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002470}
2471
2472uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2473{
2474 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2475}
2476
2477status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2478{
2479 if (!isValidSyncEvent(event)) {
2480 return BAD_VALUE;
2481 }
2482
2483 Mutex::Autolock _l(mLock);
2484
2485 for (size_t i = 0; i < mTracks.size(); ++i) {
2486 sp<Track> track = mTracks[i];
2487 if (event->triggerSession() == track->sessionId()) {
2488 (void) track->setSyncEvent(event);
2489 return NO_ERROR;
2490 }
2491 }
2492
2493 return NAME_NOT_FOUND;
2494}
2495
2496bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2497{
2498 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2499}
2500
2501void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2502 const Vector< sp<Track> >& tracksToRemove)
2503{
2504 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002505 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002506 for (size_t i = 0 ; i < count ; i++) {
2507 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002508 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002509 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002510 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002511#ifdef ADD_BATTERY_DATA
2512 // to track the speaker usage
2513 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2514#endif
2515 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002516 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002517 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002518 }
Eric Laurent81784c32012-11-19 14:55:58 -08002519 }
2520 }
2521 }
Eric Laurent81784c32012-11-19 14:55:58 -08002522}
2523
2524void AudioFlinger::PlaybackThread::checkSilentMode_l()
2525{
2526 if (!mMasterMute) {
2527 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002528 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2529 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2530 return;
2531 }
Eric Laurent81784c32012-11-19 14:55:58 -08002532 if (property_get("ro.audio.silent", value, "0") > 0) {
2533 char *endptr;
2534 unsigned long ul = strtoul(value, &endptr, 0);
2535 if (*endptr == '\0' && ul != 0) {
2536 ALOGD("Silence is golden");
2537 // The setprop command will not allow a property to be changed after
2538 // the first time it is set, so we don't have to worry about un-muting.
2539 setMasterMute_l(true);
2540 }
2541 }
2542 }
2543}
2544
2545// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002546ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002547{
Eric Laurent81784c32012-11-19 14:55:58 -08002548 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002549 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002550 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002551
2552 // If an NBAIO sink is present, use it to write the normal mixer's submix
2553 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002554
Andy Hung010a1a12014-03-13 13:57:33 -07002555 const size_t count = mBytesRemaining / mFrameSize;
2556
Simon Wilson2d590962012-11-29 15:18:50 -08002557 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002558 // update the setpoint when AudioFlinger::mScreenState changes
2559 uint32_t screenState = AudioFlinger::mScreenState;
2560 if (screenState != mScreenState) {
2561 mScreenState = screenState;
2562 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2563 if (pipe != NULL) {
2564 pipe->setAvgFrames((mScreenState & 1) ?
2565 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2566 }
2567 }
Andy Hung010a1a12014-03-13 13:57:33 -07002568 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002569 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002570 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002571 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002572 } else {
2573 bytesWritten = framesWritten;
2574 }
2575 // otherwise use the HAL / AudioStreamOut directly
2576 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002577 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002578
Eric Laurentbfb1b832013-01-07 09:53:42 -08002579 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002580 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2581 mWriteAckSequence += 2;
2582 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002583 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002584 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002586 // FIXME We should have an implementation of timestamps for direct output threads.
2587 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002588 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002589
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590 if (mUseAsyncWrite &&
2591 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2592 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002593 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002595 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002596 }
Eric Laurent81784c32012-11-19 14:55:58 -08002597 }
2598
Eric Laurent81784c32012-11-19 14:55:58 -08002599 mNumWrites++;
2600 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002601 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002602 return bytesWritten;
2603}
2604
2605void AudioFlinger::PlaybackThread::threadLoop_drain()
2606{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002607 bool supportsDrain = false;
2608 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002609 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2610 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002611 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2612 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002613 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002614 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002615 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002616 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002617 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002618 }
2619}
2620
2621void AudioFlinger::PlaybackThread::threadLoop_exit()
2622{
Eric Laurent275e8e92014-11-30 15:14:47 -08002623 {
2624 Mutex::Autolock _l(mLock);
2625 for (size_t i = 0; i < mTracks.size(); i++) {
2626 sp<Track> track = mTracks[i];
2627 track->invalidate();
2628 }
2629 }
Eric Laurent81784c32012-11-19 14:55:58 -08002630}
2631
2632/*
2633The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002634 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002635 - mActiveSleepTimeUs from activeSleepTimeUs()
2636 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002637 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2638 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002639 - maxPeriod from frame count and sample rate (MIXER only)
2640
2641The parameters that affect these derived values are:
2642 - frame count
2643 - frame size
2644 - sample rate
2645 - device type: A2DP or not
2646 - device latency
2647 - format: PCM or not
2648 - active sleep time
2649 - idle sleep time
2650*/
2651
2652void AudioFlinger::PlaybackThread::cacheParameters_l()
2653{
Andy Hung25c2dac2014-02-27 14:56:00 -08002654 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002655 mActiveSleepTimeUs = activeSleepTimeUs();
2656 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002657
2658 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2659 // truncating audio when going to standby.
2660 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2661 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2662 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2663 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2664 }
2665 }
Eric Laurent81784c32012-11-19 14:55:58 -08002666}
2667
Eric Laurent13084622016-05-17 10:51:49 -07002668bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002669{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002670 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002671 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002672 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002673 size_t size = mTracks.size();
2674 for (size_t i = 0; i < size; i++) {
2675 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002676 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002677 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002678 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002679 }
2680 }
Eric Laurent13084622016-05-17 10:51:49 -07002681 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002682}
2683
Haynes Mathew George05317d22016-05-03 16:34:26 -07002684void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2685{
2686 Mutex::Autolock _l(mLock);
2687 invalidateTracks_l(streamType);
2688}
2689
Eric Laurent81784c32012-11-19 14:55:58 -08002690status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2691{
Glenn Kastend848eb42016-03-08 13:42:11 -08002692 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002693 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2694 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002695 bool ownsBuffer = false;
2696
2697 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002698 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002699 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002700 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002701 if (mType != DIRECT) {
2702 size_t numSamples = mNormalFrameCount * mChannelCount;
2703 buffer = new int16_t[numSamples];
2704 memset(buffer, 0, numSamples * sizeof(int16_t));
2705 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2706 ownsBuffer = true;
2707 }
2708
2709 // Attach all tracks with same session ID to this chain.
2710 for (size_t i = 0; i < mTracks.size(); ++i) {
2711 sp<Track> track = mTracks[i];
2712 if (session == track->sessionId()) {
2713 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2714 buffer);
2715 track->setMainBuffer(buffer);
2716 chain->incTrackCnt();
2717 }
2718 }
2719
2720 // indicate all active tracks in the chain
Andy Hung2f366df2016-10-31 14:01:16 -07002721 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002722 if (session == track->sessionId()) {
2723 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2724 chain->incActiveTrackCnt();
2725 }
2726 }
2727 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002728 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002729 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002730 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2731 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002732 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002733 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002734 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2735 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002736 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002737 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002738 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002739 // Effect chain for other sessions are inserted at beginning of effect
2740 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002741 // sessions is not important.
2742 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2743 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2744 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002745 size_t size = mEffectChains.size();
2746 size_t i = 0;
2747 for (i = 0; i < size; i++) {
2748 if (mEffectChains[i]->sessionId() < session) {
2749 break;
2750 }
2751 }
2752 mEffectChains.insertAt(chain, i);
2753 checkSuspendOnAddEffectChain_l(chain);
2754
2755 return NO_ERROR;
2756}
2757
2758size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2759{
Glenn Kastend848eb42016-03-08 13:42:11 -08002760 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002761
2762 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2763
2764 for (size_t i = 0; i < mEffectChains.size(); i++) {
2765 if (chain == mEffectChains[i]) {
2766 mEffectChains.removeAt(i);
2767 // detach all active tracks from the chain
Andy Hung2f366df2016-10-31 14:01:16 -07002768 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002769 if (session == track->sessionId()) {
2770 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2771 chain.get(), session);
2772 chain->decActiveTrackCnt();
2773 }
2774 }
2775
2776 // detach all tracks with same session ID from this chain
2777 for (size_t i = 0; i < mTracks.size(); ++i) {
2778 sp<Track> track = mTracks[i];
2779 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002780 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002781 chain->decTrackCnt();
2782 }
2783 }
2784 break;
2785 }
2786 }
2787 return mEffectChains.size();
2788}
2789
2790status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002791 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002792{
2793 Mutex::Autolock _l(mLock);
2794 return attachAuxEffect_l(track, EffectId);
2795}
2796
2797status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002798 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002799{
2800 status_t status = NO_ERROR;
2801
2802 if (EffectId == 0) {
2803 track->setAuxBuffer(0, NULL);
2804 } else {
2805 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2806 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2807 if (effect != 0) {
2808 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2809 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2810 } else {
2811 status = INVALID_OPERATION;
2812 }
2813 } else {
2814 status = BAD_VALUE;
2815 }
2816 }
2817 return status;
2818}
2819
2820void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2821{
2822 for (size_t i = 0; i < mTracks.size(); ++i) {
2823 sp<Track> track = mTracks[i];
2824 if (track->auxEffectId() == effectId) {
2825 attachAuxEffect_l(track, 0);
2826 }
2827 }
2828}
2829
2830bool AudioFlinger::PlaybackThread::threadLoop()
2831{
2832 Vector< sp<Track> > tracksToRemove;
2833
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002834 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002835 nsecs_t lastWriteFinished = -1; // time last server write completed
2836 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002837
2838 // MIXER
2839 nsecs_t lastWarning = 0;
2840
2841 // DUPLICATING
2842 // FIXME could this be made local to while loop?
2843 writeFrames = 0;
2844
2845 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002846 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002847
2848 if (mType == MIXER) {
2849 sleepTimeShift = 0;
2850 }
2851
2852 CpuStats cpuStats;
2853 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2854
2855 acquireWakeLock();
2856
Glenn Kasten9e58b552013-01-18 15:09:48 -08002857 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2858 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2859 // and then that string will be logged at the next convenient opportunity.
2860 const char *logString = NULL;
2861
Eric Laurent664539d2013-09-23 18:24:31 -07002862 checkSilentMode_l();
2863
Eric Laurent81784c32012-11-19 14:55:58 -08002864 while (!exitPending())
2865 {
2866 cpuStats.sample(myName);
2867
2868 Vector< sp<EffectChain> > effectChains;
2869
Eric Laurent81784c32012-11-19 14:55:58 -08002870 { // scope for mLock
2871
2872 Mutex::Autolock _l(mLock);
2873
Eric Laurent021cf962014-05-13 10:18:14 -07002874 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002875
Glenn Kasten9e58b552013-01-18 15:09:48 -08002876 if (logString != NULL) {
2877 mNBLogWriter->logTimestamp();
2878 mNBLogWriter->log(logString);
2879 logString = NULL;
2880 }
2881
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002882 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002883 // and associate with the sink frames written out. We need
2884 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002885 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002886 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002887 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002888 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002889 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002890 ExtendedTimestamp timestamp; // use private copy to fetch
2891 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002892
2893 // We keep track of the last valid kernel position in case we are in underrun
2894 // and the normal mixer period is the same as the fast mixer period, or there
2895 // is some error from the HAL.
2896 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2897 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2898 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2899 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2900 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2901
2902 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2903 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2904 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2905 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002906 }
2907
2908 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2909 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002910 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002911 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002912 }
2913
Andy Hung818e7a32016-02-16 18:08:07 -08002914 // copy over kernel info
2915 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07002916 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
2917 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08002918 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2919 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002920 }
2921 // mFramesWritten for non-offloaded tracks are contiguous
2922 // even after standby() is called. This is useful for the track frame
2923 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07002924 bool serverLocationUpdate = false;
2925 if (mFramesWritten != lastFramesWritten) {
2926 serverLocationUpdate = true;
2927 lastFramesWritten = mFramesWritten;
2928 }
2929 // Only update timestamps if there is a meaningful change.
2930 // Either the kernel timestamp must be valid or we have written something.
2931 if (kernelLocationUpdate || serverLocationUpdate) {
2932 if (serverLocationUpdate) {
2933 // use the time before we called the HAL write - it is a bit more accurate
2934 // to when the server last read data than the current time here.
2935 //
2936 // If we haven't written anything, mLastWriteTime will be -1
2937 // and we use systemTime().
2938 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2939 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
2940 ? systemTime() : mLastWriteTime;
2941 }
Andy Hung2f366df2016-10-31 14:01:16 -07002942
2943 for (const sp<Track> &t : mActiveTracks) {
2944 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07002945 t->updateTrackFrameInfo(
2946 t->mAudioTrackServerProxy->framesReleased(),
2947 mFramesWritten,
2948 mTimestamp);
2949 }
Andy Hunge10393e2015-06-12 13:59:33 -07002950 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002951 }
2952
Eric Laurent81784c32012-11-19 14:55:58 -08002953 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002954 if (mSignalPending) {
2955 // A signal was raised while we were unlocked
2956 mSignalPending = false;
2957 } else if (waitingAsyncCallback_l()) {
2958 if (exitPending()) {
2959 break;
2960 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002961 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07002962 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07002963 releaseWakeLock_l();
2964 released = true;
2965 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002966 ALOGV("wait async completion");
2967 mWaitWorkCV.wait(mLock);
2968 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002969 if (released) {
2970 acquireWakeLock_l();
2971 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002972 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2973 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002974
2975 continue;
2976 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002977 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002978 isSuspended()) {
2979 // put audio hardware into standby after short delay
2980 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002981
2982 threadLoop_standby();
2983
2984 mStandby = true;
2985 }
2986
2987 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2988 // we're about to wait, flush the binder command buffer
2989 IPCThreadState::self()->flushCommands();
2990
2991 clearOutputTracks();
2992
2993 if (exitPending()) {
2994 break;
2995 }
2996
2997 releaseWakeLock_l();
2998 // wait until we have something to do...
2999 ALOGV("%s going to sleep", myName.string());
3000 mWaitWorkCV.wait(mLock);
3001 ALOGV("%s waking up", myName.string());
3002 acquireWakeLock_l();
3003
3004 mMixerStatus = MIXER_IDLE;
3005 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3006 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003007 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003008 checkSilentMode_l();
3009
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003010 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3011 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003012 if (mType == MIXER) {
3013 sleepTimeShift = 0;
3014 }
3015
3016 continue;
3017 }
3018 }
Eric Laurent81784c32012-11-19 14:55:58 -08003019 // mMixerStatusIgnoringFastTracks is also updated internally
3020 mMixerStatus = prepareTracks_l(&tracksToRemove);
3021
Andy Hung2f366df2016-10-31 14:01:16 -07003022 mActiveTracks.updateWakeLockUids(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003023
Eric Laurent81784c32012-11-19 14:55:58 -08003024 // prevent any changes in effect chain list and in each effect chain
3025 // during mixing and effect process as the audio buffers could be deleted
3026 // or modified if an effect is created or deleted
3027 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003028 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003029
Eric Laurentbfb1b832013-01-07 09:53:42 -08003030 if (mBytesRemaining == 0) {
3031 mCurrentWriteLength = 0;
3032 if (mMixerStatus == MIXER_TRACKS_READY) {
3033 // threadLoop_mix() sets mCurrentWriteLength
3034 threadLoop_mix();
3035 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3036 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003037 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003038 // must be written to HAL
3039 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003040 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003041 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003042 }
3043 }
Andy Hung98ef9782014-03-04 14:46:50 -08003044 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003045 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003046 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3047 // or mSinkBuffer (if there are no effects).
3048 //
3049 // This is done pre-effects computation; if effects change to
3050 // support higher precision, this needs to move.
3051 //
3052 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003053 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003054 if (mMixerBufferValid) {
3055 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3056 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3057
Andy Hung2ddee192015-12-18 17:34:44 -08003058 // mono blend occurs for mixer threads only (not direct or offloaded)
3059 // and is handled here if we're going directly to the sink.
3060 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003061 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3062 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003063 }
3064
Andy Hung98ef9782014-03-04 14:46:50 -08003065 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3066 mNormalFrameCount * mChannelCount);
3067 }
3068
Eric Laurentbfb1b832013-01-07 09:53:42 -08003069 mBytesRemaining = mCurrentWriteLength;
3070 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003071 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3072 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3073 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3074 mBytesWritten += mBytesRemaining;
3075 mFramesWritten += framesRemaining;
3076 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003077 mBytesRemaining = 0;
3078 }
Eric Laurent81784c32012-11-19 14:55:58 -08003079
Eric Laurentbfb1b832013-01-07 09:53:42 -08003080 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003081 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003082 for (size_t i = 0; i < effectChains.size(); i ++) {
3083 effectChains[i]->process_l();
3084 }
Eric Laurent81784c32012-11-19 14:55:58 -08003085 }
3086 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003087 // Process effect chains for offloaded thread even if no audio
3088 // was read from audio track: process only updates effect state
3089 // and thus does have to be synchronized with audio writes but may have
3090 // to be called while waiting for async write callback
3091 if (mType == OFFLOAD) {
3092 for (size_t i = 0; i < effectChains.size(); i ++) {
3093 effectChains[i]->process_l();
3094 }
3095 }
Eric Laurent81784c32012-11-19 14:55:58 -08003096
Andy Hung98ef9782014-03-04 14:46:50 -08003097 // Only if the Effects buffer is enabled and there is data in the
3098 // Effects buffer (buffer valid), we need to
3099 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003100 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003101 if (mEffectBufferValid) {
3102 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003103
3104 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003105 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3106 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003107 }
3108
Andy Hung98ef9782014-03-04 14:46:50 -08003109 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3110 mNormalFrameCount * mChannelCount);
3111 }
3112
Eric Laurent81784c32012-11-19 14:55:58 -08003113 // enable changes in effect chain
3114 unlockEffectChains(effectChains);
3115
Eric Laurentbfb1b832013-01-07 09:53:42 -08003116 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003117 // mSleepTimeUs == 0 means we must write to audio hardware
3118 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003119 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003120 // We save lastWriteFinished here, as previousLastWriteFinished,
3121 // for throttling. On thread start, previousLastWriteFinished will be
3122 // set to -1, which properly results in no throttling after the first write.
3123 nsecs_t previousLastWriteFinished = lastWriteFinished;
3124 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003125 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003126 // FIXME rewrite to reduce number of system calls
3127 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003128 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003129 lastWriteFinished = systemTime();
3130 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003131 if (ret < 0) {
3132 mBytesRemaining = 0;
3133 } else {
3134 mBytesWritten += ret;
3135 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003136 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003137 }
3138 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3139 (mMixerStatus == MIXER_DRAIN_ALL)) {
3140 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003141 }
Andy Hung08fb1742015-05-31 23:22:10 -07003142 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003143 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003144 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003145 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003146 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003147 ATRACE_NAME("underrun");
3148 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003149 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003150 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003151 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003152 }
Andy Hung08fb1742015-05-31 23:22:10 -07003153
3154 if (mThreadThrottle
3155 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3156 && ret > 0) { // we wrote something
3157 // Limit MixerThread data processing to no more than twice the
3158 // expected processing rate.
3159 //
3160 // This helps prevent underruns with NuPlayer and other applications
3161 // which may set up buffers that are close to the minimum size, or use
3162 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3163 //
3164 // The throttle smooths out sudden large data drains from the device,
3165 // e.g. when it comes out of standby, which often causes problems with
3166 // (1) mixer threads without a fast mixer (which has its own warm-up)
3167 // (2) minimum buffer sized tracks (even if the track is full,
3168 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003169 //
3170 // Total time spent in last processing cycle equals time spent in
3171 // 1. threadLoop_write, as well as time spent in
3172 // 2. threadLoop_mix (significant for heavy mixing, especially
3173 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003174
Andy Hung69488c42016-05-16 18:43:33 -07003175 // it's OK if deltaMs is an overestimate.
3176 const int32_t deltaMs =
3177 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003178 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3179 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3180 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003181 // notify of throttle start on verbose log
3182 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3183 "mixer(%p) throttle begin:"
3184 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003185 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003186 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003187 // Throttle must be attributed to the previous mixer loop's write time
3188 // to allow back-to-back throttling.
3189 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003190 } else {
3191 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3192 if (diff > 0) {
3193 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003194 // but prevent spamming for bluetooth
3195 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3196 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003197 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3198 }
Andy Hung08fb1742015-05-31 23:22:10 -07003199 }
3200 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003201 }
Eric Laurent81784c32012-11-19 14:55:58 -08003202
Eric Laurentbfb1b832013-01-07 09:53:42 -08003203 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003204 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003205 Mutex::Autolock _l(mLock);
3206 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3207 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003208 }
Glenn Kastene7754022014-10-31 12:11:26 -07003209 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003210 }
Eric Laurent81784c32012-11-19 14:55:58 -08003211 }
3212
3213 // Finally let go of removed track(s), without the lock held
3214 // since we can't guarantee the destructors won't acquire that
3215 // same lock. This will also mutate and push a new fast mixer state.
3216 threadLoop_removeTracks(tracksToRemove);
3217 tracksToRemove.clear();
3218
3219 // FIXME I don't understand the need for this here;
3220 // it was in the original code but maybe the
3221 // assignment in saveOutputTracks() makes this unnecessary?
3222 clearOutputTracks();
3223
3224 // Effect chains will be actually deleted here if they were removed from
3225 // mEffectChains list during mixing or effects processing
3226 effectChains.clear();
3227
3228 // FIXME Note that the above .clear() is no longer necessary since effectChains
3229 // is now local to this block, but will keep it for now (at least until merge done).
3230 }
3231
Eric Laurentbfb1b832013-01-07 09:53:42 -08003232 threadLoop_exit();
3233
Eric Laurentcf817a22014-08-04 20:36:31 -07003234 if (!mStandby) {
3235 threadLoop_standby();
3236 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003237 }
3238
3239 releaseWakeLock();
3240
3241 ALOGV("Thread %p type %d exiting", this, mType);
3242 return false;
3243}
3244
Eric Laurentbfb1b832013-01-07 09:53:42 -08003245// removeTracks_l() must be called with ThreadBase::mLock held
3246void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3247{
3248 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003249 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003250 for (size_t i=0 ; i<count ; i++) {
3251 const sp<Track>& track = tracksToRemove.itemAt(i);
3252 mActiveTracks.remove(track);
3253 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3254 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3255 if (chain != 0) {
3256 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3257 track->sessionId());
3258 chain->decActiveTrackCnt();
3259 }
3260 if (track->isTerminated()) {
3261 removeTrack_l(track);
3262 }
3263 }
3264 }
3265
3266}
Eric Laurent81784c32012-11-19 14:55:58 -08003267
Eric Laurentaccc1472013-09-20 09:36:34 -07003268status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3269{
3270 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003271 ExtendedTimestamp ets;
3272 status_t status = mNormalSink->getTimestamp(ets);
3273 if (status == NO_ERROR) {
3274 status = ets.getBestTimestamp(&timestamp);
3275 }
3276 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003277 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003278 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003279 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003280 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003281 timestamp.mPosition = (uint32_t)position64;
3282 return NO_ERROR;
3283 }
3284 }
3285 return INVALID_OPERATION;
3286}
Eric Laurent1c333e22014-05-20 10:48:17 -07003287
Eric Laurent054d9d32015-04-24 08:48:48 -07003288status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3289 audio_patch_handle_t *handle)
3290{
Andy Hungf60abce2016-08-26 11:37:54 -07003291 status_t status;
3292 if (property_get_bool("af.patch_park", false /* default_value */)) {
3293 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3294 // or if HAL does not properly lock against access.
3295 AutoPark<FastMixer> park(mFastMixer);
3296 status = PlaybackThread::createAudioPatch_l(patch, handle);
3297 } else {
3298 status = PlaybackThread::createAudioPatch_l(patch, handle);
3299 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003300 return status;
3301}
3302
Eric Laurent1c333e22014-05-20 10:48:17 -07003303status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3304 audio_patch_handle_t *handle)
3305{
3306 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003307
3308 // store new device and send to effects
3309 audio_devices_t type = AUDIO_DEVICE_NONE;
3310 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3311 type |= patch->sinks[i].ext.device.type;
3312 }
3313
3314#ifdef ADD_BATTERY_DATA
3315 // when changing the audio output device, call addBatteryData to notify
3316 // the change
3317 if (mOutDevice != type) {
3318 uint32_t params = 0;
3319 // check whether speaker is on
3320 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3321 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003322 }
3323
Eric Laurent054d9d32015-04-24 08:48:48 -07003324 audio_devices_t deviceWithoutSpeaker
3325 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3326 // check if any other device (except speaker) is on
3327 if (type & deviceWithoutSpeaker) {
3328 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3329 }
3330
3331 if (params != 0) {
3332 addBatteryData(params);
3333 }
3334 }
3335#endif
3336
3337 for (size_t i = 0; i < mEffectChains.size(); i++) {
3338 mEffectChains[i]->setDevice_l(type);
3339 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003340
3341 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3342 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3343 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003344 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003345 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003346
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003347 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003348 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3349 status = hwDevice->createAudioPatch(patch->num_sources,
3350 patch->sources,
3351 patch->num_sinks,
3352 patch->sinks,
3353 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003354 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003355 char *address;
3356 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3357 //FIXME: we only support address on first sink with HAL version < 3.0
3358 address = audio_device_address_to_parameter(
3359 patch->sinks[0].ext.device.type,
3360 patch->sinks[0].ext.device.address);
3361 } else {
3362 address = (char *)calloc(1, 1);
3363 }
3364 AudioParameter param = AudioParameter(String8(address));
3365 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003366 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003367 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003368 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003369 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003370 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003371 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003372 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3373 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003374 return status;
3375}
3376
Eric Laurent054d9d32015-04-24 08:48:48 -07003377status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3378{
Andy Hungf60abce2016-08-26 11:37:54 -07003379 status_t status;
3380 if (property_get_bool("af.patch_park", false /* default_value */)) {
3381 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3382 // or if HAL does not properly lock against access.
3383 AutoPark<FastMixer> park(mFastMixer);
3384 status = PlaybackThread::releaseAudioPatch_l(handle);
3385 } else {
3386 status = PlaybackThread::releaseAudioPatch_l(handle);
3387 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003388 return status;
3389}
3390
Eric Laurent1c333e22014-05-20 10:48:17 -07003391status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3392{
3393 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003394
3395 mOutDevice = AUDIO_DEVICE_NONE;
3396
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003397 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003398 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3399 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003400 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003401 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003402 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003403 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003404 }
3405 return status;
3406}
3407
Eric Laurent83b88082014-06-20 18:31:16 -07003408void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3409{
3410 Mutex::Autolock _l(mLock);
3411 mTracks.add(track);
3412}
3413
3414void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3415{
3416 Mutex::Autolock _l(mLock);
3417 destroyTrack_l(track);
3418}
3419
3420void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3421{
3422 ThreadBase::getAudioPortConfig(config);
3423 config->role = AUDIO_PORT_ROLE_SOURCE;
3424 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3425 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3426}
3427
Eric Laurent81784c32012-11-19 14:55:58 -08003428// ----------------------------------------------------------------------------
3429
3430AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003431 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3432 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003433 // mAudioMixer below
3434 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003435 mFastMixerFutex(0),
3436 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003437 // mOutputSink below
3438 // mPipeSink below
3439 // mNormalSink below
3440{
3441 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003442 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3443 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003444 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3445 mNormalFrameCount);
3446 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3447
Andy Hungfbfc3952015-01-15 13:33:51 -08003448 if (type == DUPLICATING) {
3449 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3450 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3451 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3452 return;
3453 }
Eric Laurent81784c32012-11-19 14:55:58 -08003454 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003455 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003456 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003457 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003458#if !LOG_NDEBUG
3459 ssize_t index =
3460#else
3461 (void)
3462#endif
3463 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003464 ALOG_ASSERT(index == 0);
3465
3466 // initialize fast mixer depending on configuration
3467 bool initFastMixer;
3468 switch (kUseFastMixer) {
3469 case FastMixer_Never:
3470 initFastMixer = false;
3471 break;
3472 case FastMixer_Always:
3473 initFastMixer = true;
3474 break;
3475 case FastMixer_Static:
3476 case FastMixer_Dynamic:
3477 initFastMixer = mFrameCount < mNormalFrameCount;
3478 break;
3479 }
3480 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003481 audio_format_t fastMixerFormat;
3482 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3483 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3484 } else {
3485 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3486 }
3487 if (mFormat != fastMixerFormat) {
3488 // change our Sink format to accept our intermediate precision
3489 mFormat = fastMixerFormat;
3490 free(mSinkBuffer);
3491 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3492 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3493 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3494 }
Eric Laurent81784c32012-11-19 14:55:58 -08003495
3496 // create a MonoPipe to connect our submix to FastMixer
3497 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003498#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003499 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003500#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003501 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003502 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003503 format.mFormat = fastMixerFormat;
3504 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3505
Eric Laurent81784c32012-11-19 14:55:58 -08003506 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3507 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3508 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3509 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3510 const NBAIO_Format offers[1] = {format};
3511 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003512#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003513 ssize_t index =
3514#else
3515 (void)
3516#endif
3517 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003518 ALOG_ASSERT(index == 0);
3519 monoPipe->setAvgFrames((mScreenState & 1) ?
3520 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3521 mPipeSink = monoPipe;
3522
Glenn Kasten46909e72013-02-26 09:20:22 -08003523#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003524 if (mTeeSinkOutputEnabled) {
3525 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003526 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3527 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003528 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003529 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003530 ALOG_ASSERT(index == 0);
3531 mTeeSink = teeSink;
3532 PipeReader *teeSource = new PipeReader(*teeSink);
3533 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003534 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003535 ALOG_ASSERT(index == 0);
3536 mTeeSource = teeSource;
3537 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003538#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003539
3540 // create fast mixer and configure it initially with just one fast track for our submix
3541 mFastMixer = new FastMixer();
3542 FastMixerStateQueue *sq = mFastMixer->sq();
3543#ifdef STATE_QUEUE_DUMP
3544 sq->setObserverDump(&mStateQueueObserverDump);
3545 sq->setMutatorDump(&mStateQueueMutatorDump);
3546#endif
3547 FastMixerState *state = sq->begin();
3548 FastTrack *fastTrack = &state->mFastTracks[0];
3549 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3550 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3551 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003552 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3553 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003554 fastTrack->mGeneration++;
3555 state->mFastTracksGen++;
3556 state->mTrackMask = 1;
3557 // fast mixer will use the HAL output sink
3558 state->mOutputSink = mOutputSink.get();
3559 state->mOutputSinkGen++;
3560 state->mFrameCount = mFrameCount;
3561 state->mCommand = FastMixerState::COLD_IDLE;
3562 // already done in constructor initialization list
3563 //mFastMixerFutex = 0;
3564 state->mColdFutexAddr = &mFastMixerFutex;
3565 state->mColdGen++;
3566 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003567#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003568 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003569#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003570 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3571 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003572 sq->end();
3573 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3574
3575 // start the fast mixer
3576 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3577 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003578 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003579
3580#ifdef AUDIO_WATCHDOG
3581 // create and start the watchdog
3582 mAudioWatchdog = new AudioWatchdog();
3583 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3584 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3585 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003586 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003587#endif
3588
Eric Laurent81784c32012-11-19 14:55:58 -08003589 }
3590
3591 switch (kUseFastMixer) {
3592 case FastMixer_Never:
3593 case FastMixer_Dynamic:
3594 mNormalSink = mOutputSink;
3595 break;
3596 case FastMixer_Always:
3597 mNormalSink = mPipeSink;
3598 break;
3599 case FastMixer_Static:
3600 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3601 break;
3602 }
3603}
3604
3605AudioFlinger::MixerThread::~MixerThread()
3606{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003607 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003608 FastMixerStateQueue *sq = mFastMixer->sq();
3609 FastMixerState *state = sq->begin();
3610 if (state->mCommand == FastMixerState::COLD_IDLE) {
3611 int32_t old = android_atomic_inc(&mFastMixerFutex);
3612 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003613 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003614 }
3615 }
3616 state->mCommand = FastMixerState::EXIT;
3617 sq->end();
3618 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3619 mFastMixer->join();
3620 // Though the fast mixer thread has exited, it's state queue is still valid.
3621 // We'll use that extract the final state which contains one remaining fast track
3622 // corresponding to our sub-mix.
3623 state = sq->begin();
3624 ALOG_ASSERT(state->mTrackMask == 1);
3625 FastTrack *fastTrack = &state->mFastTracks[0];
3626 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3627 delete fastTrack->mBufferProvider;
3628 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003629 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003630#ifdef AUDIO_WATCHDOG
3631 if (mAudioWatchdog != 0) {
3632 mAudioWatchdog->requestExit();
3633 mAudioWatchdog->requestExitAndWait();
3634 mAudioWatchdog.clear();
3635 }
3636#endif
3637 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003638 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003639 delete mAudioMixer;
3640}
3641
3642
3643uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3644{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003645 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003646 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3647 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3648 }
3649 return latency;
3650}
3651
3652
3653void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3654{
3655 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3656}
3657
Eric Laurentbfb1b832013-01-07 09:53:42 -08003658ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003659{
3660 // FIXME we should only do one push per cycle; confirm this is true
3661 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003662 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003663 FastMixerStateQueue *sq = mFastMixer->sq();
3664 FastMixerState *state = sq->begin();
3665 if (state->mCommand != FastMixerState::MIX_WRITE &&
3666 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3667 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003668
3669 // FIXME workaround for first HAL write being CPU bound on some devices
3670 ATRACE_BEGIN("write");
3671 mOutput->write((char *)mSinkBuffer, 0);
3672 ATRACE_END();
3673
Eric Laurent81784c32012-11-19 14:55:58 -08003674 int32_t old = android_atomic_inc(&mFastMixerFutex);
3675 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003676 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003677 }
3678#ifdef AUDIO_WATCHDOG
3679 if (mAudioWatchdog != 0) {
3680 mAudioWatchdog->resume();
3681 }
3682#endif
3683 }
3684 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003685#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003686 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003687 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003688#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003689 sq->end();
3690 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3691 if (kUseFastMixer == FastMixer_Dynamic) {
3692 mNormalSink = mPipeSink;
3693 }
3694 } else {
3695 sq->end(false /*didModify*/);
3696 }
3697 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003698 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003699}
3700
3701void AudioFlinger::MixerThread::threadLoop_standby()
3702{
3703 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003704 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003705 FastMixerStateQueue *sq = mFastMixer->sq();
3706 FastMixerState *state = sq->begin();
3707 if (!(state->mCommand & FastMixerState::IDLE)) {
3708 state->mCommand = FastMixerState::COLD_IDLE;
3709 state->mColdFutexAddr = &mFastMixerFutex;
3710 state->mColdGen++;
3711 mFastMixerFutex = 0;
3712 sq->end();
3713 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3714 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3715 if (kUseFastMixer == FastMixer_Dynamic) {
3716 mNormalSink = mOutputSink;
3717 }
3718#ifdef AUDIO_WATCHDOG
3719 if (mAudioWatchdog != 0) {
3720 mAudioWatchdog->pause();
3721 }
3722#endif
3723 } else {
3724 sq->end(false /*didModify*/);
3725 }
3726 }
3727 PlaybackThread::threadLoop_standby();
3728}
3729
Eric Laurentbfb1b832013-01-07 09:53:42 -08003730bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3731{
3732 return false;
3733}
3734
3735bool AudioFlinger::PlaybackThread::shouldStandby_l()
3736{
3737 return !mStandby;
3738}
3739
3740bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3741{
3742 Mutex::Autolock _l(mLock);
3743 return waitingAsyncCallback_l();
3744}
3745
Eric Laurent81784c32012-11-19 14:55:58 -08003746// shared by MIXER and DIRECT, overridden by DUPLICATING
3747void AudioFlinger::PlaybackThread::threadLoop_standby()
3748{
3749 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003750 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003751 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003752 // discard any pending drain or write ack by incrementing sequence
3753 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3754 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003755 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003756 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3757 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003758 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003759 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003760}
3761
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003762void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3763{
3764 ALOGV("signal playback thread");
3765 broadcast_l();
3766}
3767
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003768void AudioFlinger::PlaybackThread::onAsyncError()
3769{
3770 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3771 invalidateTracks((audio_stream_type_t)i);
3772 }
3773}
3774
Eric Laurent81784c32012-11-19 14:55:58 -08003775void AudioFlinger::MixerThread::threadLoop_mix()
3776{
Eric Laurent81784c32012-11-19 14:55:58 -08003777 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003778 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003779 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003780 // increase sleep time progressively when application underrun condition clears.
3781 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3782 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3783 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003784 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003785 sleepTimeShift--;
3786 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003787 mSleepTimeUs = 0;
3788 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003789 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003790
Eric Laurent81784c32012-11-19 14:55:58 -08003791}
3792
3793void AudioFlinger::MixerThread::threadLoop_sleepTime()
3794{
3795 // If no tracks are ready, sleep once for the duration of an output
3796 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003797 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003798 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003799 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3800 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3801 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003802 }
3803 // reduce sleep time in case of consecutive application underruns to avoid
3804 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3805 // duration we would end up writing less data than needed by the audio HAL if
3806 // the condition persists.
3807 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3808 sleepTimeShift++;
3809 }
3810 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003811 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003812 }
3813 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003814 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3815 // before effects processing or output.
3816 if (mMixerBufferValid) {
3817 memset(mMixerBuffer, 0, mMixerBufferSize);
3818 } else {
3819 memset(mSinkBuffer, 0, mSinkBufferSize);
3820 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003821 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003822 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3823 "anticipated start");
3824 }
3825 // TODO add standby time extension fct of effect tail
3826}
3827
3828// prepareTracks_l() must be called with ThreadBase::mLock held
3829AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3830 Vector< sp<Track> > *tracksToRemove)
3831{
3832
3833 mixer_state mixerStatus = MIXER_IDLE;
3834 // find out which tracks need to be processed
3835 size_t count = mActiveTracks.size();
3836 size_t mixedTracks = 0;
3837 size_t tracksWithEffect = 0;
3838 // counts only _active_ fast tracks
3839 size_t fastTracks = 0;
3840 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3841
3842 float masterVolume = mMasterVolume;
3843 bool masterMute = mMasterMute;
3844
3845 if (masterMute) {
3846 masterVolume = 0;
3847 }
3848 // Delegate master volume control to effect in output mix effect chain if needed
3849 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3850 if (chain != 0) {
3851 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3852 chain->setVolume_l(&v, &v);
3853 masterVolume = (float)((v + (1 << 23)) >> 24);
3854 chain.clear();
3855 }
3856
3857 // prepare a new state to push
3858 FastMixerStateQueue *sq = NULL;
3859 FastMixerState *state = NULL;
3860 bool didModify = false;
3861 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003862 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003863 sq = mFastMixer->sq();
3864 state = sq->begin();
3865 }
3866
Andy Hung69aed5f2014-02-25 17:24:40 -08003867 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003868 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003869
Eric Laurent81784c32012-11-19 14:55:58 -08003870 for (size_t i=0 ; i<count ; i++) {
Andy Hung2f366df2016-10-31 14:01:16 -07003871 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003872
3873 // this const just means the local variable doesn't change
3874 Track* const track = t.get();
3875
3876 // process fast tracks
3877 if (track->isFastTrack()) {
3878
3879 // It's theoretically possible (though unlikely) for a fast track to be created
3880 // and then removed within the same normal mix cycle. This is not a problem, as
3881 // the track never becomes active so it's fast mixer slot is never touched.
3882 // The converse, of removing an (active) track and then creating a new track
3883 // at the identical fast mixer slot within the same normal mix cycle,
3884 // is impossible because the slot isn't marked available until the end of each cycle.
3885 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003886 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003887 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3888 FastTrack *fastTrack = &state->mFastTracks[j];
3889
3890 // Determine whether the track is currently in underrun condition,
3891 // and whether it had a recent underrun.
3892 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3893 FastTrackUnderruns underruns = ftDump->mUnderruns;
3894 uint32_t recentFull = (underruns.mBitFields.mFull -
3895 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3896 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3897 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3898 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3899 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3900 uint32_t recentUnderruns = recentPartial + recentEmpty;
3901 track->mObservedUnderruns = underruns;
3902 // don't count underruns that occur while stopping or pausing
3903 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003904 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3905 recentUnderruns > 0) {
3906 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3907 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003908 } else {
3909 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003910 }
3911
3912 // This is similar to the state machine for normal tracks,
3913 // with a few modifications for fast tracks.
3914 bool isActive = true;
3915 switch (track->mState) {
3916 case TrackBase::STOPPING_1:
3917 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003919 track->mState = TrackBase::STOPPING_2;
3920 }
3921 break;
3922 case TrackBase::PAUSING:
3923 // ramp down is not yet implemented
3924 track->setPaused();
3925 break;
3926 case TrackBase::RESUMING:
3927 // ramp up is not yet implemented
3928 track->mState = TrackBase::ACTIVE;
3929 break;
3930 case TrackBase::ACTIVE:
3931 if (recentFull > 0 || recentPartial > 0) {
3932 // track has provided at least some frames recently: reset retry count
3933 track->mRetryCount = kMaxTrackRetries;
3934 }
3935 if (recentUnderruns == 0) {
3936 // no recent underruns: stay active
3937 break;
3938 }
3939 // there has recently been an underrun of some kind
3940 if (track->sharedBuffer() == 0) {
3941 // were any of the recent underruns "empty" (no frames available)?
3942 if (recentEmpty == 0) {
3943 // no, then ignore the partial underruns as they are allowed indefinitely
3944 break;
3945 }
3946 // there has recently been an "empty" underrun: decrement the retry counter
3947 if (--(track->mRetryCount) > 0) {
3948 break;
3949 }
3950 // indicate to client process that the track was disabled because of underrun;
3951 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003952 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003953 // remove from active list, but state remains ACTIVE [confusing but true]
3954 isActive = false;
3955 break;
3956 }
3957 // fall through
3958 case TrackBase::STOPPING_2:
3959 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003960 case TrackBase::STOPPED:
3961 case TrackBase::FLUSHED: // flush() while active
3962 // Check for presentation complete if track is inactive
3963 // We have consumed all the buffers of this track.
3964 // This would be incomplete if we auto-paused on underrun
3965 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003966 uint32_t latency = 0;
3967 status_t result = mOutput->stream->getLatency(&latency);
3968 ALOGE_IF(result != OK,
3969 "Error when retrieving output stream latency: %d", result);
3970 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003971 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003972 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3973 // track stays in active list until presentation is complete
3974 break;
3975 }
3976 }
3977 if (track->isStopping_2()) {
3978 track->mState = TrackBase::STOPPED;
3979 }
3980 if (track->isStopped()) {
3981 // Can't reset directly, as fast mixer is still polling this track
3982 // track->reset();
3983 // So instead mark this track as needing to be reset after push with ack
3984 resetMask |= 1 << i;
3985 }
3986 isActive = false;
3987 break;
3988 case TrackBase::IDLE:
3989 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003990 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003991 }
3992
3993 if (isActive) {
3994 // was it previously inactive?
3995 if (!(state->mTrackMask & (1 << j))) {
3996 ExtendedAudioBufferProvider *eabp = track;
3997 VolumeProvider *vp = track;
3998 fastTrack->mBufferProvider = eabp;
3999 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004000 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004001 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004002 fastTrack->mGeneration++;
4003 state->mTrackMask |= 1 << j;
4004 didModify = true;
4005 // no acknowledgement required for newly active tracks
4006 }
4007 // cache the combined master volume and stream type volume for fast mixer; this
4008 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004009 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004010 ++fastTracks;
4011 } else {
4012 // was it previously active?
4013 if (state->mTrackMask & (1 << j)) {
4014 fastTrack->mBufferProvider = NULL;
4015 fastTrack->mGeneration++;
4016 state->mTrackMask &= ~(1 << j);
4017 didModify = true;
4018 // If any fast tracks were removed, we must wait for acknowledgement
4019 // because we're about to decrement the last sp<> on those tracks.
4020 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4021 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004022 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4023 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4024 j, track->mState, state->mTrackMask, recentUnderruns,
4025 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004026 }
4027 tracksToRemove->add(track);
4028 // Avoids a misleading display in dumpsys
4029 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4030 }
4031 continue;
4032 }
4033
4034 { // local variable scope to avoid goto warning
4035
4036 audio_track_cblk_t* cblk = track->cblk();
4037
4038 // The first time a track is added we wait
4039 // for all its buffers to be filled before processing it
4040 int name = track->name();
4041 // make sure that we have enough frames to mix one full buffer.
4042 // enforce this condition only once to enable draining the buffer in case the client
4043 // app does not call stop() and relies on underrun to stop:
4044 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4045 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004046 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004047 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004048 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004049
4050 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004051 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004052 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4053 // add frames already consumed but not yet released by the resampler
4054 // because mAudioTrackServerProxy->framesReady() will include these frames
4055 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4056
Eric Laurent81784c32012-11-19 14:55:58 -08004057 uint32_t minFrames = 1;
4058 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4059 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004060 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004061 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004062
4063 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004064 if (ATRACE_ENABLED()) {
4065 // I wish we had formatted trace names
4066 char traceName[16];
4067 strcpy(traceName, "nRdy");
4068 int name = track->name();
4069 if (AudioMixer::TRACK0 <= name &&
4070 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4071 name -= AudioMixer::TRACK0;
4072 traceName[4] = (name / 10) + '0';
4073 traceName[5] = (name % 10) + '0';
4074 } else {
4075 traceName[4] = '?';
4076 traceName[5] = '?';
4077 }
4078 traceName[6] = '\0';
4079 ATRACE_INT(traceName, framesReady);
4080 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004081 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004082 !track->isPaused() && !track->isTerminated())
4083 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004084 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004085
4086 mixedTracks++;
4087
Andy Hung69aed5f2014-02-25 17:24:40 -08004088 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4089 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004090 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004091 if (track->mainBuffer() != mSinkBuffer &&
4092 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004093 if (mEffectBufferEnabled) {
4094 mEffectBufferValid = true; // Later can set directly.
4095 }
Eric Laurent81784c32012-11-19 14:55:58 -08004096 chain = getEffectChain_l(track->sessionId());
4097 // Delegate volume control to effect in track effect chain if needed
4098 if (chain != 0) {
4099 tracksWithEffect++;
4100 } else {
4101 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4102 "session %d",
4103 name, track->sessionId());
4104 }
4105 }
4106
4107
4108 int param = AudioMixer::VOLUME;
4109 if (track->mFillingUpStatus == Track::FS_FILLED) {
4110 // no ramp for the first volume setting
4111 track->mFillingUpStatus = Track::FS_ACTIVE;
4112 if (track->mState == TrackBase::RESUMING) {
4113 track->mState = TrackBase::ACTIVE;
4114 param = AudioMixer::RAMP_VOLUME;
4115 }
4116 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004117 // FIXME should not make a decision based on mServer
4118 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004119 // If the track is stopped before the first frame was mixed,
4120 // do not apply ramp
4121 param = AudioMixer::RAMP_VOLUME;
4122 }
4123
4124 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004125 uint32_t vl, vr; // in U8.24 integer format
4126 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004127 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004128 vl = vr = 0;
4129 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004130 if (track->isPausing()) {
4131 track->setPaused();
4132 }
4133 } else {
4134
4135 // read original volumes with volume control
4136 float typeVolume = mStreamTypes[track->streamType()].volume;
4137 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004138 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004139 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004140 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4141 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004142 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004143 if (vlf > GAIN_FLOAT_UNITY) {
4144 ALOGV("Track left volume out of range: %.3g", vlf);
4145 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004146 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004147 if (vrf > GAIN_FLOAT_UNITY) {
4148 ALOGV("Track right volume out of range: %.3g", vrf);
4149 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004150 }
4151 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004152 vlf *= v;
4153 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004154 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004155 // then derive vl and vr as U8.24 versions for the effect chain
4156 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4157 vl = (uint32_t) (scaleto8_24 * vlf);
4158 vr = (uint32_t) (scaleto8_24 * vrf);
4159 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004160 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004161 // send level comes from shared memory and so may be corrupt
4162 if (sendLevel > MAX_GAIN_INT) {
4163 ALOGV("Track send level out of range: %04X", sendLevel);
4164 sendLevel = MAX_GAIN_INT;
4165 }
Andy Hung6be49402014-05-30 10:42:03 -07004166 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4167 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004168 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004169
Eric Laurent81784c32012-11-19 14:55:58 -08004170 // Delegate volume control to effect in track effect chain if needed
4171 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4172 // Do not ramp volume if volume is controlled by effect
4173 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004174 // Update remaining floating point volume levels
4175 vlf = (float)vl / (1 << 24);
4176 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004177 track->mHasVolumeController = true;
4178 } else {
4179 // force no volume ramp when volume controller was just disabled or removed
4180 // from effect chain to avoid volume spike
4181 if (track->mHasVolumeController) {
4182 param = AudioMixer::VOLUME;
4183 }
4184 track->mHasVolumeController = false;
4185 }
4186
Eric Laurent81784c32012-11-19 14:55:58 -08004187 // XXX: these things DON'T need to be done each time
4188 mAudioMixer->setBufferProvider(name, track);
4189 mAudioMixer->enable(name);
4190
Andy Hung6be49402014-05-30 10:42:03 -07004191 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4192 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4193 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004194 mAudioMixer->setParameter(
4195 name,
4196 AudioMixer::TRACK,
4197 AudioMixer::FORMAT, (void *)track->format());
4198 mAudioMixer->setParameter(
4199 name,
4200 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004201 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004202 mAudioMixer->setParameter(
4203 name,
4204 AudioMixer::TRACK,
4205 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004206 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004207 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004208 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004209 if (reqSampleRate == 0) {
4210 reqSampleRate = mSampleRate;
4211 } else if (reqSampleRate > maxSampleRate) {
4212 reqSampleRate = maxSampleRate;
4213 }
Eric Laurent81784c32012-11-19 14:55:58 -08004214 mAudioMixer->setParameter(
4215 name,
4216 AudioMixer::RESAMPLE,
4217 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004218 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004219
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004220 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004221 mAudioMixer->setParameter(
4222 name,
4223 AudioMixer::TIMESTRETCH,
4224 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004225 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004226
Andy Hung69aed5f2014-02-25 17:24:40 -08004227 /*
4228 * Select the appropriate output buffer for the track.
4229 *
Andy Hung98ef9782014-03-04 14:46:50 -08004230 * Tracks with effects go into their own effects chain buffer
4231 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004232 *
4233 * Other tracks can use mMixerBuffer for higher precision
4234 * channel accumulation. If this buffer is enabled
4235 * (mMixerBufferEnabled true), then selected tracks will accumulate
4236 * into it.
4237 *
4238 */
4239 if (mMixerBufferEnabled
4240 && (track->mainBuffer() == mSinkBuffer
4241 || track->mainBuffer() == mMixerBuffer)) {
4242 mAudioMixer->setParameter(
4243 name,
4244 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004245 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004246 mAudioMixer->setParameter(
4247 name,
4248 AudioMixer::TRACK,
4249 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4250 // TODO: override track->mainBuffer()?
4251 mMixerBufferValid = true;
4252 } else {
4253 mAudioMixer->setParameter(
4254 name,
4255 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004256 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004257 mAudioMixer->setParameter(
4258 name,
4259 AudioMixer::TRACK,
4260 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4261 }
Eric Laurent81784c32012-11-19 14:55:58 -08004262 mAudioMixer->setParameter(
4263 name,
4264 AudioMixer::TRACK,
4265 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4266
4267 // reset retry count
4268 track->mRetryCount = kMaxTrackRetries;
4269
4270 // If one track is ready, set the mixer ready if:
4271 // - the mixer was not ready during previous round OR
4272 // - no other track is not ready
4273 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4274 mixerStatus != MIXER_TRACKS_ENABLED) {
4275 mixerStatus = MIXER_TRACKS_READY;
4276 }
4277 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004278 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004279 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4280 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004281 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004282 } else {
4283 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004284 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004285
Eric Laurent81784c32012-11-19 14:55:58 -08004286 // clear effect chain input buffer if an active track underruns to avoid sending
4287 // previous audio buffer again to effects
4288 chain = getEffectChain_l(track->sessionId());
4289 if (chain != 0) {
4290 chain->clearInputBuffer();
4291 }
4292
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004293 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004294 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4295 track->isStopped() || track->isPaused()) {
4296 // We have consumed all the buffers of this track.
4297 // Remove it from the list of active tracks.
4298 // TODO: use actual buffer filling status instead of latency when available from
4299 // audio HAL
4300 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004301 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004302 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4303 if (track->isStopped()) {
4304 track->reset();
4305 }
4306 tracksToRemove->add(track);
4307 }
4308 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004309 // No buffers for this track. Give it a few chances to
4310 // fill a buffer, then remove it from active list.
4311 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004312 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004313 tracksToRemove->add(track);
4314 // indicate to client process that the track was disabled because of underrun;
4315 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004316 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004317 // If one track is not ready, mark the mixer also not ready if:
4318 // - the mixer was ready during previous round OR
4319 // - no other track is ready
4320 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4321 mixerStatus != MIXER_TRACKS_READY) {
4322 mixerStatus = MIXER_TRACKS_ENABLED;
4323 }
4324 }
4325 mAudioMixer->disable(name);
4326 }
4327
4328 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004329
4330 }
4331
4332 // Push the new FastMixer state if necessary
4333 bool pauseAudioWatchdog = false;
4334 if (didModify) {
4335 state->mFastTracksGen++;
4336 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4337 if (kUseFastMixer == FastMixer_Dynamic &&
4338 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4339 state->mCommand = FastMixerState::COLD_IDLE;
4340 state->mColdFutexAddr = &mFastMixerFutex;
4341 state->mColdGen++;
4342 mFastMixerFutex = 0;
4343 if (kUseFastMixer == FastMixer_Dynamic) {
4344 mNormalSink = mOutputSink;
4345 }
4346 // If we go into cold idle, need to wait for acknowledgement
4347 // so that fast mixer stops doing I/O.
4348 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4349 pauseAudioWatchdog = true;
4350 }
Eric Laurent81784c32012-11-19 14:55:58 -08004351 }
4352 if (sq != NULL) {
4353 sq->end(didModify);
4354 sq->push(block);
4355 }
4356#ifdef AUDIO_WATCHDOG
4357 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4358 mAudioWatchdog->pause();
4359 }
4360#endif
4361
4362 // Now perform the deferred reset on fast tracks that have stopped
4363 while (resetMask != 0) {
4364 size_t i = __builtin_ctz(resetMask);
4365 ALOG_ASSERT(i < count);
4366 resetMask &= ~(1 << i);
Andy Hung2f366df2016-10-31 14:01:16 -07004367 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004368 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4369 track->reset();
4370 }
4371
4372 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004373 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004374
Eric Laurent97d547d2014-09-02 14:45:53 -07004375 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4376 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004377 }
4378
4379 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004380 // as long as there are effects we should clear the effects buffer, to avoid
4381 // passing a non-clean buffer to the effect chain
4382 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004383 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004384 // sink or mix buffer must be cleared if all tracks are connected to an
4385 // effect chain as in this case the mixer will not write to the sink or mix buffer
4386 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004387 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4388 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004389 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004390 if (mMixerBufferValid) {
4391 memset(mMixerBuffer, 0, mMixerBufferSize);
4392 // TODO: In testing, mSinkBuffer below need not be cleared because
4393 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4394 // after mixing.
4395 //
4396 // To enforce this guarantee:
4397 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4398 // (mixedTracks == 0 && fastTracks > 0))
4399 // must imply MIXER_TRACKS_READY.
4400 // Later, we may clear buffers regardless, and skip much of this logic.
4401 }
Andy Hung98ef9782014-03-04 14:46:50 -08004402 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004403 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004404 }
4405
4406 // if any fast tracks, then status is ready
4407 mMixerStatusIgnoringFastTracks = mixerStatus;
4408 if (fastTracks > 0) {
4409 mixerStatus = MIXER_TRACKS_READY;
4410 }
4411 return mixerStatus;
4412}
4413
Eric Laurentad7dd962016-09-22 12:38:37 -07004414// trackCountForUid_l() must be called with ThreadBase::mLock held
4415uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4416{
4417 uint32_t trackCount = 0;
4418 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004419 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004420 trackCount++;
4421 }
4422 }
4423 return trackCount;
4424}
4425
Eric Laurent81784c32012-11-19 14:55:58 -08004426// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004427int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004428 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004429{
Eric Laurentad7dd962016-09-22 12:38:37 -07004430 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4431 return -1;
4432 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004433 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004434}
4435
4436// deleteTrackName_l() must be called with ThreadBase::mLock held
4437void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4438{
4439 ALOGV("remove track (%d) and delete from mixer", name);
4440 mAudioMixer->deleteTrackName(name);
4441}
4442
Eric Laurent10351942014-05-08 18:49:52 -07004443// checkForNewParameter_l() must be called with ThreadBase::mLock held
4444bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4445 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004446{
Eric Laurent81784c32012-11-19 14:55:58 -08004447 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004448 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004449
Eric Laurent10351942014-05-08 18:49:52 -07004450 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004451
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004452 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004453
Eric Laurent10351942014-05-08 18:49:52 -07004454 AudioParameter param = AudioParameter(keyValuePair);
4455 int value;
4456 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4457 reconfig = true;
4458 }
4459 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004460 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004461 status = BAD_VALUE;
4462 } else {
4463 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004464 reconfig = true;
4465 }
Eric Laurent10351942014-05-08 18:49:52 -07004466 }
4467 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004468 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004469 status = BAD_VALUE;
4470 } else {
4471 // no need to save value, since it's constant
4472 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004473 }
Eric Laurent10351942014-05-08 18:49:52 -07004474 }
4475 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4476 // do not accept frame count changes if tracks are open as the track buffer
4477 // size depends on frame count and correct behavior would not be guaranteed
4478 // if frame count is changed after track creation
4479 if (!mTracks.isEmpty()) {
4480 status = INVALID_OPERATION;
4481 } else {
4482 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004483 }
Eric Laurent10351942014-05-08 18:49:52 -07004484 }
4485 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004486#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004487 // when changing the audio output device, call addBatteryData to notify
4488 // the change
4489 if (mOutDevice != value) {
4490 uint32_t params = 0;
4491 // check whether speaker is on
4492 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4493 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004494 }
Eric Laurent10351942014-05-08 18:49:52 -07004495
4496 audio_devices_t deviceWithoutSpeaker
4497 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4498 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004499 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004500 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4501 }
4502
4503 if (params != 0) {
4504 addBatteryData(params);
4505 }
4506 }
Eric Laurent81784c32012-11-19 14:55:58 -08004507#endif
4508
Eric Laurent10351942014-05-08 18:49:52 -07004509 // forward device change to effects that have requested to be
4510 // aware of attached audio device.
4511 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004512 a2dpDeviceChanged =
4513 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004514 mOutDevice = value;
4515 for (size_t i = 0; i < mEffectChains.size(); i++) {
4516 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004517 }
4518 }
Eric Laurent10351942014-05-08 18:49:52 -07004519 }
Eric Laurent81784c32012-11-19 14:55:58 -08004520
Eric Laurent10351942014-05-08 18:49:52 -07004521 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004522 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004523 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004524 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004525 mStandby = true;
4526 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004527 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004528 }
Eric Laurent10351942014-05-08 18:49:52 -07004529 if (status == NO_ERROR && reconfig) {
4530 readOutputParameters_l();
4531 delete mAudioMixer;
4532 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4533 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004534 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004535 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004536 if (name < 0) {
4537 break;
4538 }
4539 mTracks[i]->mName = name;
4540 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004541 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004542 }
Eric Laurent81784c32012-11-19 14:55:58 -08004543 }
4544
Eric Laurent42537be2016-01-08 17:16:42 -08004545 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004546}
4547
4548
4549void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4550{
Eric Laurent81784c32012-11-19 14:55:58 -08004551 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004552 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004553 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004554 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004555
4556 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004557 // while we are dumping it. It may be inconsistent, but it won't mutate!
4558 // This is a large object so we place it on the heap.
4559 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4560 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4561 copy->dump(fd);
4562 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004563
4564#ifdef STATE_QUEUE_DUMP
4565 // Similar for state queue
4566 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4567 observerCopy.dump(fd);
4568 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4569 mutatorCopy.dump(fd);
4570#endif
4571
Glenn Kasten46909e72013-02-26 09:20:22 -08004572#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004573 // Write the tee output to a .wav file
4574 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004575#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004576
4577#ifdef AUDIO_WATCHDOG
4578 if (mAudioWatchdog != 0) {
4579 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4580 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4581 wdCopy.dump(fd);
4582 }
4583#endif
4584}
4585
4586uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4587{
4588 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4589}
4590
4591uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4592{
4593 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4594}
4595
4596void AudioFlinger::MixerThread::cacheParameters_l()
4597{
4598 PlaybackThread::cacheParameters_l();
4599
4600 // FIXME: Relaxed timing because of a certain device that can't meet latency
4601 // Should be reduced to 2x after the vendor fixes the driver issue
4602 // increase threshold again due to low power audio mode. The way this warning
4603 // threshold is calculated and its usefulness should be reconsidered anyway.
4604 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4605}
4606
4607// ----------------------------------------------------------------------------
4608
4609AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004610 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4611 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004612 // mLeftVolFloat, mRightVolFloat
4613{
4614}
4615
Eric Laurentbfb1b832013-01-07 09:53:42 -08004616AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4617 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004618 ThreadBase::type_t type, bool systemReady)
4619 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004620 // mLeftVolFloat, mRightVolFloat
4621{
4622}
4623
Eric Laurent81784c32012-11-19 14:55:58 -08004624AudioFlinger::DirectOutputThread::~DirectOutputThread()
4625{
4626}
4627
Eric Laurent5850c4c2016-11-10 13:04:31 -08004628void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004629{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004630 float left, right;
4631
4632 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4633 left = right = 0;
4634 } else {
4635 float typeVolume = mStreamTypes[track->streamType()].volume;
4636 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004637 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004638 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4639 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4640 if (left > GAIN_FLOAT_UNITY) {
4641 left = GAIN_FLOAT_UNITY;
4642 }
4643 left *= v;
4644 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4645 if (right > GAIN_FLOAT_UNITY) {
4646 right = GAIN_FLOAT_UNITY;
4647 }
4648 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004649 }
4650
4651 if (lastTrack) {
4652 if (left != mLeftVolFloat || right != mRightVolFloat) {
4653 mLeftVolFloat = left;
4654 mRightVolFloat = right;
4655
4656 // Convert volumes from float to 8.24
4657 uint32_t vl = (uint32_t)(left * (1 << 24));
4658 uint32_t vr = (uint32_t)(right * (1 << 24));
4659
4660 // Delegate volume control to effect in track effect chain if needed
4661 // only one effect chain can be present on DirectOutputThread, so if
4662 // there is one, the track is connected to it
4663 if (!mEffectChains.isEmpty()) {
4664 mEffectChains[0]->setVolume_l(&vl, &vr);
4665 left = (float)vl / (1 << 24);
4666 right = (float)vr / (1 << 24);
4667 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004668 status_t result = mOutput->stream->setVolume(left, right);
4669 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004670 }
4671 }
4672}
4673
Phil Burk43b4dcc2015-06-09 16:53:44 -07004674void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4675{
4676 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hung2f366df2016-10-31 14:01:16 -07004677 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004678
Eric Laurent0f0631e2015-07-06 18:01:25 -07004679 if (previousTrack != 0 && latestTrack != 0) {
4680 if (mType == DIRECT) {
4681 if (previousTrack.get() != latestTrack.get()) {
4682 mFlushPending = true;
4683 }
4684 } else /* mType == OFFLOAD */ {
4685 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4686 mFlushPending = true;
4687 }
4688 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004689 }
4690 PlaybackThread::onAddNewTrack_l();
4691}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004692
Eric Laurent81784c32012-11-19 14:55:58 -08004693AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4694 Vector< sp<Track> > *tracksToRemove
4695)
4696{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004697 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004698 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004699 bool doHwPause = false;
4700 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004701
4702 // find out which tracks need to be processed
Eric Laurent5850c4c2016-11-10 13:04:31 -08004703 for (const sp<Track> &t : mActiveTracks) {
4704 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004705 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004706 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004707 continue;
4708 }
4709
Eric Laurent5850c4c2016-11-10 13:04:31 -08004710 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004711#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004712 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004713#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004714 // Only consider last track started for volume and mixer state control.
4715 // In theory an older track could underrun and restart after the new one starts
4716 // but as we only care about the transition phase between two tracks on a
4717 // direct output, it is not a problem to ignore the underrun case.
Eric Laurent5850c4c2016-11-10 13:04:31 -08004718 sp<Track> l = mActiveTracks.getLatest();
4719 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004720
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004721 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004722 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004723 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004724 doHwPause = true;
4725 mHwPaused = true;
4726 }
4727 tracksToRemove->add(track);
4728 } else if (track->isFlushPending()) {
4729 track->flushAck();
4730 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004731 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004732 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004733 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004734 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004735 if (last) {
4736 mLeftVolFloat = mRightVolFloat = -1.0;
4737 if (mHwPaused) {
4738 doHwResume = true;
4739 mHwPaused = false;
4740 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004741 }
4742 }
4743
Eric Laurent81784c32012-11-19 14:55:58 -08004744 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004745 // for all its buffers to be filled before processing it.
4746 // Allow draining the buffer in case the client
4747 // app does not call stop() and relies on underrun to stop:
4748 // hence the test on (track->mRetryCount > 1).
4749 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004750 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004751 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004752 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004753 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004754 minFrames = mNormalFrameCount;
4755 } else {
4756 minFrames = 1;
4757 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004758
Eric Laurentab5cdba2014-06-09 17:22:27 -07004759 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4760 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004761 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004762 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004763
4764 if (track->mFillingUpStatus == Track::FS_FILLED) {
4765 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004766 if (last) {
4767 // make sure processVolume_l() will apply new volume even if 0
4768 mLeftVolFloat = mRightVolFloat = -1.0;
4769 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004770 if (!mHwSupportsPause) {
4771 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004772 }
4773 }
4774
4775 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004776 processVolume_l(track, last);
4777 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004778 sp<Track> previousTrack = mPreviousTrack.promote();
4779 if (previousTrack != 0) {
4780 if (track != previousTrack.get()) {
4781 // Flush any data still being written from last track
4782 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004783 // Invalidate previous track to force a seek when resuming.
4784 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004785 }
4786 }
4787 mPreviousTrack = track;
4788
Eric Laurentd595b7c2013-04-03 17:27:56 -07004789 // reset retry count
4790 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004791 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004792 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004793 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004794 doHwResume = true;
4795 mHwPaused = false;
4796 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004797 }
Eric Laurent81784c32012-11-19 14:55:58 -08004798 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004799 // clear effect chain input buffer if the last active track started underruns
4800 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004801 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004802 mEffectChains[0]->clearInputBuffer();
4803 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004804 if (track->isStopping_1()) {
4805 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004806 if (last && mHwPaused) {
4807 doHwResume = true;
4808 mHwPaused = false;
4809 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004810 }
4811 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4812 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004813 // We have consumed all the buffers of this track.
4814 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004815 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004816 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004817 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4818 } else {
4819 audioHALFrames = 0;
4820 }
4821
Andy Hung818e7a32016-02-16 18:08:07 -08004822 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004823 if (mStandby || !last ||
4824 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004825 if (track->isStopping_2()) {
4826 track->mState = TrackBase::STOPPED;
4827 }
Eric Laurent81784c32012-11-19 14:55:58 -08004828 if (track->isStopped()) {
4829 track->reset();
4830 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004831 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004832 }
4833 } else {
4834 // No buffers for this track. Give it a few chances to
4835 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004836 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004837 if (--(track->mRetryCount) <= 0) {
4838 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004839 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004840 // indicate to client process that the track was disabled because of underrun;
4841 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004842 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004843 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004844 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4845 "minFrames = %u, mFormat = %#x",
4846 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004847 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004848 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004849 doHwPause = true;
4850 mHwPaused = true;
4851 }
Eric Laurent81784c32012-11-19 14:55:58 -08004852 }
4853 }
4854 }
4855 }
4856
Eric Laurentd1f69b02014-12-15 14:33:13 -08004857 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004858 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004859 for (size_t i = 0; i < mTracks.size(); i++) {
4860 if (mTracks[i]->isFlushPending()) {
4861 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004862 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004863 }
4864 }
4865 }
4866
4867 // make sure the pause/flush/resume sequence is executed in the right order.
4868 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4869 // before flush and then resume HW. This can happen in case of pause/flush/resume
4870 // if resume is received before pause is executed.
4871 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004872 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004873 status_t result = mOutput->stream->pause();
4874 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004875 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004876 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004877 flushHw_l();
4878 }
4879 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004880 status_t result = mOutput->stream->resume();
4881 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004882 }
Eric Laurent81784c32012-11-19 14:55:58 -08004883 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004884 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004885
4886 return mixerStatus;
4887}
4888
4889void AudioFlinger::DirectOutputThread::threadLoop_mix()
4890{
Eric Laurent81784c32012-11-19 14:55:58 -08004891 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004892 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004893 // output audio to hardware
4894 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004895 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004896 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004897 status_t status = mActiveTrack->getNextBuffer(&buffer);
4898 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004899 // no need to pad with 0 for compressed audio
4900 if (audio_has_proportional_frames(mFormat)) {
4901 memset(curBuf, 0, frameCount * mFrameSize);
4902 }
Eric Laurent81784c32012-11-19 14:55:58 -08004903 break;
4904 }
4905 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4906 frameCount -= buffer.frameCount;
4907 curBuf += buffer.frameCount * mFrameSize;
4908 mActiveTrack->releaseBuffer(&buffer);
4909 }
Andy Hung2098f272014-02-27 14:00:06 -08004910 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004911 mSleepTimeUs = 0;
4912 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004913 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004914}
4915
4916void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4917{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004918 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004919 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004920 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004921 return;
4922 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004923 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004924 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07004925 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004926 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004927 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004928 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004929 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004930 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004931 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004932 }
4933}
4934
Eric Laurentd1f69b02014-12-15 14:33:13 -08004935void AudioFlinger::DirectOutputThread::threadLoop_exit()
4936{
4937 {
4938 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004939 for (size_t i = 0; i < mTracks.size(); i++) {
4940 if (mTracks[i]->isFlushPending()) {
4941 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004942 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004943 }
4944 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004945 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004946 flushHw_l();
4947 }
4948 }
4949 PlaybackThread::threadLoop_exit();
4950}
4951
4952// must be called with thread mutex locked
4953bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4954{
4955 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004956 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004957
vivek mehta9cd7ad12016-03-17 00:18:29 -07004958 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4959 return !mStandby;
4960 }
4961
Eric Laurentd1f69b02014-12-15 14:33:13 -08004962 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4963 // after a timeout and we will enter standby then.
4964 if (mTracks.size() > 0) {
4965 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004966 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4967 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004968 }
4969
Eric Laurent5cff4032015-05-26 13:49:58 -07004970 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004971}
4972
Eric Laurent81784c32012-11-19 14:55:58 -08004973// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004974int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07004975 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004976{
Eric Laurentad7dd962016-09-22 12:38:37 -07004977 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4978 return -1;
4979 }
Eric Laurent81784c32012-11-19 14:55:58 -08004980 return 0;
4981}
4982
4983// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004984void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004985{
4986}
4987
Eric Laurent10351942014-05-08 18:49:52 -07004988// checkForNewParameter_l() must be called with ThreadBase::mLock held
4989bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4990 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004991{
4992 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004993 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004994
Eric Laurent10351942014-05-08 18:49:52 -07004995 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004996
Eric Laurent10351942014-05-08 18:49:52 -07004997 AudioParameter param = AudioParameter(keyValuePair);
4998 int value;
4999 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5000 // forward device change to effects that have requested to be
5001 // aware of attached audio device.
5002 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005003 a2dpDeviceChanged =
5004 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005005 mOutDevice = value;
5006 for (size_t i = 0; i < mEffectChains.size(); i++) {
5007 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005008 }
5009 }
Eric Laurent81784c32012-11-19 14:55:58 -08005010 }
Eric Laurent10351942014-05-08 18:49:52 -07005011 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5012 // do not accept frame count changes if tracks are open as the track buffer
5013 // size depends on frame count and correct behavior would not be garantied
5014 // if frame count is changed after track creation
5015 if (!mTracks.isEmpty()) {
5016 status = INVALID_OPERATION;
5017 } else {
5018 reconfig = true;
5019 }
5020 }
5021 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005022 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005023 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005024 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005025 mStandby = true;
5026 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005027 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005028 }
5029 if (status == NO_ERROR && reconfig) {
5030 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005031 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005032 }
5033 }
5034
Eric Laurent42537be2016-01-08 17:16:42 -08005035 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005036}
5037
5038uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5039{
5040 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005041 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005042 time = PlaybackThread::activeSleepTimeUs();
5043 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005044 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005045 }
5046 return time;
5047}
5048
5049uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5050{
5051 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005052 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005053 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5054 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005055 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005056 }
5057 return time;
5058}
5059
5060uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5061{
5062 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005063 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005064 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5065 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005066 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005067 }
5068 return time;
5069}
5070
5071void AudioFlinger::DirectOutputThread::cacheParameters_l()
5072{
5073 PlaybackThread::cacheParameters_l();
5074
5075 // use shorter standby delay as on normal output to release
5076 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005077 // no delay on outputs with HW A/V sync
5078 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005079 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005080 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005081 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005082 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005083 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005084 }
Eric Laurent81784c32012-11-19 14:55:58 -08005085}
5086
Eric Laurente659ef42014-09-29 13:06:46 -07005087void AudioFlinger::DirectOutputThread::flushHw_l()
5088{
Phil Burk062e67a2015-02-11 13:40:50 -08005089 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005090 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005091 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005092}
5093
Eric Laurent81784c32012-11-19 14:55:58 -08005094// ----------------------------------------------------------------------------
5095
Eric Laurentbfb1b832013-01-07 09:53:42 -08005096AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005097 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005098 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005099 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005100 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005101 mDrainSequence(0),
5102 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005103{
5104}
5105
5106AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5107{
5108}
5109
5110void AudioFlinger::AsyncCallbackThread::onFirstRef()
5111{
5112 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5113}
5114
5115bool AudioFlinger::AsyncCallbackThread::threadLoop()
5116{
5117 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005118 uint32_t writeAckSequence;
5119 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005120 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005121
5122 {
5123 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005124 while (!((mWriteAckSequence & 1) ||
5125 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005126 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005127 exitPending())) {
5128 mWaitWorkCV.wait(mLock);
5129 }
5130
Eric Laurentbfb1b832013-01-07 09:53:42 -08005131 if (exitPending()) {
5132 break;
5133 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005134 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5135 mWriteAckSequence, mDrainSequence);
5136 writeAckSequence = mWriteAckSequence;
5137 mWriteAckSequence &= ~1;
5138 drainSequence = mDrainSequence;
5139 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005140 asyncError = mAsyncError;
5141 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005142 }
5143 {
Eric Laurent4de95592013-09-26 15:28:21 -07005144 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5145 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005146 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005147 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005148 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005149 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005150 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005151 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005152 if (asyncError) {
5153 playbackThread->onAsyncError();
5154 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005155 }
5156 }
5157 }
5158 return false;
5159}
5160
5161void AudioFlinger::AsyncCallbackThread::exit()
5162{
5163 ALOGV("AsyncCallbackThread::exit");
5164 Mutex::Autolock _l(mLock);
5165 requestExit();
5166 mWaitWorkCV.broadcast();
5167}
5168
Eric Laurent3b4529e2013-09-05 18:09:19 -07005169void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005170{
5171 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005172 // bit 0 is cleared
5173 mWriteAckSequence = sequence << 1;
5174}
5175
5176void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5177{
5178 Mutex::Autolock _l(mLock);
5179 // ignore unexpected callbacks
5180 if (mWriteAckSequence & 2) {
5181 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005182 mWaitWorkCV.signal();
5183 }
5184}
5185
Eric Laurent3b4529e2013-09-05 18:09:19 -07005186void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005187{
5188 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005189 // bit 0 is cleared
5190 mDrainSequence = sequence << 1;
5191}
5192
5193void AudioFlinger::AsyncCallbackThread::resetDraining()
5194{
5195 Mutex::Autolock _l(mLock);
5196 // ignore unexpected callbacks
5197 if (mDrainSequence & 2) {
5198 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005199 mWaitWorkCV.signal();
5200 }
5201}
5202
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005203void AudioFlinger::AsyncCallbackThread::setAsyncError()
5204{
5205 Mutex::Autolock _l(mLock);
5206 mAsyncError = true;
5207 mWaitWorkCV.signal();
5208}
5209
Eric Laurentbfb1b832013-01-07 09:53:42 -08005210
5211// ----------------------------------------------------------------------------
5212AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005213 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5214 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005215 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5216 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005217{
Eric Laurentfd477972013-10-25 18:10:40 -07005218 //FIXME: mStandby should be set to true by ThreadBase constructor
5219 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005220 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005221}
5222
Eric Laurentbfb1b832013-01-07 09:53:42 -08005223void AudioFlinger::OffloadThread::threadLoop_exit()
5224{
5225 if (mFlushPending || mHwPaused) {
5226 // If a flush is pending or track was paused, just discard buffered data
5227 flushHw_l();
5228 } else {
5229 mMixerStatus = MIXER_DRAIN_ALL;
5230 threadLoop_drain();
5231 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005232 if (mUseAsyncWrite) {
5233 ALOG_ASSERT(mCallbackThread != 0);
5234 mCallbackThread->exit();
5235 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005236 PlaybackThread::threadLoop_exit();
5237}
5238
5239AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5240 Vector< sp<Track> > *tracksToRemove
5241)
5242{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005243 size_t count = mActiveTracks.size();
5244
5245 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005246 bool doHwPause = false;
5247 bool doHwResume = false;
5248
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005249 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005250
Eric Laurentbfb1b832013-01-07 09:53:42 -08005251 // find out which tracks need to be processed
Eric Laurent5850c4c2016-11-10 13:04:31 -08005252 for (const sp<Track> &t : mActiveTracks) {
5253 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005254#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005255 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005256#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005257 // Only consider last track started for volume and mixer state control.
5258 // In theory an older track could underrun and restart after the new one starts
5259 // but as we only care about the transition phase between two tracks on a
5260 // direct output, it is not a problem to ignore the underrun case.
Eric Laurent5850c4c2016-11-10 13:04:31 -08005261 sp<Track> l = mActiveTracks.getLatest();
5262 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005263
Haynes Mathew George7844f672014-01-15 12:32:55 -08005264 if (track->isInvalid()) {
5265 ALOGW("An invalidated track shouldn't be in active list");
5266 tracksToRemove->add(track);
5267 continue;
5268 }
5269
5270 if (track->mState == TrackBase::IDLE) {
5271 ALOGW("An idle track shouldn't be in active list");
5272 continue;
5273 }
5274
Eric Laurentbfb1b832013-01-07 09:53:42 -08005275 if (track->isPausing()) {
5276 track->setPaused();
5277 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005278 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005279 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005280 mHwPaused = true;
5281 }
5282 // If we were part way through writing the mixbuffer to
5283 // the HAL we must save this until we resume
5284 // BUG - this will be wrong if a different track is made active,
5285 // in that case we want to discard the pending data in the
5286 // mixbuffer and tell the client to present it again when the
5287 // track is resumed
5288 mPausedWriteLength = mCurrentWriteLength;
5289 mPausedBytesRemaining = mBytesRemaining;
5290 mBytesRemaining = 0; // stop writing
5291 }
5292 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005293 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005294 if (track->isStopping_1()) {
5295 track->mRetryCount = kMaxTrackStopRetriesOffload;
5296 } else {
5297 track->mRetryCount = kMaxTrackRetriesOffload;
5298 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005299 track->flushAck();
5300 if (last) {
5301 mFlushPending = true;
5302 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005303 } else if (track->isResumePending()){
5304 track->resumeAck();
5305 if (last) {
5306 if (mPausedBytesRemaining) {
5307 // Need to continue write that was interrupted
5308 mCurrentWriteLength = mPausedWriteLength;
5309 mBytesRemaining = mPausedBytesRemaining;
5310 mPausedBytesRemaining = 0;
5311 }
5312 if (mHwPaused) {
5313 doHwResume = true;
5314 mHwPaused = false;
5315 // threadLoop_mix() will handle the case that we need to
5316 // resume an interrupted write
5317 }
5318 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005319 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005320
Eric Laurent3df841a2016-07-15 15:15:40 -07005321 mLeftVolFloat = mRightVolFloat = -1.0;
5322
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005323 // Do not handle new data in this iteration even if track->framesReady()
5324 mixerStatus = MIXER_TRACKS_ENABLED;
5325 }
5326 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005327 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005328 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005329 if (track->mFillingUpStatus == Track::FS_FILLED) {
5330 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005331 if (last) {
5332 // make sure processVolume_l() will apply new volume even if 0
5333 mLeftVolFloat = mRightVolFloat = -1.0;
5334 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005335 }
5336
5337 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005338 sp<Track> previousTrack = mPreviousTrack.promote();
5339 if (previousTrack != 0) {
5340 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005341 // Flush any data still being written from last track
5342 mBytesRemaining = 0;
5343 if (mPausedBytesRemaining) {
5344 // Last track was paused so we also need to flush saved
5345 // mixbuffer state and invalidate track so that it will
5346 // re-submit that unwritten data when it is next resumed
5347 mPausedBytesRemaining = 0;
5348 // Invalidate is a bit drastic - would be more efficient
5349 // to have a flag to tell client that some of the
5350 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005351 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005352 }
5353 // flush data already sent to the DSP if changing audio session as audio
5354 // comes from a different source. Also invalidate previous track to force a
5355 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005356 if (previousTrack->sessionId() != track->sessionId()) {
5357 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005358 }
5359 }
5360 }
5361 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005362 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005363 if (track->isStopping_1()) {
5364 track->mRetryCount = kMaxTrackStopRetriesOffload;
5365 } else {
5366 track->mRetryCount = kMaxTrackRetriesOffload;
5367 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005368 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005369 mixerStatus = MIXER_TRACKS_READY;
5370 }
5371 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005372 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005373 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005374 if (--(track->mRetryCount) <= 0) {
5375 // Hardware buffer can hold a large amount of audio so we must
5376 // wait for all current track's data to drain before we say
5377 // that the track is stopped.
5378 if (mBytesRemaining == 0) {
5379 // Only start draining when all data in mixbuffer
5380 // has been written
5381 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5382 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5383 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5384 if (last && !mStandby) {
5385 // do not modify drain sequence if we are already draining. This happens
5386 // when resuming from pause after drain.
5387 if ((mDrainSequence & 1) == 0) {
5388 mSleepTimeUs = 0;
5389 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5390 mixerStatus = MIXER_DRAIN_TRACK;
5391 mDrainSequence += 2;
5392 }
5393 if (mHwPaused) {
5394 // It is possible to move from PAUSED to STOPPING_1 without
5395 // a resume so we must ensure hardware is running
5396 doHwResume = true;
5397 mHwPaused = false;
5398 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005399 }
5400 }
Eric Laurente93cc032016-05-05 10:15:10 -07005401 } else if (last) {
5402 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5403 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005404 }
5405 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005406 // Drain has completed or we are in standby, signal presentation complete
5407 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005408 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005409 uint32_t latency = 0;
5410 status_t result = mOutput->stream->getLatency(&latency);
5411 ALOGE_IF(result != OK,
5412 "Error when retrieving output stream latency: %d", result);
5413 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005414 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005415 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416 track->presentationComplete(framesWritten, audioHALFrames);
5417 track->reset();
5418 tracksToRemove->add(track);
5419 }
5420 } else {
5421 // No buffers for this track. Give it a few chances to
5422 // fill a buffer, then remove it from active list.
5423 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005424 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005425 uint64_t position = 0;
5426 struct timespec unused;
5427 // The running check restarts the retry counter at least once.
5428 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5429 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5430 running = true;
5431 mOffloadUnderrunPosition = position;
5432 }
5433 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005434 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5435 (long long)position, (long long)mOffloadUnderrunPosition);
5436 }
5437 if (running) { // still running, give us more time.
5438 track->mRetryCount = kMaxTrackRetriesOffload;
5439 } else {
5440 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5441 track->name());
5442 tracksToRemove->add(track);
5443 // indicate to client process that the track was disabled because of underrun;
5444 // it will then automatically call start() when data is available
5445 track->disable();
5446 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005447 } else if (last){
5448 mixerStatus = MIXER_TRACKS_ENABLED;
5449 }
5450 }
5451 }
5452 // compute volume for this track
5453 processVolume_l(track, last);
5454 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005455
Eric Laurentea0fade2013-10-04 16:23:48 -07005456 // make sure the pause/flush/resume sequence is executed in the right order.
5457 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5458 // before flush and then resume HW. This can happen in case of pause/flush/resume
5459 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005460 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005461 status_t result = mOutput->stream->pause();
5462 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005463 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005464 if (mFlushPending) {
5465 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005466 }
Eric Laurentfd477972013-10-25 18:10:40 -07005467 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005468 status_t result = mOutput->stream->resume();
5469 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005470 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005471
Eric Laurentbfb1b832013-01-07 09:53:42 -08005472 // remove all the tracks that need to be...
5473 removeTracks_l(*tracksToRemove);
5474
5475 return mixerStatus;
5476}
5477
Eric Laurentbfb1b832013-01-07 09:53:42 -08005478// must be called with thread mutex locked
5479bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5480{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005481 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5482 mWriteAckSequence, mDrainSequence);
5483 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005484 return true;
5485 }
5486 return false;
5487}
5488
Eric Laurentbfb1b832013-01-07 09:53:42 -08005489bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5490{
5491 Mutex::Autolock _l(mLock);
5492 return waitingAsyncCallback_l();
5493}
5494
5495void AudioFlinger::OffloadThread::flushHw_l()
5496{
Eric Laurente659ef42014-09-29 13:06:46 -07005497 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005498 // Flush anything still waiting in the mixbuffer
5499 mCurrentWriteLength = 0;
5500 mBytesRemaining = 0;
5501 mPausedWriteLength = 0;
5502 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005503 // reset bytes written count to reflect that DSP buffers are empty after flush.
5504 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005505 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005506
Eric Laurentbfb1b832013-01-07 09:53:42 -08005507 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005508 // discard any pending drain or write ack by incrementing sequence
5509 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5510 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005511 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005512 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5513 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005514 }
5515}
5516
Haynes Mathew George05317d22016-05-03 16:34:26 -07005517void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5518{
5519 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005520 if (PlaybackThread::invalidateTracks_l(streamType)) {
5521 mFlushPending = true;
5522 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005523}
5524
Eric Laurentbfb1b832013-01-07 09:53:42 -08005525// ----------------------------------------------------------------------------
5526
Eric Laurent81784c32012-11-19 14:55:58 -08005527AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005528 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005529 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005530 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005531 mWaitTimeMs(UINT_MAX)
5532{
5533 addOutputTrack(mainThread);
5534}
5535
5536AudioFlinger::DuplicatingThread::~DuplicatingThread()
5537{
5538 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5539 mOutputTracks[i]->destroy();
5540 }
5541}
5542
5543void AudioFlinger::DuplicatingThread::threadLoop_mix()
5544{
5545 // mix buffers...
5546 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005547 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005548 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005549 if (mMixerBufferValid) {
5550 memset(mMixerBuffer, 0, mMixerBufferSize);
5551 } else {
5552 memset(mSinkBuffer, 0, mSinkBufferSize);
5553 }
Eric Laurent81784c32012-11-19 14:55:58 -08005554 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005555 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005556 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005557 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005558 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005559}
5560
5561void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5562{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005563 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005564 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005565 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005566 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005567 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005568 }
5569 } else if (mBytesWritten != 0) {
5570 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5571 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005572 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005573 } else {
5574 // flush remaining overflow buffers in output tracks
5575 writeFrames = 0;
5576 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005577 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005578 }
5579}
5580
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005582{
5583 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005584 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005585 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005586 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005587 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005588}
5589
5590void AudioFlinger::DuplicatingThread::threadLoop_standby()
5591{
5592 // DuplicatingThread implements standby by stopping all tracks
5593 for (size_t i = 0; i < outputTracks.size(); i++) {
5594 outputTracks[i]->stop();
5595 }
5596}
5597
5598void AudioFlinger::DuplicatingThread::saveOutputTracks()
5599{
5600 outputTracks = mOutputTracks;
5601}
5602
5603void AudioFlinger::DuplicatingThread::clearOutputTracks()
5604{
5605 outputTracks.clear();
5606}
5607
5608void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5609{
5610 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005611 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5612 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5613 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5614 const size_t frameCount =
5615 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5616 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5617 // from different OutputTracks and their associated MixerThreads (e.g. one may
5618 // nearly empty and the other may be dropping data).
5619
5620 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005621 this,
5622 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005623 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005624 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005625 frameCount,
5626 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005627 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5628 if (status != NO_ERROR) {
5629 ALOGE("addOutputTrack() initCheck failed %d", status);
5630 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005631 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005632 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5633 mOutputTracks.add(outputTrack);
5634 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5635 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005636}
5637
5638void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5639{
5640 Mutex::Autolock _l(mLock);
5641 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5642 if (mOutputTracks[i]->thread() == thread) {
5643 mOutputTracks[i]->destroy();
5644 mOutputTracks.removeAt(i);
5645 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005646 if (thread->getOutput() == mOutput) {
5647 mOutput = NULL;
5648 }
Eric Laurent81784c32012-11-19 14:55:58 -08005649 return;
5650 }
5651 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005652 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005653}
5654
5655// caller must hold mLock
5656void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5657{
5658 mWaitTimeMs = UINT_MAX;
5659 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5660 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5661 if (strong != 0) {
5662 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5663 if (waitTimeMs < mWaitTimeMs) {
5664 mWaitTimeMs = waitTimeMs;
5665 }
5666 }
5667 }
5668}
5669
5670
5671bool AudioFlinger::DuplicatingThread::outputsReady(
5672 const SortedVector< sp<OutputTrack> > &outputTracks)
5673{
5674 for (size_t i = 0; i < outputTracks.size(); i++) {
5675 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5676 if (thread == 0) {
5677 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5678 outputTracks[i].get());
5679 return false;
5680 }
5681 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5682 // see note at standby() declaration
5683 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5684 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5685 thread.get());
5686 return false;
5687 }
5688 }
5689 return true;
5690}
5691
5692uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5693{
5694 return (mWaitTimeMs * 1000) / 2;
5695}
5696
5697void AudioFlinger::DuplicatingThread::cacheParameters_l()
5698{
5699 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5700 updateWaitTime_l();
5701
5702 MixerThread::cacheParameters_l();
5703}
5704
5705// ----------------------------------------------------------------------------
5706// Record
5707// ----------------------------------------------------------------------------
5708
5709AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5710 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005711 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005712 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005713 audio_devices_t inDevice,
5714 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005715#ifdef TEE_SINK
5716 , const sp<NBAIO_Sink>& teeSink
5717#endif
5718 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005719 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2f366df2016-10-31 14:01:16 -07005720 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005721 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005722 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005723#ifdef TEE_SINK
5724 , mTeeSink(teeSink)
5725#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005726 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5727 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005728 // mFastCapture below
5729 , mFastCaptureFutex(0)
5730 // mInputSource
5731 // mPipeSink
5732 // mPipeSource
5733 , mPipeFramesP2(0)
5734 // mPipeMemory
5735 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005736 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005737{
Glenn Kastend7dca052015-03-05 16:05:54 -08005738 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5739 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005740
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005741 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005742
5743 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005744 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005745 size_t numCounterOffers = 0;
5746 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005747#if !LOG_NDEBUG
5748 ssize_t index =
5749#else
5750 (void)
5751#endif
5752 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005753 ALOG_ASSERT(index == 0);
5754
5755 // initialize fast capture depending on configuration
5756 bool initFastCapture;
5757 switch (kUseFastCapture) {
5758 case FastCapture_Never:
5759 initFastCapture = false;
5760 break;
5761 case FastCapture_Always:
5762 initFastCapture = true;
5763 break;
5764 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005765 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005766 break;
5767 // case FastCapture_Dynamic:
5768 }
5769
5770 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005771 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005772 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005773 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5774 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005775 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5776 void *pipeBuffer;
5777 const sp<MemoryDealer> roHeap(readOnlyHeap());
5778 sp<IMemory> pipeMemory;
5779 if ((roHeap == 0) ||
5780 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5781 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5782 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5783 goto failed;
5784 }
5785 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5786 memset(pipeBuffer, 0, pipeSize);
5787 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5788 const NBAIO_Format offers[1] = {format};
5789 size_t numCounterOffers = 0;
5790 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5791 ALOG_ASSERT(index == 0);
5792 mPipeSink = pipe;
5793 PipeReader *pipeReader = new PipeReader(*pipe);
5794 numCounterOffers = 0;
5795 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5796 ALOG_ASSERT(index == 0);
5797 mPipeSource = pipeReader;
5798 mPipeFramesP2 = pipeFramesP2;
5799 mPipeMemory = pipeMemory;
5800
5801 // create fast capture
5802 mFastCapture = new FastCapture();
5803 FastCaptureStateQueue *sq = mFastCapture->sq();
5804#ifdef STATE_QUEUE_DUMP
5805 // FIXME
5806#endif
5807 FastCaptureState *state = sq->begin();
5808 state->mCblk = NULL;
5809 state->mInputSource = mInputSource.get();
5810 state->mInputSourceGen++;
5811 state->mPipeSink = pipe;
5812 state->mPipeSinkGen++;
5813 state->mFrameCount = mFrameCount;
5814 state->mCommand = FastCaptureState::COLD_IDLE;
5815 // already done in constructor initialization list
5816 //mFastCaptureFutex = 0;
5817 state->mColdFutexAddr = &mFastCaptureFutex;
5818 state->mColdGen++;
5819 state->mDumpState = &mFastCaptureDumpState;
5820#ifdef TEE_SINK
5821 // FIXME
5822#endif
5823 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5824 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5825 sq->end();
5826 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5827
5828 // start the fast capture
5829 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5830 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005831 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005832#ifdef AUDIO_WATCHDOG
5833 // FIXME
5834#endif
5835
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005836 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005837 }
5838failed: ;
5839
5840 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005841}
5842
Eric Laurent81784c32012-11-19 14:55:58 -08005843AudioFlinger::RecordThread::~RecordThread()
5844{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005845 if (mFastCapture != 0) {
5846 FastCaptureStateQueue *sq = mFastCapture->sq();
5847 FastCaptureState *state = sq->begin();
5848 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5849 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5850 if (old == -1) {
5851 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5852 }
5853 }
5854 state->mCommand = FastCaptureState::EXIT;
5855 sq->end();
5856 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5857 mFastCapture->join();
5858 mFastCapture.clear();
5859 }
5860 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005861 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005862 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005863}
5864
5865void AudioFlinger::RecordThread::onFirstRef()
5866{
Glenn Kastend7dca052015-03-05 16:05:54 -08005867 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005868}
5869
Eric Laurent81784c32012-11-19 14:55:58 -08005870bool AudioFlinger::RecordThread::threadLoop()
5871{
Eric Laurent81784c32012-11-19 14:55:58 -08005872 nsecs_t lastWarning = 0;
5873
5874 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005875
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005876reacquire_wakelock:
5877 sp<RecordTrack> activeTrack;
5878 {
5879 Mutex::Autolock _l(mLock);
Andy Hung2f366df2016-10-31 14:01:16 -07005880 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005881 }
5882
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005883 // used to request a deferred sleep, to be executed later while mutex is unlocked
5884 uint32_t sleepUs = 0;
5885
5886 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005887 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005888 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005889
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005890 // activeTracks accumulates a copy of a subset of mActiveTracks
5891 Vector< sp<RecordTrack> > activeTracks;
5892
Glenn Kasten735f45f2014-08-18 15:51:59 -07005893 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005894 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005895
Glenn Kasten735f45f2014-08-18 15:51:59 -07005896 // reference to a fast track which is about to be removed
5897 sp<RecordTrack> fastTrackToRemove;
5898
Eric Laurent81784c32012-11-19 14:55:58 -08005899 { // scope for mLock
5900 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005901
Eric Laurent021cf962014-05-13 10:18:14 -07005902 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005903
Eric Laurent000a4192014-01-29 15:17:32 -08005904 // check exitPending here because checkForNewParameters_l() and
5905 // checkForNewParameters_l() can temporarily release mLock
5906 if (exitPending()) {
5907 break;
5908 }
5909
Eric Laurent5c25d562016-07-13 17:17:45 -07005910 // sleep with mutex unlocked
5911 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07005912 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07005913 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
5914 ATRACE_END();
5915 sleepUs = 0;
5916 continue;
5917 }
5918
Glenn Kasten2b806402013-11-20 16:37:38 -08005919 // if no active track(s), then standby and release wakelock
5920 size_t size = mActiveTracks.size();
5921 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005922 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005923 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005924 releaseWakeLock_l();
5925 ALOGV("RecordThread: loop stopping");
5926 // go to sleep
5927 mWaitWorkCV.wait(mLock);
5928 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005929 goto reacquire_wakelock;
5930 }
5931
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005932 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07005933 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005934 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005935
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005936 activeTrack = mActiveTracks[i];
5937 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005938 if (activeTrack->isFastTrack()) {
5939 ALOG_ASSERT(fastTrackToRemove == 0);
5940 fastTrackToRemove = activeTrack;
5941 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005942 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005943 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005944 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005945 continue;
5946 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005947
5948 TrackBase::track_state activeTrackState = activeTrack->mState;
5949 switch (activeTrackState) {
5950
5951 case TrackBase::PAUSING:
5952 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005953 doBroadcast = true;
5954 size--;
5955 continue;
5956
5957 case TrackBase::STARTING_1:
5958 sleepUs = 10000;
5959 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07005960 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005961 continue;
5962
5963 case TrackBase::STARTING_2:
5964 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005965 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005966 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07005967 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005968 break;
5969
5970 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07005971 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005972 break;
5973
5974 case TrackBase::IDLE:
5975 i++;
5976 continue;
5977
5978 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005979 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005980 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005981
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005982 activeTracks.add(activeTrack);
5983 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005984
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005985 if (activeTrack->isFastTrack()) {
5986 ALOG_ASSERT(!mFastTrackAvail);
5987 ALOG_ASSERT(fastTrack == 0);
5988 fastTrack = activeTrack;
5989 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005990 }
Eric Laurent5c25d562016-07-13 17:17:45 -07005991
Andy Hung2f366df2016-10-31 14:01:16 -07005992 mActiveTracks.updateWakeLockUids(this);
5993
Eric Laurent5c25d562016-07-13 17:17:45 -07005994 if (allStopped) {
5995 standbyIfNotAlreadyInStandby();
5996 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005997 if (doBroadcast) {
5998 mStartStopCond.broadcast();
5999 }
6000
6001 // sleep if there are no active tracks to process
6002 if (activeTracks.size() == 0) {
6003 if (sleepUs == 0) {
6004 sleepUs = kRecordThreadSleepUs;
6005 }
6006 continue;
6007 }
6008 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006009
Eric Laurent81784c32012-11-19 14:55:58 -08006010 lockEffectChains_l(effectChains);
6011 }
6012
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006013 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006014
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006015 size_t size = effectChains.size();
6016 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006017 // thread mutex is not locked, but effect chain is locked
6018 effectChains[i]->process_l();
6019 }
6020
Glenn Kasten735f45f2014-08-18 15:51:59 -07006021 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006022 if (mFastCapture != 0) {
6023 FastCaptureStateQueue *sq = mFastCapture->sq();
6024 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006025 bool didModify = false;
6026 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006027 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6028 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6029 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6030 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6031 if (old == -1) {
6032 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6033 }
6034 }
6035 state->mCommand = FastCaptureState::READ_WRITE;
6036#if 0 // FIXME
6037 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006038 FastThreadDumpState::kSamplingNforLowRamDevice :
6039 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006040#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006041 didModify = true;
6042 }
6043 audio_track_cblk_t *cblkOld = state->mCblk;
6044 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6045 if (cblkNew != cblkOld) {
6046 state->mCblk = cblkNew;
6047 // block until acked if removing a fast track
6048 if (cblkOld != NULL) {
6049 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6050 }
6051 didModify = true;
6052 }
6053 sq->end(didModify);
6054 if (didModify) {
6055 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006056#if 0
6057 if (kUseFastCapture == FastCapture_Dynamic) {
6058 mNormalSource = mPipeSource;
6059 }
6060#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006061 }
6062 }
6063
Glenn Kasten735f45f2014-08-18 15:51:59 -07006064 // now run the fast track destructor with thread mutex unlocked
6065 fastTrackToRemove.clear();
6066
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006067 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6068 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6069 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6070 // If destination is non-contiguous, first read past the nominal end of buffer, then
6071 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006072
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006073 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006074 ssize_t framesRead;
6075
6076 // If an NBAIO source is present, use it to read the normal capture's data
6077 if (mPipeSource != 0) {
6078 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006079 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006080 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006081 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006082 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6083 // buffer size or at least for 20ms.
6084 size_t sleepFrames = max(
6085 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6086 if (framesRead <= (ssize_t) sleepFrames) {
6087 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6088 }
6089 if (framesRead < 0) {
6090 status_t status = (status_t) framesRead;
6091 switch (status) {
6092 case OVERRUN:
6093 ALOGW("overrun on read from pipe");
6094 framesRead = 0;
6095 break;
6096 case NEGOTIATE:
6097 ALOGE("re-negotiation is needed");
6098 framesRead = -1; // Will cause an attempt to recover.
6099 break;
6100 default:
6101 ALOGE("unknown error %d on read from pipe", status);
6102 break;
6103 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006104 }
6105 // otherwise use the HAL / AudioStreamIn directly
6106 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006107 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006108 size_t bytesRead;
6109 status_t result = mInput->stream->read(
6110 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006111 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006112 if (result < 0) {
6113 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006114 } else {
6115 framesRead = bytesRead / mFrameSize;
6116 }
6117 }
6118
Andy Hung3f0c9022016-01-15 17:49:46 -08006119 // Update server timestamp with server stats
6120 // systemTime() is optional if the hardware supports timestamps.
6121 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6122 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6123
6124 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006125 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006126 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006127 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006128 if (ret == NO_ERROR) {
6129 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6130 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6131 // Note: In general record buffers should tend to be empty in
6132 // a properly running pipeline.
6133 //
6134 // Also, it is not advantageous to call get_presentation_position during the read
6135 // as the read obtains a lock, preventing the timestamp call from executing.
6136 }
6137 }
6138 // Use this to track timestamp information
6139 // ALOGD("%s", mTimestamp.toString().c_str());
6140
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006141 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006142 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006143 // Force input into standby so that it tries to recover at next read attempt
6144 inputStandBy();
6145 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006146 }
6147 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006148 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006149 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006150 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006151
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006152 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006153 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006154 }
6155 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006156 {
6157 size_t part1 = mRsmpInFramesP2 - rear;
6158 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006159 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006160 (framesRead - part1) * mFrameSize);
6161 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006162 }
6163 rear = mRsmpInRear += framesRead;
6164
6165 size = activeTracks.size();
6166 // loop over each active track
6167 for (size_t i = 0; i < size; i++) {
6168 activeTrack = activeTracks[i];
6169
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006170 // skip fast tracks, as those are handled directly by FastCapture
6171 if (activeTrack->isFastTrack()) {
6172 continue;
6173 }
6174
Andy Hung73c02e42015-03-29 01:13:58 -07006175 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006176 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6177
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006178 enum {
6179 OVERRUN_UNKNOWN,
6180 OVERRUN_TRUE,
6181 OVERRUN_FALSE
6182 } overrun = OVERRUN_UNKNOWN;
6183
6184 // loop over getNextBuffer to handle circular sink
6185 for (;;) {
6186
6187 activeTrack->mSink.frameCount = ~0;
6188 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6189 size_t framesOut = activeTrack->mSink.frameCount;
6190 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6191
Andy Hung73c02e42015-03-29 01:13:58 -07006192 // check available frames and handle overrun conditions
6193 // if the record track isn't draining fast enough.
6194 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006195 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006196 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6197 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006198 overrun = OVERRUN_TRUE;
6199 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006200 if (framesOut == 0 || framesIn == 0) {
6201 break;
6202 }
6203
Andy Hung6770c6f2015-04-07 13:43:36 -07006204 // Don't allow framesOut to be larger than what is possible with resampling
6205 // from framesIn.
6206 // This isn't strictly necessary but helps limit buffer resizing in
6207 // RecordBufferConverter. TODO: remove when no longer needed.
6208 framesOut = min(framesOut,
6209 destinationFramesPossible(
6210 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006211 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6212 framesOut = activeTrack->mRecordBufferConverter->convert(
6213 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006214
6215 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6216 overrun = OVERRUN_FALSE;
6217 }
6218
6219 if (activeTrack->mFramesToDrop == 0) {
6220 if (framesOut > 0) {
6221 activeTrack->mSink.frameCount = framesOut;
6222 activeTrack->releaseBuffer(&activeTrack->mSink);
6223 }
6224 } else {
6225 // FIXME could do a partial drop of framesOut
6226 if (activeTrack->mFramesToDrop > 0) {
6227 activeTrack->mFramesToDrop -= framesOut;
6228 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006229 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006230 }
6231 } else {
6232 activeTrack->mFramesToDrop += framesOut;
6233 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6234 activeTrack->mSyncStartEvent->isCancelled()) {
6235 ALOGW("Synced record %s, session %d, trigger session %d",
6236 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6237 activeTrack->sessionId(),
6238 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006239 activeTrack->mSyncStartEvent->triggerSession() :
6240 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006241 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006242 }
6243 }
6244 }
6245
6246 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006247 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006248 }
6249 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006250
6251 switch (overrun) {
6252 case OVERRUN_TRUE:
6253 // client isn't retrieving buffers fast enough
6254 if (!activeTrack->setOverflow()) {
6255 nsecs_t now = systemTime();
6256 // FIXME should lastWarning per track?
6257 if ((now - lastWarning) > kWarningThrottleNs) {
6258 ALOGW("RecordThread: buffer overflow");
6259 lastWarning = now;
6260 }
6261 }
6262 break;
6263 case OVERRUN_FALSE:
6264 activeTrack->clearOverflow();
6265 break;
6266 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006267 break;
6268 }
6269
Andy Hung3f0c9022016-01-15 17:49:46 -08006270 // update frame information and push timestamp out
6271 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006272 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006273 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6274 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006275 }
6276
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006277unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006278 // enable changes in effect chain
6279 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006280 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006281 }
6282
Glenn Kasten93e471f2013-08-19 08:40:07 -07006283 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006284
6285 {
6286 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006287 for (size_t i = 0; i < mTracks.size(); i++) {
6288 sp<RecordTrack> track = mTracks[i];
6289 track->invalidate();
6290 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006291 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006292 mStartStopCond.broadcast();
6293 }
6294
6295 releaseWakeLock();
6296
6297 ALOGV("RecordThread %p exiting", this);
6298 return false;
6299}
6300
Glenn Kasten93e471f2013-08-19 08:40:07 -07006301void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006302{
6303 if (!mStandby) {
6304 inputStandBy();
6305 mStandby = true;
6306 }
6307}
6308
6309void AudioFlinger::RecordThread::inputStandBy()
6310{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006311 // Idle the fast capture if it's currently running
6312 if (mFastCapture != 0) {
6313 FastCaptureStateQueue *sq = mFastCapture->sq();
6314 FastCaptureState *state = sq->begin();
6315 if (!(state->mCommand & FastCaptureState::IDLE)) {
6316 state->mCommand = FastCaptureState::COLD_IDLE;
6317 state->mColdFutexAddr = &mFastCaptureFutex;
6318 state->mColdGen++;
6319 mFastCaptureFutex = 0;
6320 sq->end();
6321 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6322 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6323#if 0
6324 if (kUseFastCapture == FastCapture_Dynamic) {
6325 // FIXME
6326 }
6327#endif
6328#ifdef AUDIO_WATCHDOG
6329 // FIXME
6330#endif
6331 } else {
6332 sq->end(false /*didModify*/);
6333 }
6334 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006335 status_t result = mInput->stream->standby();
6336 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006337
6338 // If going into standby, flush the pipe source.
6339 if (mPipeSource.get() != nullptr) {
6340 const ssize_t flushed = mPipeSource->flush();
6341 if (flushed > 0) {
6342 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6343 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6344 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6345 }
6346 }
Eric Laurent81784c32012-11-19 14:55:58 -08006347}
6348
Glenn Kasten05997e22014-03-13 15:08:33 -07006349// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006350sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006351 const sp<AudioFlinger::Client>& client,
6352 uint32_t sampleRate,
6353 audio_format_t format,
6354 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006355 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006356 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006357 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006358 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006359 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006360 pid_t tid,
6361 status_t *status)
6362{
Glenn Kasten74935e42013-12-19 08:56:45 -08006363 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006364 sp<RecordTrack> track;
6365 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006366 audio_input_flags_t inputFlags = mInput->flags;
6367
6368 // special case for FAST flag considered OK if fast capture is present
6369 if (hasFastCapture()) {
6370 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6371 }
6372
6373 // Check if requested flags are compatible with output stream flags
6374 if ((*flags & inputFlags) != *flags) {
6375 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6376 " input flags (%08x)",
6377 *flags, inputFlags);
6378 *flags = (audio_input_flags_t)(*flags & inputFlags);
6379 }
Eric Laurent81784c32012-11-19 14:55:58 -08006380
Glenn Kasten90e58b12013-07-31 16:16:02 -07006381 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006382 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006383 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006384 // we formerly checked for a callback handler (non-0 tid),
6385 // but that is no longer required for TRANSFER_OBTAIN mode
6386 //
Glenn Kasten74105912014-07-03 12:28:53 -07006387 // frame count is not specified, or is exactly the pipe depth
6388 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006389 // PCM data
6390 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006391 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006392 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006393 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006394 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006395 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006396 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006397 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006398 hasFastCapture() &&
6399 // there are sufficient fast track slots available
6400 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006401 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006402 // check compatibility with audio effects.
6403 Mutex::Autolock _l(mLock);
6404 // Do not accept FAST flag if the session has software effects
6405 sp<EffectChain> chain = getEffectChain_l(sessionId);
6406 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006407 audio_input_flags_t old = *flags;
6408 chain->checkInputFlagCompatibility(flags);
6409 if (old != *flags) {
6410 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6411 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006412 }
6413 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006414 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006415 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6416 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006417 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006418 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006419 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006420 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006421 frameCount, mFrameCount, mPipeFramesP2,
6422 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6423 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006424 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006425 }
6426 }
6427
6428 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006429 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006430 // fast track: frame count is exactly the pipe depth
6431 frameCount = mPipeFramesP2;
6432 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6433 *notificationFrames = mFrameCount;
6434 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006435 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6436 // or 20 ms if there is a fast capture
6437 // TODO This could be a roundupRatio inline, and const
6438 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6439 * sampleRate + mSampleRate - 1) / mSampleRate;
6440 // minimum number of notification periods is at least kMinNotifications,
6441 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6442 static const size_t kMinNotifications = 3;
6443 static const uint32_t kMinMs = 30;
6444 // TODO This could be a roundupRatio inline
6445 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6446 // TODO This could be a roundupRatio inline
6447 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6448 maxNotificationFrames;
6449 const size_t minFrameCount = maxNotificationFrames *
6450 max(kMinNotifications, minNotificationsByMs);
6451 frameCount = max(frameCount, minFrameCount);
6452 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6453 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006454 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006455 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006456 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006457
Glenn Kasten15e57982013-09-24 11:52:37 -07006458 lStatus = initCheck();
6459 if (lStatus != NO_ERROR) {
6460 ALOGE("createRecordTrack_l() audio driver not initialized");
6461 goto Exit;
6462 }
Eric Laurent81784c32012-11-19 14:55:58 -08006463
6464 { // scope for mLock
6465 Mutex::Autolock _l(mLock);
6466
6467 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006468 format, channelMask, frameCount, NULL, sessionId, uid,
6469 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006470
Glenn Kasten03003332013-08-06 15:40:54 -07006471 lStatus = track->initCheck();
6472 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006473 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006474 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006475 goto Exit;
6476 }
6477 mTracks.add(track);
6478
6479 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6480 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6481 mAudioFlinger->btNrecIsOff();
6482 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6483 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006484
Eric Laurent05067782016-06-01 18:27:28 -07006485 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006486 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6487 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6488 // so ask activity manager to do this on our behalf
6489 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6490 }
Eric Laurent81784c32012-11-19 14:55:58 -08006491 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006492
Eric Laurent81784c32012-11-19 14:55:58 -08006493 lStatus = NO_ERROR;
6494
6495Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006496 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006497 return track;
6498}
6499
6500status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6501 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006502 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006503{
6504 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6505 sp<ThreadBase> strongMe = this;
6506 status_t status = NO_ERROR;
6507
6508 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006509 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006510 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006511 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006512 triggerSession,
6513 recordTrack->sessionId(),
6514 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006515 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006516 // Sync event can be cancelled by the trigger session if the track is not in a
6517 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006518 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006519 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006520 } else {
6521 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006522 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006523 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006524 }
6525 }
6526
6527 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006528 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006529 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006530 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6531 if (recordTrack->mState == TrackBase::PAUSING) {
6532 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006533 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006534 } else {
6535 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006536 }
6537 return status;
6538 }
6539
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006540 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6541 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6542 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006543 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006544 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006545 status_t status = NO_ERROR;
6546 if (recordTrack->isExternalTrack()) {
6547 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006548 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006549 mLock.lock();
6550 // FIXME should verify that recordTrack is still in mActiveTracks
6551 if (status != NO_ERROR) {
6552 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006553 recordTrack->clearSyncStartEvent();
6554 ALOGV("RecordThread::start error %d", status);
6555 return status;
6556 }
Eric Laurent81784c32012-11-19 14:55:58 -08006557 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006558 // Catch up with current buffer indices if thread is already running.
6559 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6560 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6561 // see previously buffered data before it called start(), but with greater risk of overrun.
6562
Andy Hung73c02e42015-03-29 01:13:58 -07006563 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006564 // clear any converter state as new data will be discontinuous
6565 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006566 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006567 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006568 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006569 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006570 ALOGV("Record failed to start");
6571 status = BAD_VALUE;
6572 goto startError;
6573 }
Eric Laurent81784c32012-11-19 14:55:58 -08006574 return status;
6575 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006576
Eric Laurent81784c32012-11-19 14:55:58 -08006577startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006578 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006579 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006580 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006581 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006582 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006583 return status;
6584}
6585
Eric Laurent81784c32012-11-19 14:55:58 -08006586void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6587{
6588 sp<SyncEvent> strongEvent = event.promote();
6589
6590 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006591 sp<RefBase> ptr = strongEvent->cookie().promote();
6592 if (ptr != 0) {
6593 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6594 recordTrack->handleSyncStartEvent(strongEvent);
6595 }
Eric Laurent81784c32012-11-19 14:55:58 -08006596 }
6597}
6598
Glenn Kastena8356f62013-07-25 14:37:52 -07006599bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006600 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006601 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006602 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006603 return false;
6604 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006605 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006606 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006607 // signal thread to stop
6608 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006609 // do not wait for mStartStopCond if exiting
6610 if (exitPending()) {
6611 return true;
6612 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006613 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006614 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006615 // if we have been restarted, recordTrack is in mActiveTracks here
6616 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006617 ALOGV("Record stopped OK");
6618 return true;
6619 }
6620 return false;
6621}
6622
Glenn Kasten0f11b512014-01-31 16:18:54 -08006623bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006624{
6625 return false;
6626}
6627
Glenn Kasten0f11b512014-01-31 16:18:54 -08006628status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006629{
6630#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6631 if (!isValidSyncEvent(event)) {
6632 return BAD_VALUE;
6633 }
6634
Glenn Kastend848eb42016-03-08 13:42:11 -08006635 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006636 status_t ret = NAME_NOT_FOUND;
6637
6638 Mutex::Autolock _l(mLock);
6639
6640 for (size_t i = 0; i < mTracks.size(); i++) {
6641 sp<RecordTrack> track = mTracks[i];
6642 if (eventSession == track->sessionId()) {
6643 (void) track->setSyncEvent(event);
6644 ret = NO_ERROR;
6645 }
6646 }
6647 return ret;
6648#else
6649 return BAD_VALUE;
6650#endif
6651}
6652
6653// destroyTrack_l() must be called with ThreadBase::mLock held
6654void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6655{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006656 track->terminate();
6657 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006658 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006659 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006660 removeTrack_l(track);
6661 }
6662}
6663
6664void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6665{
6666 mTracks.remove(track);
6667 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006668 if (track->isFastTrack()) {
6669 ALOG_ASSERT(!mFastTrackAvail);
6670 mFastTrackAvail = true;
6671 }
Eric Laurent81784c32012-11-19 14:55:58 -08006672}
6673
6674void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6675{
6676 dumpInternals(fd, args);
6677 dumpTracks(fd, args);
6678 dumpEffectChains(fd, args);
6679}
6680
6681void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6682{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006683 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006684
Glenn Kasten44182c22015-03-05 17:12:23 -08006685 dumpBase(fd, args);
6686
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006687 AudioStreamIn *input = mInput;
6688 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6689 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6690 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006691 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006692 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006693 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006694 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006695 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006696
Glenn Kasten2f90c512015-12-02 11:40:09 -08006697 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6698 // while we are dumping it. It may be inconsistent, but it won't mutate!
6699 // This is a large object so we place it on the heap.
6700 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6701 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6702 copy->dump(fd);
6703 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006704}
6705
Glenn Kasten0f11b512014-01-31 16:18:54 -08006706void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006707{
6708 const size_t SIZE = 256;
6709 char buffer[SIZE];
6710 String8 result;
6711
Marco Nelissenb2208842014-02-07 14:00:50 -08006712 size_t numtracks = mTracks.size();
6713 size_t numactive = mActiveTracks.size();
6714 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006715 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006716 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006717 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006718 RecordTrack::appendDumpHeader(result);
6719 for (size_t i = 0; i < numtracks ; ++i) {
6720 sp<RecordTrack> track = mTracks[i];
6721 if (track != 0) {
6722 bool active = mActiveTracks.indexOf(track) >= 0;
6723 if (active) {
6724 numactiveseen++;
6725 }
6726 track->dump(buffer, SIZE, active);
6727 result.append(buffer);
6728 }
Eric Laurent81784c32012-11-19 14:55:58 -08006729 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006730 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006731 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006732 }
6733
Marco Nelissenb2208842014-02-07 14:00:50 -08006734 if (numactiveseen != numactive) {
6735 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6736 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006737 result.append(buffer);
6738 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006739 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006740 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006741 if (mTracks.indexOf(track) < 0) {
6742 track->dump(buffer, SIZE, true);
6743 result.append(buffer);
6744 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006745 }
Eric Laurent81784c32012-11-19 14:55:58 -08006746
6747 }
6748 write(fd, result.string(), result.size());
6749}
6750
Andy Hung73c02e42015-03-29 01:13:58 -07006751
6752void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6753{
6754 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6755 RecordThread *recordThread = (RecordThread *) threadBase.get();
6756 mRsmpInFront = recordThread->mRsmpInRear;
6757 mRsmpInUnrel = 0;
6758}
6759
6760void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6761 size_t *framesAvailable, bool *hasOverrun)
6762{
6763 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6764 RecordThread *recordThread = (RecordThread *) threadBase.get();
6765 const int32_t rear = recordThread->mRsmpInRear;
6766 const int32_t front = mRsmpInFront;
6767 const ssize_t filled = rear - front;
6768
6769 size_t framesIn;
6770 bool overrun = false;
6771 if (filled < 0) {
6772 // should not happen, but treat like a massive overrun and re-sync
6773 framesIn = 0;
6774 mRsmpInFront = rear;
6775 overrun = true;
6776 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6777 framesIn = (size_t) filled;
6778 } else {
6779 // client is not keeping up with server, but give it latest data
6780 framesIn = recordThread->mRsmpInFrames;
6781 mRsmpInFront = /* front = */ rear - framesIn;
6782 overrun = true;
6783 }
6784 if (framesAvailable != NULL) {
6785 *framesAvailable = framesIn;
6786 }
6787 if (hasOverrun != NULL) {
6788 *hasOverrun = overrun;
6789 }
6790}
6791
Eric Laurent81784c32012-11-19 14:55:58 -08006792// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006793status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006794 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006795{
Andy Hung73c02e42015-03-29 01:13:58 -07006796 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006797 if (threadBase == 0) {
6798 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006799 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006800 return NOT_ENOUGH_DATA;
6801 }
6802 RecordThread *recordThread = (RecordThread *) threadBase.get();
6803 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006804 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006805 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006806 // FIXME should not be P2 (don't want to increase latency)
6807 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006808 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006809 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006810 front &= recordThread->mRsmpInFramesP2 - 1;
6811 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006812 if (part1 > (size_t) filled) {
6813 part1 = filled;
6814 }
6815 size_t ask = buffer->frameCount;
6816 ALOG_ASSERT(ask > 0);
6817 if (part1 > ask) {
6818 part1 = ask;
6819 }
6820 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006821 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006822 buffer->raw = NULL;
6823 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006824 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006825 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006826 }
6827
Andy Hung57446612015-04-19 23:56:46 -07006828 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006829 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006830 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006831 return NO_ERROR;
6832}
6833
6834// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006835void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6836 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006837{
Glenn Kasten85948432013-08-19 12:09:05 -07006838 size_t stepCount = buffer->frameCount;
6839 if (stepCount == 0) {
6840 return;
6841 }
Andy Hung73c02e42015-03-29 01:13:58 -07006842 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6843 mRsmpInUnrel -= stepCount;
6844 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006845 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006846 buffer->frameCount = 0;
6847}
6848
Andy Hung97a893e2015-03-29 01:03:07 -07006849AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6850 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6851 uint32_t srcSampleRate,
6852 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6853 uint32_t dstSampleRate) :
6854 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6855 // mSrcFormat
6856 // mSrcSampleRate
6857 // mDstChannelMask
6858 // mDstFormat
6859 // mDstSampleRate
6860 // mSrcChannelCount
6861 // mDstChannelCount
6862 // mDstFrameSize
6863 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006864 mResampler(NULL),
6865 mIsLegacyDownmix(false),
6866 mIsLegacyUpmix(false),
6867 mRequiresFloat(false),
6868 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006869{
6870 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6871 dstChannelMask, dstFormat, dstSampleRate);
6872}
6873
6874AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6875 free(mBuf);
6876 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006877 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006878}
6879
6880size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6881 AudioBufferProvider *provider, size_t frames)
6882{
Andy Hungd330ee42015-04-20 13:23:41 -07006883 if (mInputConverterProvider != NULL) {
6884 mInputConverterProvider->setBufferProvider(provider);
6885 provider = mInputConverterProvider;
6886 }
6887
6888 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006889 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6890 mSrcSampleRate, mSrcFormat, mDstFormat);
6891
6892 AudioBufferProvider::Buffer buffer;
6893 for (size_t i = frames; i > 0; ) {
6894 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006895 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006896 if (status != OK || buffer.frameCount == 0) {
6897 frames -= i; // cannot fill request.
6898 break;
6899 }
Andy Hungd330ee42015-04-20 13:23:41 -07006900 // format convert to destination buffer
6901 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006902
6903 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6904 i -= buffer.frameCount;
6905 provider->releaseBuffer(&buffer);
6906 }
6907 } else {
6908 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6909 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6910
Andy Hungd330ee42015-04-20 13:23:41 -07006911 // reallocate buffer if needed
6912 if (mBufFrameSize != 0 && mBufFrames < frames) {
6913 free(mBuf);
6914 mBufFrames = frames;
6915 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6916 }
Andy Hung97a893e2015-03-29 01:03:07 -07006917 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006918 memset(mBuf, 0, frames * mBufFrameSize);
6919 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6920 // format convert to destination buffer
6921 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006922 }
6923 return frames;
6924}
6925
6926status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6927 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6928 uint32_t srcSampleRate,
6929 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6930 uint32_t dstSampleRate)
6931{
6932 // quick evaluation if there is any change.
6933 if (mSrcFormat == srcFormat
6934 && mSrcChannelMask == srcChannelMask
6935 && mSrcSampleRate == srcSampleRate
6936 && mDstFormat == dstFormat
6937 && mDstChannelMask == dstChannelMask
6938 && mDstSampleRate == dstSampleRate) {
6939 return NO_ERROR;
6940 }
6941
Andy Hungdb4c0312015-05-06 08:46:52 -07006942 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6943 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6944 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006945 const bool valid =
6946 audio_is_input_channel(srcChannelMask)
6947 && audio_is_input_channel(dstChannelMask)
6948 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6949 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6950 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6951 ; // no upsampling checks for now
6952 if (!valid) {
6953 return BAD_VALUE;
6954 }
6955
6956 mSrcFormat = srcFormat;
6957 mSrcChannelMask = srcChannelMask;
6958 mSrcSampleRate = srcSampleRate;
6959 mDstFormat = dstFormat;
6960 mDstChannelMask = dstChannelMask;
6961 mDstSampleRate = dstSampleRate;
6962
6963 // compute derived parameters
6964 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6965 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6966 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6967
Andy Hungd330ee42015-04-20 13:23:41 -07006968 // do we need to resample?
6969 delete mResampler;
6970 mResampler = NULL;
6971 if (mSrcSampleRate != mDstSampleRate) {
6972 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6973 mSrcChannelCount, mDstSampleRate);
6974 mResampler->setSampleRate(mSrcSampleRate);
6975 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6976 }
6977
6978 // are we running legacy channel conversion modes?
6979 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6980 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6981 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6982 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6983 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6984 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6985
6986 // do we need to process in float?
6987 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6988
6989 // do we need a staging buffer to convert for destination (we can still optimize this)?
6990 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6991 if (mResampler != NULL) {
6992 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6993 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006994 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006995 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6996 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006997 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6998 } else {
6999 mBufFrameSize = 0;
7000 }
7001 mBufFrames = 0; // force the buffer to be resized.
7002
Andy Hungd330ee42015-04-20 13:23:41 -07007003 // do we need an input converter buffer provider to give us float?
7004 delete mInputConverterProvider;
7005 mInputConverterProvider = NULL;
7006 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7007 mInputConverterProvider = new ReformatBufferProvider(
7008 audio_channel_count_from_in_mask(mSrcChannelMask),
7009 mSrcFormat,
7010 AUDIO_FORMAT_PCM_FLOAT,
7011 256 /* provider buffer frame count */);
7012 }
7013
7014 // do we need a remixer to do channel mask conversion
7015 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7016 (void) memcpy_by_index_array_initialization_from_channel_mask(
7017 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007018 }
7019 return NO_ERROR;
7020}
7021
Andy Hungd330ee42015-04-20 13:23:41 -07007022void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7023 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007024{
Andy Hungd330ee42015-04-20 13:23:41 -07007025 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007026 if (mBufFrameSize != 0 && mBufFrames < frames) {
7027 free(mBuf);
7028 mBufFrames = frames;
7029 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7030 }
Andy Hungd330ee42015-04-20 13:23:41 -07007031 // do we need to do legacy upmix and downmix?
7032 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007033 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007034 if (mIsLegacyUpmix) {
7035 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7036 (const float *)src, frames);
7037 } else /*mIsLegacyDownmix */ {
7038 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7039 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007040 }
Andy Hungd330ee42015-04-20 13:23:41 -07007041 if (mBuf != NULL) {
7042 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7043 frames * mDstChannelCount);
7044 }
7045 return;
7046 }
7047 // do we need to do channel mask conversion?
7048 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007049 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007050 memcpy_by_index_array(dstBuf, mDstChannelCount,
7051 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7052 if (dstBuf == dst) {
7053 return; // format is the same
7054 }
7055 }
7056 // convert to destination buffer
7057 const void *convertBuf = mBuf != NULL ? mBuf : src;
7058 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7059 frames * mDstChannelCount);
7060}
7061
7062void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7063 void *dst, /*not-a-const*/ void *src, size_t frames)
7064{
7065 // src buffer format is ALWAYS float when entering this routine
7066 if (mIsLegacyUpmix) {
7067 ; // mono to stereo already handled by resampler
7068 } else if (mIsLegacyDownmix
7069 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7070 // the resampler outputs stereo for mono input channel (a feature?)
7071 // must convert to mono
7072 downmix_to_mono_float_from_stereo_float((float *)src,
7073 (const float *)src, frames);
7074 } else if (mSrcChannelMask != mDstChannelMask) {
7075 // convert to mono channel again for channel mask conversion (could be skipped
7076 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007077 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007078 downmix_to_mono_float_from_stereo_float((float *)src,
7079 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007080 }
Andy Hungd330ee42015-04-20 13:23:41 -07007081 // convert to destination format (in place, OK as float is larger than other types)
7082 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7083 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7084 frames * mSrcChannelCount);
7085 }
7086 // channel convert and save to dst
7087 memcpy_by_index_array(dst, mDstChannelCount,
7088 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7089 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007090 }
Andy Hungd330ee42015-04-20 13:23:41 -07007091 // convert to destination format and save to dst
7092 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7093 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007094}
7095
Eric Laurent10351942014-05-08 18:49:52 -07007096bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7097 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007098{
7099 bool reconfig = false;
7100
Eric Laurent10351942014-05-08 18:49:52 -07007101 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007102
Eric Laurent10351942014-05-08 18:49:52 -07007103 audio_format_t reqFormat = mFormat;
7104 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007105 // 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 -07007106 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7107
7108 AudioParameter param = AudioParameter(keyValuePair);
7109 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007110
7111 // scope for AutoPark extends to end of method
7112 AutoPark<FastCapture> park(mFastCapture);
7113
Eric Laurent10351942014-05-08 18:49:52 -07007114 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7115 // channel count change can be requested. Do we mandate the first client defines the
7116 // HAL sampling rate and channel count or do we allow changes on the fly?
7117 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7118 samplingRate = value;
7119 reconfig = true;
7120 }
7121 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007122 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007123 status = BAD_VALUE;
7124 } else {
7125 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007126 reconfig = true;
7127 }
Eric Laurent10351942014-05-08 18:49:52 -07007128 }
7129 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7130 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007131 if (!audio_is_input_channel(mask) ||
7132 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007133 status = BAD_VALUE;
7134 } else {
7135 channelMask = mask;
7136 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007137 }
Eric Laurent10351942014-05-08 18:49:52 -07007138 }
7139 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7140 // do not accept frame count changes if tracks are open as the track buffer
7141 // size depends on frame count and correct behavior would not be guaranteed
7142 // if frame count is changed after track creation
7143 if (mActiveTracks.size() > 0) {
7144 status = INVALID_OPERATION;
7145 } else {
7146 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007147 }
Eric Laurent10351942014-05-08 18:49:52 -07007148 }
7149 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7150 // forward device change to effects that have requested to be
7151 // aware of attached audio device.
7152 for (size_t i = 0; i < mEffectChains.size(); i++) {
7153 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007154 }
Eric Laurent81784c32012-11-19 14:55:58 -08007155
Eric Laurent10351942014-05-08 18:49:52 -07007156 // store input device and output device but do not forward output device to audio HAL.
7157 // Note that status is ignored by the caller for output device
7158 // (see AudioFlinger::setParameters()
7159 if (audio_is_output_devices(value)) {
7160 mOutDevice = value;
7161 status = BAD_VALUE;
7162 } else {
7163 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007164 if (value != AUDIO_DEVICE_NONE) {
7165 mPrevInDevice = value;
7166 }
Eric Laurent10351942014-05-08 18:49:52 -07007167 // disable AEC and NS if the device is a BT SCO headset supporting those
7168 // pre processings
7169 if (mTracks.size() > 0) {
7170 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7171 mAudioFlinger->btNrecIsOff();
7172 for (size_t i = 0; i < mTracks.size(); i++) {
7173 sp<RecordTrack> track = mTracks[i];
7174 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7175 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007176 }
7177 }
7178 }
Eric Laurent10351942014-05-08 18:49:52 -07007179 }
7180 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7181 mAudioSource != (audio_source_t)value) {
7182 // forward device change to effects that have requested to be
7183 // aware of attached audio device.
7184 for (size_t i = 0; i < mEffectChains.size(); i++) {
7185 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007186 }
Eric Laurent10351942014-05-08 18:49:52 -07007187 mAudioSource = (audio_source_t)value;
7188 }
Glenn Kastene198c362013-08-13 09:13:36 -07007189
Eric Laurent10351942014-05-08 18:49:52 -07007190 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007191 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007192 if (status == INVALID_OPERATION) {
7193 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007194 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007195 }
7196 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007197 if (status == BAD_VALUE) {
7198 uint32_t sRate;
7199 audio_channel_mask_t channelMask;
7200 audio_format_t format;
7201 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7202 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7203 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7204 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7205 status = NO_ERROR;
7206 }
Eric Laurent81784c32012-11-19 14:55:58 -08007207 }
Eric Laurent10351942014-05-08 18:49:52 -07007208 if (status == NO_ERROR) {
7209 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007210 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007211 }
7212 }
Eric Laurent81784c32012-11-19 14:55:58 -08007213 }
Eric Laurent10351942014-05-08 18:49:52 -07007214
Eric Laurent81784c32012-11-19 14:55:58 -08007215 return reconfig;
7216}
7217
7218String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7219{
Eric Laurent81784c32012-11-19 14:55:58 -08007220 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007221 if (initCheck() == NO_ERROR) {
7222 String8 out_s8;
7223 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7224 return out_s8;
7225 }
Eric Laurent81784c32012-11-19 14:55:58 -08007226 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007227 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007228}
7229
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007230void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007231 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7232
7233 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007234
7235 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007236 case AUDIO_INPUT_OPENED:
7237 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007238 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007239 desc->mChannelMask = mChannelMask;
7240 desc->mSamplingRate = mSampleRate;
7241 desc->mFormat = mFormat;
7242 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007243 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007244 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007245 break;
7246
Eric Laurent73e26b62015-04-27 16:55:58 -07007247 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007248 default:
7249 break;
7250 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007251 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007252}
7253
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007254void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007255{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007256 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7257 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007258 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007259 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007260 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007261 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7262 result = mInput->stream->getFrameSize(&mFrameSize);
7263 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7264 result = mInput->stream->getBufferSize(&mBufferSize);
7265 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007266 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007267 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007268 // 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 -07007269 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007270 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007271 // A larger value should allow more old data to be read after a track calls start(),
7272 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007273 //
7274 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007275 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007276 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007277 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007278 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007279
7280 // TODO optimize audio capture buffer sizes ...
7281 // Here we calculate the size of the sliding buffer used as a source
7282 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7283 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7284 // be better to have it derived from the pipe depth in the long term.
7285 // The current value is higher than necessary. However it should not add to latency.
7286
Glenn Kasten85948432013-08-19 12:09:05 -07007287 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007288 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7289 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7290 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007291
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007292 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7293 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007294}
7295
Glenn Kasten5f972c02014-01-13 09:59:31 -08007296uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007297{
7298 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007299 uint32_t result;
7300 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7301 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007302 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007303 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007304}
7305
Eric Laurent4c415062016-06-17 16:14:16 -07007306// hasAudioSession_l() must be called with ThreadBase::mLock held
7307uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007308{
Eric Laurent81784c32012-11-19 14:55:58 -08007309 uint32_t result = 0;
7310 if (getEffectChain_l(sessionId) != 0) {
7311 result = EFFECT_SESSION;
7312 }
7313
7314 for (size_t i = 0; i < mTracks.size(); ++i) {
7315 if (sessionId == mTracks[i]->sessionId()) {
7316 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007317 if (mTracks[i]->isFastTrack()) {
7318 result |= FAST_SESSION;
7319 }
Eric Laurent81784c32012-11-19 14:55:58 -08007320 break;
7321 }
7322 }
7323
7324 return result;
7325}
7326
Glenn Kastend848eb42016-03-08 13:42:11 -08007327KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007328{
Glenn Kastend848eb42016-03-08 13:42:11 -08007329 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007330 Mutex::Autolock _l(mLock);
7331 for (size_t j = 0; j < mTracks.size(); ++j) {
7332 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007333 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007334 if (ids.indexOfKey(sessionId) < 0) {
7335 ids.add(sessionId, true);
7336 }
7337 }
7338 return ids;
7339}
7340
7341AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7342{
7343 Mutex::Autolock _l(mLock);
7344 AudioStreamIn *input = mInput;
7345 mInput = NULL;
7346 return input;
7347}
7348
7349// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007350sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007351{
7352 if (mInput == NULL) {
7353 return NULL;
7354 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007355 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007356}
7357
7358status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7359{
7360 // only one chain per input thread
7361 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007362 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007363 return INVALID_OPERATION;
7364 }
7365 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007366 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007367 chain->setInBuffer(NULL);
7368 chain->setOutBuffer(NULL);
7369
7370 checkSuspendOnAddEffectChain_l(chain);
7371
Eric Laurent1b928682014-10-02 19:41:47 -07007372 // make sure enabled pre processing effects state is communicated to the HAL as we
7373 // just moved them to a new input stream.
7374 chain->syncHalEffectsState();
7375
Eric Laurent81784c32012-11-19 14:55:58 -08007376 mEffectChains.add(chain);
7377
7378 return NO_ERROR;
7379}
7380
7381size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7382{
7383 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7384 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007385 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007386 chain.get(), mEffectChains.size(), this);
7387 if (mEffectChains.size() == 1) {
7388 mEffectChains.removeAt(0);
7389 }
7390 return 0;
7391}
7392
Eric Laurent1c333e22014-05-20 10:48:17 -07007393status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7394 audio_patch_handle_t *handle)
7395{
7396 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007397
7398 // store new device and send to effects
7399 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007400 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007401 for (size_t i = 0; i < mEffectChains.size(); i++) {
7402 mEffectChains[i]->setDevice_l(mInDevice);
7403 }
7404
7405 // disable AEC and NS if the device is a BT SCO headset supporting those
7406 // pre processings
7407 if (mTracks.size() > 0) {
7408 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7409 mAudioFlinger->btNrecIsOff();
7410 for (size_t i = 0; i < mTracks.size(); i++) {
7411 sp<RecordTrack> track = mTracks[i];
7412 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7413 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7414 }
7415 }
7416
7417 // store new source and send to effects
7418 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7419 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007420 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007421 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007422 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007423 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007424
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007425 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007426 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7427 status = hwDevice->createAudioPatch(patch->num_sources,
7428 patch->sources,
7429 patch->num_sinks,
7430 patch->sinks,
7431 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007432 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007433 char *address;
7434 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7435 address = audio_device_address_to_parameter(
7436 patch->sources[0].ext.device.type,
7437 patch->sources[0].ext.device.address);
7438 } else {
7439 address = (char *)calloc(1, 1);
7440 }
7441 AudioParameter param = AudioParameter(String8(address));
7442 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007443 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007444 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007445 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007446 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007447 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007448 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007449 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007450
Eric Laurente8726fe2015-06-26 09:39:24 -07007451 if (mInDevice != mPrevInDevice) {
7452 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7453 mPrevInDevice = mInDevice;
7454 }
Eric Laurent296fb132015-05-01 11:38:42 -07007455
Eric Laurent1c333e22014-05-20 10:48:17 -07007456 return status;
7457}
7458
7459status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7460{
7461 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007462
7463 mInDevice = AUDIO_DEVICE_NONE;
7464
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007465 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007466 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7467 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007468 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007469 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007470 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007471 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007472 }
7473 return status;
7474}
7475
Eric Laurent83b88082014-06-20 18:31:16 -07007476void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7477{
7478 Mutex::Autolock _l(mLock);
7479 mTracks.add(record);
7480}
7481
7482void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7483{
7484 Mutex::Autolock _l(mLock);
7485 destroyTrack_l(record);
7486}
7487
7488void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7489{
7490 ThreadBase::getAudioPortConfig(config);
7491 config->role = AUDIO_PORT_ROLE_SINK;
7492 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7493 config->ext.mix.usecase.source = mAudioSource;
7494}
Eric Laurent1c333e22014-05-20 10:48:17 -07007495
Glenn Kasten63238ef2015-03-02 15:50:29 -08007496} // namespace android