blob: 5376540d04b5bee5e147dd049aa966491cb1f128 [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)),
Wei Jia3f273d12015-11-24 09:06:49 -0800511 mSystemReady(systemReady),
512 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800513{
Eric Laurent296fb132015-05-01 11:38:42 -0700514 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
517AudioFlinger::ThreadBase::~ThreadBase()
518{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 mConfigEvents.clear();
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522 // do not lock the mutex in destructor
523 releaseWakeLock_l();
524 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800525 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800526 binder->unlinkToDeath(mDeathRecipient);
527 }
528}
529
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700530status_t AudioFlinger::ThreadBase::readyToRun()
531{
532 status_t status = initCheck();
533 if (status == NO_ERROR) {
534 ALOGI("AudioFlinger's thread %p ready to run", this);
535 } else {
536 ALOGE("No working audio driver found.");
537 }
538 return status;
539}
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541void AudioFlinger::ThreadBase::exit()
542{
543 ALOGV("ThreadBase::exit");
544 // do any cleanup required for exit to succeed
545 preExit();
546 {
547 // This lock prevents the following race in thread (uniprocessor for illustration):
548 // if (!exitPending()) {
549 // // context switch from here to exit()
550 // // exit() calls requestExit(), what exitPending() observes
551 // // exit() calls signal(), which is dropped since no waiters
552 // // context switch back from exit() to here
553 // mWaitWorkCV.wait(...);
554 // // now thread is hung
555 // }
556 AutoMutex lock(mLock);
557 requestExit();
558 mWaitWorkCV.broadcast();
559 }
560 // When Thread::requestExitAndWait is made virtual and this method is renamed to
561 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
562 requestExitAndWait();
563}
564
565status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
566{
Eric Laurent81784c32012-11-19 14:55:58 -0800567 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
568 Mutex::Autolock _l(mLock);
569
Eric Laurent10351942014-05-08 18:49:52 -0700570 return sendSetParameterConfigEvent_l(keyValuePairs);
571}
572
573// sendConfigEvent_l() must be called with ThreadBase::mLock held
574// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
575status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
576{
577 status_t status = NO_ERROR;
578
Eric Laurent72e3f392015-05-20 14:43:50 -0700579 if (event->mRequiresSystemReady && !mSystemReady) {
580 event->mWaitStatus = false;
581 mPendingConfigEvents.add(event);
582 return status;
583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700585 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800586 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700587 mLock.unlock();
588 {
589 Mutex::Autolock _l(event->mLock);
590 while (event->mWaitStatus) {
591 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
592 event->mStatus = TIMED_OUT;
593 event->mWaitStatus = false;
594 }
595 }
596 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800597 }
Eric Laurent10351942014-05-08 18:49:52 -0700598 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800599 return status;
600}
601
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700602void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
604 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
608// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700612 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800613}
614
Eric Laurent72e3f392015-05-20 14:43:50 -0700615void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
616{
617 Mutex::Autolock _l(mLock);
618 sendPrioConfigEvent_l(pid, tid, prio);
619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
622void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
623{
Eric Laurent10351942014-05-08 18:49:52 -0700624 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
625 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800626}
627
Eric Laurent10351942014-05-08 18:49:52 -0700628// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
629status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800630{
Andy Hung2ddee192015-12-18 17:34:44 -0800631 sp<ConfigEvent> configEvent;
632 AudioParameter param(keyValuePair);
633 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700634 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800635 setMasterMono_l(value != 0);
636 if (param.size() == 1) {
637 return NO_ERROR; // should be a solo parameter - we don't pass down
638 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700639 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800640 configEvent = new SetParameterConfigEvent(param.toString());
641 } else {
642 configEvent = new SetParameterConfigEvent(keyValuePair);
643 }
Eric Laurent10351942014-05-08 18:49:52 -0700644 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700645}
646
Eric Laurent1c333e22014-05-20 10:48:17 -0700647status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
648 const struct audio_patch *patch,
649 audio_patch_handle_t *handle)
650{
651 Mutex::Autolock _l(mLock);
652 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
653 status_t status = sendConfigEvent_l(configEvent);
654 if (status == NO_ERROR) {
655 CreateAudioPatchConfigEventData *data =
656 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
657 *handle = data->mHandle;
658 }
659 return status;
660}
661
662status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
663 const audio_patch_handle_t handle)
664{
665 Mutex::Autolock _l(mLock);
666 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
667 return sendConfigEvent_l(configEvent);
668}
669
670
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700671// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700672void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700673{
Eric Laurent10351942014-05-08 18:49:52 -0700674 bool configChanged = false;
675
Eric Laurent81784c32012-11-19 14:55:58 -0800676 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700677 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700678 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800679 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700680 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700681 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700682 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
683 // FIXME Need to understand why this has to be done asynchronously
684 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700685 true /*asynchronous*/);
686 if (err != 0) {
687 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700688 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700689 }
690 } break;
691 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700692 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700693 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700694 } break;
695 case CFG_EVENT_SET_PARAMETER: {
696 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
697 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
698 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700699 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700700 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700701 case CFG_EVENT_CREATE_AUDIO_PATCH: {
702 CreateAudioPatchConfigEventData *data =
703 (CreateAudioPatchConfigEventData *)event->mData.get();
704 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
705 } break;
706 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
707 ReleaseAudioPatchConfigEventData *data =
708 (ReleaseAudioPatchConfigEventData *)event->mData.get();
709 event->mStatus = releaseAudioPatch_l(data->mHandle);
710 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700711 default:
Eric Laurent10351942014-05-08 18:49:52 -0700712 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700713 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800714 }
Eric Laurent10351942014-05-08 18:49:52 -0700715 {
716 Mutex::Autolock _l(event->mLock);
717 if (event->mWaitStatus) {
718 event->mWaitStatus = false;
719 event->mCond.signal();
720 }
721 }
722 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
723 }
724
725 if (configChanged) {
726 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800727 }
Eric Laurent81784c32012-11-19 14:55:58 -0800728}
729
Marco Nelissenb2208842014-02-07 14:00:50 -0800730String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
731 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700732 const audio_channel_representation_t representation =
733 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700734
735 switch (representation) {
736 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
737 if (output) {
738 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
739 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
740 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
741 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
742 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
743 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
744 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
745 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
746 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
747 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
748 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
749 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
750 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
751 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
753 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
754 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
755 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
756 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
757 } else {
758 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
759 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
760 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
761 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
762 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
763 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
764 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
765 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
766 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
767 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
768 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
769 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
770 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
771 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
772 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
773 }
774 const int len = s.length();
775 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700776 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700777 s.unlockBuffer(len - 2); // remove trailing ", "
778 }
779 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800780 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700781 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
782 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
783 return s;
784 default:
785 s.appendFormat("unknown mask, representation:%d bits:%#x",
786 representation, audio_channel_mask_get_bits(mask));
787 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800788 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800789}
790
Glenn Kasten0f11b512014-01-31 16:18:54 -0800791void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800792{
793 const size_t SIZE = 256;
794 char buffer[SIZE];
795 String8 result;
796
797 bool locked = AudioFlinger::dumpTryLock(mLock);
798 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700799 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800800 }
801
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800802 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700803 dprintf(fd, " I/O handle: %d\n", mId);
804 dprintf(fd, " TID: %d\n", getTid());
805 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700806 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700807 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700808 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700809 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700810 dprintf(fd, " Channel count: %u\n", mChannelCount);
811 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800812 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700813 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700814 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700815 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800816 size_t numConfig = mConfigEvents.size();
817 if (numConfig) {
818 for (size_t i = 0; i < numConfig; i++) {
819 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700820 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800821 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700822 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800823 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700824 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800825 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700826 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
827 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800828 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800829
830 if (locked) {
831 mLock.unlock();
832 }
833}
834
835void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
836{
837 const size_t SIZE = 256;
838 char buffer[SIZE];
839 String8 result;
840
Marco Nelissenb2208842014-02-07 14:00:50 -0800841 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000842 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800843 write(fd, buffer, strlen(buffer));
844
Marco Nelissenb2208842014-02-07 14:00:50 -0800845 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800846 sp<EffectChain> chain = mEffectChains[i];
847 if (chain != 0) {
848 chain->dump(fd, args);
849 }
850 }
851}
852
Marco Nelissene14a5d62013-10-03 08:51:24 -0700853void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800854{
855 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700856 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800857}
858
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100859String16 AudioFlinger::ThreadBase::getWakeLockTag()
860{
861 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800862 case MIXER:
863 return String16("AudioMix");
864 case DIRECT:
865 return String16("AudioDirectOut");
866 case DUPLICATING:
867 return String16("AudioDup");
868 case RECORD:
869 return String16("AudioIn");
870 case OFFLOAD:
871 return String16("AudioOffload");
872 default:
873 ALOG_ASSERT(false);
874 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100875 }
876}
877
Marco Nelissene14a5d62013-10-03 08:51:24 -0700878void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800879{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800880 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800881 if (mPowerManager != 0) {
882 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700883 status_t status;
884 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700885 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700886 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100887 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700888 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700889 uid,
890 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700891 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700892 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700893 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100894 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700895 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700896 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700897 }
Eric Laurent81784c32012-11-19 14:55:58 -0800898 if (status == NO_ERROR) {
899 mWakeLockToken = binder;
900 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800901 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800902 }
Wei Jia3f273d12015-11-24 09:06:49 -0800903
904 if (!mNotifiedBatteryStart) {
Wei Jiaf2ae3e12016-10-27 17:10:59 -0700905 // TODO: call this function for each track when it becomes active.
906 BatteryNotifier::getInstance().noteStartAudio(AID_AUDIOSERVER);
Wei Jia3f273d12015-11-24 09:06:49 -0800907 mNotifiedBatteryStart = true;
908 }
Andy Hung3f0c9022016-01-15 17:49:46 -0800909 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800910 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
911 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800912}
913
914void AudioFlinger::ThreadBase::releaseWakeLock()
915{
916 Mutex::Autolock _l(mLock);
917 releaseWakeLock_l();
918}
919
920void AudioFlinger::ThreadBase::releaseWakeLock_l()
921{
Andy Hung3f0c9022016-01-15 17:49:46 -0800922 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800923 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800924 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800925 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700926 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
927 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 }
929 mWakeLockToken.clear();
930 }
Wei Jia3f273d12015-11-24 09:06:49 -0800931
932 if (mNotifiedBatteryStart) {
Wei Jiaf2ae3e12016-10-27 17:10:59 -0700933 // TODO: call this function for each track when it becomes inactive.
934 BatteryNotifier::getInstance().noteStopAudio(AID_AUDIOSERVER);
Wei Jia3f273d12015-11-24 09:06:49 -0800935 mNotifiedBatteryStart = false;
936 }
Eric Laurent81784c32012-11-19 14:55:58 -0800937}
938
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800939void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
940 Mutex::Autolock _l(mLock);
941 updateWakeLockUids_l(uids);
942}
943
944void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700945 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800946 // use checkService() to avoid blocking if power service is not up yet
947 sp<IBinder> binder =
948 defaultServiceManager()->checkService(String16("power"));
949 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800950 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 } else {
952 mPowerManager = interface_cast<IPowerManager>(binder);
953 binder->linkToDeath(mDeathRecipient);
954 }
955 }
956}
957
958void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800959 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -0800960 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
961 if (mSystemReady) {
962 ALOGE("no wake lock to update, but system ready!");
963 } else {
964 ALOGW("no wake lock to update, system not ready yet");
965 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800966 return;
967 }
968 if (mPowerManager != 0) {
969 sp<IBinder> binder = new BBinder();
970 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700971 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
972 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800973 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800974 }
975}
976
Eric Laurent81784c32012-11-19 14:55:58 -0800977void AudioFlinger::ThreadBase::clearPowerManager()
978{
979 Mutex::Autolock _l(mLock);
980 releaseWakeLock_l();
981 mPowerManager.clear();
982}
983
Glenn Kasten0f11b512014-01-31 16:18:54 -0800984void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800985{
986 sp<ThreadBase> thread = mThread.promote();
987 if (thread != 0) {
988 thread->clearPowerManager();
989 }
990 ALOGW("power manager service died !!!");
991}
992
993void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800994 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800995{
996 Mutex::Autolock _l(mLock);
997 setEffectSuspended_l(type, suspend, sessionId);
998}
999
1000void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001001 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001002{
1003 sp<EffectChain> chain = getEffectChain_l(sessionId);
1004 if (chain != 0) {
1005 if (type != NULL) {
1006 chain->setEffectSuspended_l(type, suspend);
1007 } else {
1008 chain->setEffectSuspendedAll_l(suspend);
1009 }
1010 }
1011
1012 updateSuspendedSessions_l(type, suspend, sessionId);
1013}
1014
1015void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1016{
1017 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1018 if (index < 0) {
1019 return;
1020 }
1021
1022 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1023 mSuspendedSessions.valueAt(index);
1024
1025 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001026 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001027 for (int j = 0; j < desc->mRefCount; j++) {
1028 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1029 chain->setEffectSuspendedAll_l(true);
1030 } else {
1031 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1032 desc->mType.timeLow);
1033 chain->setEffectSuspended_l(&desc->mType, true);
1034 }
1035 }
1036 }
1037}
1038
1039void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1040 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001041 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001042{
1043 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1044
1045 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1046
1047 if (suspend) {
1048 if (index >= 0) {
1049 sessionEffects = mSuspendedSessions.valueAt(index);
1050 } else {
1051 mSuspendedSessions.add(sessionId, sessionEffects);
1052 }
1053 } else {
1054 if (index < 0) {
1055 return;
1056 }
1057 sessionEffects = mSuspendedSessions.valueAt(index);
1058 }
1059
1060
1061 int key = EffectChain::kKeyForSuspendAll;
1062 if (type != NULL) {
1063 key = type->timeLow;
1064 }
1065 index = sessionEffects.indexOfKey(key);
1066
1067 sp<SuspendedSessionDesc> desc;
1068 if (suspend) {
1069 if (index >= 0) {
1070 desc = sessionEffects.valueAt(index);
1071 } else {
1072 desc = new SuspendedSessionDesc();
1073 if (type != NULL) {
1074 desc->mType = *type;
1075 }
1076 sessionEffects.add(key, desc);
1077 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1078 }
1079 desc->mRefCount++;
1080 } else {
1081 if (index < 0) {
1082 return;
1083 }
1084 desc = sessionEffects.valueAt(index);
1085 if (--desc->mRefCount == 0) {
1086 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1087 sessionEffects.removeItemsAt(index);
1088 if (sessionEffects.isEmpty()) {
1089 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1090 sessionId);
1091 mSuspendedSessions.removeItem(sessionId);
1092 }
1093 }
1094 }
1095 if (!sessionEffects.isEmpty()) {
1096 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1097 }
1098}
1099
1100void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1101 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001102 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001103{
1104 Mutex::Autolock _l(mLock);
1105 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1106}
1107
1108void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1109 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001110 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001111{
1112 if (mType != RECORD) {
1113 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1114 // another session. This gives the priority to well behaved effect control panels
1115 // and applications not using global effects.
1116 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1117 // global effects
1118 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1119 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1120 }
1121 }
1122
1123 sp<EffectChain> chain = getEffectChain_l(sessionId);
1124 if (chain != 0) {
1125 chain->checkSuspendOnEffectEnabled(effect, enabled);
1126 }
1127}
1128
Eric Laurent4c415062016-06-17 16:14:16 -07001129// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1130status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1131 const effect_descriptor_t *desc, audio_session_t sessionId)
1132{
1133 // No global effect sessions on record threads
1134 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1135 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1136 desc->name, mThreadName);
1137 return BAD_VALUE;
1138 }
1139 // only pre processing effects on record thread
1140 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1141 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1142 desc->name, mThreadName);
1143 return BAD_VALUE;
1144 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001145
1146 // always allow effects without processing load or latency
1147 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1148 return NO_ERROR;
1149 }
1150
Eric Laurent4c415062016-06-17 16:14:16 -07001151 audio_input_flags_t flags = mInput->flags;
1152 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1153 if (flags & AUDIO_INPUT_FLAG_RAW) {
1154 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1155 desc->name, mThreadName);
1156 return BAD_VALUE;
1157 }
1158 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1159 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1160 desc->name, mThreadName);
1161 return BAD_VALUE;
1162 }
1163 }
1164 return NO_ERROR;
1165}
1166
1167// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1168status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1169 const effect_descriptor_t *desc, audio_session_t sessionId)
1170{
1171 // no preprocessing on playback threads
1172 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1173 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1174 " thread %s", desc->name, mThreadName);
1175 return BAD_VALUE;
1176 }
1177
1178 switch (mType) {
1179 case MIXER: {
1180 // Reject any effect on mixer multichannel sinks.
1181 // TODO: fix both format and multichannel issues with effects.
1182 if (mChannelCount != FCC_2) {
1183 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1184 " thread %s", desc->name, mChannelCount, mThreadName);
1185 return BAD_VALUE;
1186 }
1187 audio_output_flags_t flags = mOutput->flags;
1188 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1189 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1190 // global effects are applied only to non fast tracks if they are SW
1191 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1192 break;
1193 }
1194 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1195 // only post processing on output stage session
1196 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1197 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1198 " on output stage session", desc->name);
1199 return BAD_VALUE;
1200 }
1201 } else {
1202 // no restriction on effects applied on non fast tracks
1203 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1204 break;
1205 }
1206 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001207
1208 // always allow effects without processing load or latency
1209 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1210 break;
1211 }
Eric Laurent4c415062016-06-17 16:14:16 -07001212 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1213 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1214 desc->name);
1215 return BAD_VALUE;
1216 }
1217 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1218 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1219 " in fast mode", desc->name);
1220 return BAD_VALUE;
1221 }
1222 }
1223 } break;
1224 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001225 // nothing actionable on offload threads, if the effect:
1226 // - is offloadable: the effect can be created
1227 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1228 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001229 break;
1230 case DIRECT:
1231 // Reject any effect on Direct output threads for now, since the format of
1232 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1233 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1234 desc->name, mThreadName);
1235 return BAD_VALUE;
1236 case DUPLICATING:
1237 // Reject any effect on mixer multichannel sinks.
1238 // TODO: fix both format and multichannel issues with effects.
1239 if (mChannelCount != FCC_2) {
1240 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1241 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1245 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1246 " thread %s", desc->name, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1250 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1251 " DUPLICATING thread %s", desc->name, mThreadName);
1252 return BAD_VALUE;
1253 }
1254 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1255 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1256 " DUPLICATING thread %s", desc->name, mThreadName);
1257 return BAD_VALUE;
1258 }
1259 break;
1260 default:
1261 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1262 }
1263
1264 return NO_ERROR;
1265}
1266
Eric Laurent81784c32012-11-19 14:55:58 -08001267// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1268sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1269 const sp<AudioFlinger::Client>& client,
1270 const sp<IEffectClient>& effectClient,
1271 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001272 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001273 effect_descriptor_t *desc,
1274 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001275 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001276{
1277 sp<EffectModule> effect;
1278 sp<EffectHandle> handle;
1279 status_t lStatus;
1280 sp<EffectChain> chain;
1281 bool chainCreated = false;
1282 bool effectCreated = false;
1283 bool effectRegistered = false;
1284
1285 lStatus = initCheck();
1286 if (lStatus != NO_ERROR) {
1287 ALOGW("createEffect_l() Audio driver not initialized.");
1288 goto Exit;
1289 }
1290
Eric Laurent81784c32012-11-19 14:55:58 -08001291 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1292
1293 { // scope for mLock
1294 Mutex::Autolock _l(mLock);
1295
Eric Laurent4c415062016-06-17 16:14:16 -07001296 lStatus = checkEffectCompatibility_l(desc, sessionId);
1297 if (lStatus != NO_ERROR) {
1298 goto Exit;
1299 }
1300
Eric Laurent81784c32012-11-19 14:55:58 -08001301 // check for existing effect chain with the requested audio session
1302 chain = getEffectChain_l(sessionId);
1303 if (chain == 0) {
1304 // create a new chain for this session
1305 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1306 chain = new EffectChain(this, sessionId);
1307 addEffectChain_l(chain);
1308 chain->setStrategy(getStrategyForSession_l(sessionId));
1309 chainCreated = true;
1310 } else {
1311 effect = chain->getEffectFromDesc_l(desc);
1312 }
1313
1314 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1315
1316 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001317 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001318 // Check CPU and memory usage
1319 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1320 if (lStatus != NO_ERROR) {
1321 goto Exit;
1322 }
1323 effectRegistered = true;
1324 // create a new effect module if none present in the chain
1325 effect = new EffectModule(this, chain, desc, id, sessionId);
1326 lStatus = effect->status();
1327 if (lStatus != NO_ERROR) {
1328 goto Exit;
1329 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001330 effect->setOffloaded(mType == OFFLOAD, mId);
1331
Eric Laurent81784c32012-11-19 14:55:58 -08001332 lStatus = chain->addEffect_l(effect);
1333 if (lStatus != NO_ERROR) {
1334 goto Exit;
1335 }
1336 effectCreated = true;
1337
1338 effect->setDevice(mOutDevice);
1339 effect->setDevice(mInDevice);
1340 effect->setMode(mAudioFlinger->getMode());
1341 effect->setAudioSource(mAudioSource);
1342 }
1343 // create effect handle and connect it to effect module
1344 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001345 lStatus = handle->initCheck();
1346 if (lStatus == OK) {
1347 lStatus = effect->addHandle(handle.get());
1348 }
Eric Laurent81784c32012-11-19 14:55:58 -08001349 if (enabled != NULL) {
1350 *enabled = (int)effect->isEnabled();
1351 }
1352 }
1353
1354Exit:
1355 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1356 Mutex::Autolock _l(mLock);
1357 if (effectCreated) {
1358 chain->removeEffect_l(effect);
1359 }
1360 if (effectRegistered) {
1361 AudioSystem::unregisterEffect(effect->id());
1362 }
1363 if (chainCreated) {
1364 removeEffectChain_l(chain);
1365 }
1366 handle.clear();
1367 }
1368
Glenn Kasten9156ef32013-08-06 15:39:08 -07001369 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001370 return handle;
1371}
1372
Glenn Kastend848eb42016-03-08 13:42:11 -08001373sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1374 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001375{
1376 Mutex::Autolock _l(mLock);
1377 return getEffect_l(sessionId, effectId);
1378}
1379
Glenn Kastend848eb42016-03-08 13:42:11 -08001380sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1381 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001382{
1383 sp<EffectChain> chain = getEffectChain_l(sessionId);
1384 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1385}
1386
1387// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1388// PlaybackThread::mLock held
1389status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1390{
1391 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001392 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001393 sp<EffectChain> chain = getEffectChain_l(sessionId);
1394 bool chainCreated = false;
1395
Eric Laurent5baf2af2013-09-12 17:37:00 -07001396 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1397 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1398 this, effect->desc().name, effect->desc().flags);
1399
Eric Laurent81784c32012-11-19 14:55:58 -08001400 if (chain == 0) {
1401 // create a new chain for this session
1402 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1403 chain = new EffectChain(this, sessionId);
1404 addEffectChain_l(chain);
1405 chain->setStrategy(getStrategyForSession_l(sessionId));
1406 chainCreated = true;
1407 }
1408 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1409
1410 if (chain->getEffectFromId_l(effect->id()) != 0) {
1411 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1412 this, effect->desc().name, chain.get());
1413 return BAD_VALUE;
1414 }
1415
Eric Laurent5baf2af2013-09-12 17:37:00 -07001416 effect->setOffloaded(mType == OFFLOAD, mId);
1417
Eric Laurent81784c32012-11-19 14:55:58 -08001418 status_t status = chain->addEffect_l(effect);
1419 if (status != NO_ERROR) {
1420 if (chainCreated) {
1421 removeEffectChain_l(chain);
1422 }
1423 return status;
1424 }
1425
1426 effect->setDevice(mOutDevice);
1427 effect->setDevice(mInDevice);
1428 effect->setMode(mAudioFlinger->getMode());
1429 effect->setAudioSource(mAudioSource);
1430 return NO_ERROR;
1431}
1432
1433void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1434
1435 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1436 effect_descriptor_t desc = effect->desc();
1437 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1438 detachAuxEffect_l(effect->id());
1439 }
1440
1441 sp<EffectChain> chain = effect->chain().promote();
1442 if (chain != 0) {
1443 // remove effect chain if removing last effect
1444 if (chain->removeEffect_l(effect) == 0) {
1445 removeEffectChain_l(chain);
1446 }
1447 } else {
1448 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1449 }
1450}
1451
1452void AudioFlinger::ThreadBase::lockEffectChains_l(
1453 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1454{
1455 effectChains = mEffectChains;
1456 for (size_t i = 0; i < mEffectChains.size(); i++) {
1457 mEffectChains[i]->lock();
1458 }
1459}
1460
1461void AudioFlinger::ThreadBase::unlockEffectChains(
1462 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1463{
1464 for (size_t i = 0; i < effectChains.size(); i++) {
1465 effectChains[i]->unlock();
1466 }
1467}
1468
Glenn Kastend848eb42016-03-08 13:42:11 -08001469sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001470{
1471 Mutex::Autolock _l(mLock);
1472 return getEffectChain_l(sessionId);
1473}
1474
Glenn Kastend848eb42016-03-08 13:42:11 -08001475sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1476 const
Eric Laurent81784c32012-11-19 14:55:58 -08001477{
1478 size_t size = mEffectChains.size();
1479 for (size_t i = 0; i < size; i++) {
1480 if (mEffectChains[i]->sessionId() == sessionId) {
1481 return mEffectChains[i];
1482 }
1483 }
1484 return 0;
1485}
1486
1487void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1488{
1489 Mutex::Autolock _l(mLock);
1490 size_t size = mEffectChains.size();
1491 for (size_t i = 0; i < size; i++) {
1492 mEffectChains[i]->setMode_l(mode);
1493 }
1494}
1495
Eric Laurent83b88082014-06-20 18:31:16 -07001496void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1497{
1498 config->type = AUDIO_PORT_TYPE_MIX;
1499 config->ext.mix.handle = mId;
1500 config->sample_rate = mSampleRate;
1501 config->format = mFormat;
1502 config->channel_mask = mChannelMask;
1503 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1504 AUDIO_PORT_CONFIG_FORMAT;
1505}
1506
Eric Laurent72e3f392015-05-20 14:43:50 -07001507void AudioFlinger::ThreadBase::systemReady()
1508{
1509 Mutex::Autolock _l(mLock);
1510 if (mSystemReady) {
1511 return;
1512 }
1513 mSystemReady = true;
1514
1515 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1516 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1517 }
1518 mPendingConfigEvents.clear();
1519}
1520
Eric Laurent83b88082014-06-20 18:31:16 -07001521
Eric Laurent81784c32012-11-19 14:55:58 -08001522// ----------------------------------------------------------------------------
1523// Playback
1524// ----------------------------------------------------------------------------
1525
1526AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1527 AudioStreamOut* output,
1528 audio_io_handle_t id,
1529 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001530 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001531 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001532 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001533 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001534 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001535 mMixerBuffer(NULL),
1536 mMixerBufferSize(0),
1537 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1538 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001539 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001540 mEffectBuffer(NULL),
1541 mEffectBufferSize(0),
1542 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1543 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001544 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001545 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001546 mSuspendedFrames(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001547 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001548 // mStreamTypes[] initialized in constructor body
1549 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001550 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001551 mMixerStatus(MIXER_IDLE),
1552 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001553 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001554 mBytesRemaining(0),
1555 mCurrentWriteLength(0),
1556 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001557 mWriteAckSequence(0),
1558 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001559 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001560 mScreenState(AudioFlinger::mScreenState),
1561 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001562 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001563 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001564{
Glenn Kastend7dca052015-03-05 16:05:54 -08001565 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1566 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001567
1568 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1569 // it would be safer to explicitly pass initial masterVolume/masterMute as
1570 // parameter.
1571 //
1572 // If the HAL we are using has support for master volume or master mute,
1573 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1574 // and the mute set to false).
1575 mMasterVolume = audioFlinger->masterVolume_l();
1576 mMasterMute = audioFlinger->masterMute_l();
1577 if (mOutput && mOutput->audioHwDev) {
1578 if (mOutput->audioHwDev->canSetMasterVolume()) {
1579 mMasterVolume = 1.0;
1580 }
1581
1582 if (mOutput->audioHwDev->canSetMasterMute()) {
1583 mMasterMute = false;
1584 }
1585 }
1586
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001587 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001588
Eric Laurent223fd5c2014-11-11 13:43:36 -08001589 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001590 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001591 stream = (audio_stream_type_t) (stream + 1)) {
1592 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1593 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1594 }
Eric Laurent81784c32012-11-19 14:55:58 -08001595}
1596
1597AudioFlinger::PlaybackThread::~PlaybackThread()
1598{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001599 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001600 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001601 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001602 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001603}
1604
1605void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1606{
1607 dumpInternals(fd, args);
1608 dumpTracks(fd, args);
1609 dumpEffectChains(fd, args);
1610}
1611
Glenn Kasten0f11b512014-01-31 16:18:54 -08001612void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001613{
1614 const size_t SIZE = 256;
1615 char buffer[SIZE];
1616 String8 result;
1617
Marco Nelissenb2208842014-02-07 14:00:50 -08001618 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001619 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1620 const stream_type_t *st = &mStreamTypes[i];
1621 if (i > 0) {
1622 result.appendFormat(", ");
1623 }
1624 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1625 if (st->mute) {
1626 result.append("M");
1627 }
1628 }
1629 result.append("\n");
1630 write(fd, result.string(), result.length());
1631 result.clear();
1632
Eric Laurent81784c32012-11-19 14:55:58 -08001633 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1634 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001635 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001636 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001637
1638 size_t numtracks = mTracks.size();
1639 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001640 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001641 size_t numactiveseen = 0;
1642 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001643 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001644 Track::appendDumpHeader(result);
1645 for (size_t i = 0; i < numtracks; ++i) {
1646 sp<Track> track = mTracks[i];
1647 if (track != 0) {
1648 bool active = mActiveTracks.indexOf(track) >= 0;
1649 if (active) {
1650 numactiveseen++;
1651 }
1652 track->dump(buffer, SIZE, active);
1653 result.append(buffer);
1654 }
1655 }
1656 } else {
1657 result.append("\n");
1658 }
1659 if (numactiveseen != numactive) {
1660 // some tracks in the active list were not in the tracks list
1661 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1662 " not in the track list\n");
1663 result.append(buffer);
1664 Track::appendDumpHeader(result);
1665 for (size_t i = 0; i < numactive; ++i) {
1666 sp<Track> track = mActiveTracks[i].promote();
1667 if (track != 0 && mTracks.indexOf(track) < 0) {
1668 track->dump(buffer, SIZE, true);
1669 result.append(buffer);
1670 }
1671 }
1672 }
1673
1674 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001675}
1676
1677void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1678{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001679 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001680
1681 dumpBase(fd, args);
1682
Elliott Hughes87cebad2014-05-22 10:14:43 -07001683 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001684 dprintf(fd, " Last write occurred (msecs): %llu\n",
1685 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001686 dprintf(fd, " Total writes: %d\n", mNumWrites);
1687 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1688 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1689 dprintf(fd, " Suspend count: %d\n", mSuspended);
1690 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1691 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1692 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1693 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001694 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001695 AudioStreamOut *output = mOutput;
1696 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001697 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1698 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001699 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1700 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1701 if (mPipeSink.get() != nullptr) {
1702 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1703 }
1704 if (output != nullptr) {
1705 dprintf(fd, " Hal stream dump:\n");
1706 (void)output->stream->dump(fd);
1707 }
Eric Laurent81784c32012-11-19 14:55:58 -08001708}
1709
1710// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001711
1712void AudioFlinger::PlaybackThread::onFirstRef()
1713{
Glenn Kastend7dca052015-03-05 16:05:54 -08001714 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001715}
1716
1717// ThreadBase virtuals
1718void AudioFlinger::PlaybackThread::preExit()
1719{
1720 ALOGV(" preExit()");
1721 // FIXME this is using hard-coded strings but in the future, this functionality will be
1722 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001723 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1724 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001725}
1726
1727// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1728sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1729 const sp<AudioFlinger::Client>& client,
1730 audio_stream_type_t streamType,
1731 uint32_t sampleRate,
1732 audio_format_t format,
1733 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001734 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001735 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001736 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001737 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001738 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001739 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001740 status_t *status)
1741{
Glenn Kasten74935e42013-12-19 08:56:45 -08001742 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001743 sp<Track> track;
1744 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001745 audio_output_flags_t outputFlags = mOutput->flags;
1746
1747 // special case for FAST flag considered OK if fast mixer is present
1748 if (hasFastMixer()) {
1749 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1750 }
1751
1752 // Check if requested flags are compatible with output stream flags
1753 if ((*flags & outputFlags) != *flags) {
1754 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1755 *flags, outputFlags);
1756 *flags = (audio_output_flags_t)(*flags & outputFlags);
1757 }
Eric Laurent81784c32012-11-19 14:55:58 -08001758
Eric Laurent81784c32012-11-19 14:55:58 -08001759 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001760 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001761 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001762 // PCM data
1763 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001764 // TODO: extract as a data library function that checks that a computationally
1765 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001766 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001767 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1768 (channelMask == AUDIO_CHANNEL_OUT_MONO
1769 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001770 // hardware sample rate
1771 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001772 // normal mixer has an associated fast mixer
1773 hasFastMixer() &&
1774 // there are sufficient fast track slots available
1775 (mFastTrackAvailMask != 0)
1776 // FIXME test that MixerThread for this fast track has a capable output HAL
1777 // FIXME add a permission test also?
1778 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001779 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1780 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001781 // read the fast track multiplier property the first time it is needed
1782 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1783 if (ok != 0) {
1784 ALOGE("%s pthread_once failed: %d", __func__, ok);
1785 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001786 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001787 }
Eric Laurent4c415062016-06-17 16:14:16 -07001788
1789 // check compatibility with audio effects.
1790 { // scope for mLock
1791 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001792 for (audio_session_t session : {
1793 AUDIO_SESSION_OUTPUT_STAGE,
1794 AUDIO_SESSION_OUTPUT_MIX,
1795 sessionId,
1796 }) {
1797 sp<EffectChain> chain = getEffectChain_l(session);
1798 if (chain.get() != nullptr) {
1799 audio_output_flags_t old = *flags;
1800 chain->checkOutputFlagCompatibility(flags);
1801 if (old != *flags) {
1802 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1803 (int)session, (int)old, (int)*flags);
1804 }
Eric Laurent4c415062016-06-17 16:14:16 -07001805 }
1806 }
1807 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001808 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001809 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1810 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001811 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001812 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1813 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001814 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001815 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001816 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001817 audio_is_linear_pcm(format),
1818 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001819 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001820 }
1821 }
1822 // For normal PCM streaming tracks, update minimum frame count.
1823 // For compatibility with AudioTrack calculation, buffer depth is forced
1824 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1825 // This is probably too conservative, but legacy application code may depend on it.
1826 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001827 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001828 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001829 // this must match AudioTrack.cpp calculateMinFrameCount().
1830 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001831 uint32_t latencyMs = 0;
1832 lStatus = mOutput->stream->getLatency(&latencyMs);
1833 if (lStatus != OK) {
1834 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1835 goto Exit;
1836 }
Eric Laurent81784c32012-11-19 14:55:58 -08001837 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1838 if (minBufCount < 2) {
1839 minBufCount = 2;
1840 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001841 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1842 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001843 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001844 minBufCount * sourceFramesNeededWithTimestretch(
1845 sampleRate, mNormalFrameCount,
1846 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001847 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001848 frameCount = minFrameCount;
1849 }
Eric Laurent81784c32012-11-19 14:55:58 -08001850 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001851 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001852
Glenn Kastenc3df8382014-03-13 15:05:25 -07001853 switch (mType) {
1854
1855 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001856 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001857 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001858 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1859 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001860 sampleRate, format, channelMask, mOutput, mFormat);
1861 lStatus = BAD_VALUE;
1862 goto Exit;
1863 }
1864 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001865 break;
1866
1867 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001868 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001869 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1870 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001871 sampleRate, format, channelMask, mOutput, mFormat);
1872 lStatus = BAD_VALUE;
1873 goto Exit;
1874 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001875 break;
1876
1877 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001878 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001879 ALOGE("createTrack_l() Bad parameter: format %#x \""
1880 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001881 format, mOutput, mFormat);
1882 lStatus = BAD_VALUE;
1883 goto Exit;
1884 }
Andy Hungcd044842014-08-07 11:04:34 -07001885 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001886 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1887 lStatus = BAD_VALUE;
1888 goto Exit;
1889 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001890 break;
1891
Eric Laurent81784c32012-11-19 14:55:58 -08001892 }
1893
1894 lStatus = initCheck();
1895 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001896 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001897 goto Exit;
1898 }
1899
1900 { // scope for mLock
1901 Mutex::Autolock _l(mLock);
1902
1903 // all tracks in same audio session must share the same routing strategy otherwise
1904 // conflicts will happen when tracks are moved from one output to another by audio policy
1905 // manager
1906 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1907 for (size_t i = 0; i < mTracks.size(); ++i) {
1908 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001909 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001910 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1911 if (sessionId == t->sessionId() && strategy != actual) {
1912 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1913 strategy, actual);
1914 lStatus = BAD_VALUE;
1915 goto Exit;
1916 }
1917 }
1918 }
1919
Glenn Kastend79072e2016-01-06 08:41:20 -08001920 track = new Track(this, client, streamType, sampleRate, format,
1921 channelMask, frameCount, NULL, sharedBuffer,
1922 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001923
Glenn Kasten03003332013-08-06 15:40:54 -07001924 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1925 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001926 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001927 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001928 goto Exit;
1929 }
1930 mTracks.add(track);
1931
1932 sp<EffectChain> chain = getEffectChain_l(sessionId);
1933 if (chain != 0) {
1934 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1935 track->setMainBuffer(chain->inBuffer());
1936 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1937 chain->incTrackCnt();
1938 }
1939
Eric Laurent05067782016-06-01 18:27:28 -07001940 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001941 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1942 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1943 // so ask activity manager to do this on our behalf
1944 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1945 }
1946 }
1947
1948 lStatus = NO_ERROR;
1949
1950Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001951 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001952 return track;
1953}
1954
1955uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1956{
1957 return latency;
1958}
1959
1960uint32_t AudioFlinger::PlaybackThread::latency() const
1961{
1962 Mutex::Autolock _l(mLock);
1963 return latency_l();
1964}
1965uint32_t AudioFlinger::PlaybackThread::latency_l() const
1966{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001967 uint32_t latency;
1968 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
1969 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08001970 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001971 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001972}
1973
1974void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1975{
1976 Mutex::Autolock _l(mLock);
1977 // Don't apply master volume in SW if our HAL can do it for us.
1978 if (mOutput && mOutput->audioHwDev &&
1979 mOutput->audioHwDev->canSetMasterVolume()) {
1980 mMasterVolume = 1.0;
1981 } else {
1982 mMasterVolume = value;
1983 }
1984}
1985
1986void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1987{
1988 Mutex::Autolock _l(mLock);
1989 // Don't apply master mute in SW if our HAL can do it for us.
1990 if (mOutput && mOutput->audioHwDev &&
1991 mOutput->audioHwDev->canSetMasterMute()) {
1992 mMasterMute = false;
1993 } else {
1994 mMasterMute = muted;
1995 }
1996}
1997
1998void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1999{
2000 Mutex::Autolock _l(mLock);
2001 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002002 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002003}
2004
2005void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2006{
2007 Mutex::Autolock _l(mLock);
2008 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002009 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002010}
2011
2012float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2013{
2014 Mutex::Autolock _l(mLock);
2015 return mStreamTypes[stream].volume;
2016}
2017
2018// addTrack_l() must be called with ThreadBase::mLock held
2019status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2020{
2021 status_t status = ALREADY_EXISTS;
2022
Eric Laurent81784c32012-11-19 14:55:58 -08002023 if (mActiveTracks.indexOf(track) < 0) {
2024 // the track is newly added, make sure it fills up all its
2025 // buffers before playing. This is to ensure the client will
2026 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002027 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002028 TrackBase::track_state state = track->mState;
2029 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002030 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002031 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002032 mLock.lock();
2033 // abort track was stopped/paused while we released the lock
2034 if (state != track->mState) {
2035 if (status == NO_ERROR) {
2036 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002037 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002038 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002039 mLock.lock();
2040 }
2041 return INVALID_OPERATION;
2042 }
2043 // abort if start is rejected by audio policy manager
2044 if (status != NO_ERROR) {
2045 return PERMISSION_DENIED;
2046 }
2047#ifdef ADD_BATTERY_DATA
2048 // to track the speaker usage
2049 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2050#endif
2051 }
2052
Eric Laurent51716182016-02-29 18:00:56 -08002053 // set retry count for buffer fill
2054 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002055 if (track->isStopping_1()) {
2056 track->mRetryCount = kMaxTrackStopRetriesOffload;
2057 } else {
2058 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2059 }
2060 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002061 } else {
2062 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002063 track->mFillingUpStatus =
2064 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002065 }
2066
Eric Laurent81784c32012-11-19 14:55:58 -08002067 track->mResetDone = false;
2068 track->mPresentationCompleteFrames = 0;
2069 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002070 mWakeLockUids.add(track->uid());
2071 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002072 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002073 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2074 if (chain != 0) {
2075 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2076 track->sessionId());
2077 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002078 }
2079
2080 status = NO_ERROR;
2081 }
2082
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002083 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002084 return status;
2085}
2086
Eric Laurentbfb1b832013-01-07 09:53:42 -08002087bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002088{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002089 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002090 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002091 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2092 track->mState = TrackBase::STOPPED;
2093 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002094 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002095 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002096 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002097 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002098
2099 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002100}
2101
2102void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2103{
2104 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2105 mTracks.remove(track);
2106 deleteTrackName_l(track->name());
2107 // redundant as track is about to be destroyed, for dumpsys only
2108 track->mName = -1;
2109 if (track->isFastTrack()) {
2110 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002111 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002112 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2113 mFastTrackAvailMask |= 1 << index;
2114 // redundant as track is about to be destroyed, for dumpsys only
2115 track->mFastIndex = -1;
2116 }
2117 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2118 if (chain != 0) {
2119 chain->decTrackCnt();
2120 }
2121}
2122
Eric Laurentede6c3b2013-09-19 14:37:46 -07002123void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002124{
2125 // Thread could be blocked waiting for async
2126 // so signal it to handle state changes immediately
2127 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2128 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2129 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002130 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002131}
2132
Eric Laurent81784c32012-11-19 14:55:58 -08002133String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2134{
Eric Laurent81784c32012-11-19 14:55:58 -08002135 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002136 String8 out_s8;
2137 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2138 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002139 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002140 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002141}
2142
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002143void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002144 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2145 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002146
Eric Laurent73e26b62015-04-27 16:55:58 -07002147 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002148
2149 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002150 case AUDIO_OUTPUT_OPENED:
2151 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002152 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002153 desc->mChannelMask = mChannelMask;
2154 desc->mSamplingRate = mSampleRate;
2155 desc->mFormat = mFormat;
2156 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002157 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002158 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002159 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002160 break;
2161
Eric Laurent73e26b62015-04-27 16:55:58 -07002162 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002163 default:
2164 break;
2165 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002166 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002167}
2168
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002169void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002170{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002171 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002172}
2173
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002174void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002175{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002176 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002177}
2178
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002179void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002180{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002181 mCallbackThread->setAsyncError();
2182}
2183
Eric Laurent3b4529e2013-09-05 18:09:19 -07002184void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002185{
2186 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002187 // reject out of sequence requests
2188 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2189 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002190 mWaitWorkCV.signal();
2191 }
2192}
2193
Eric Laurent3b4529e2013-09-05 18:09:19 -07002194void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002195{
2196 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002197 // reject out of sequence requests
2198 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2199 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200 mWaitWorkCV.signal();
2201 }
2202}
2203
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002204void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002205{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002206 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002207 mSampleRate = mOutput->getSampleRate();
2208 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002209 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002210 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002211 }
Andy Hung9a592762014-07-21 21:56:01 -07002212 if ((mType == MIXER || mType == DUPLICATING)
2213 && !isValidPcmSinkChannelMask(mChannelMask)) {
2214 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2215 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002216 }
Andy Hunge5412692014-05-16 11:25:07 -07002217 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002218
2219 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002220 status_t result = mOutput->stream->getFormat(&mHALFormat);
2221 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002222 // Get format from the shim, which will be different than the HAL format
2223 // if playing compressed audio over HDMI passthrough.
2224 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002225 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002226 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002227 }
Andy Hung6146c082014-03-18 11:56:15 -07002228 if ((mType == MIXER || mType == DUPLICATING)
2229 && !isValidPcmSinkFormat(mFormat)) {
2230 LOG_FATAL("HAL format %#x not supported for mixed output",
2231 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002232 }
Phil Burk062e67a2015-02-11 13:40:50 -08002233 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002234 result = mOutput->stream->getBufferSize(&mBufferSize);
2235 LOG_ALWAYS_FATAL_IF(result != OK,
2236 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002237 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002238 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002239 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002240 mFrameCount);
2241 }
2242
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002243 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2244 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002245 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002246 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002247 }
2248 }
2249
Eric Laurentd1f69b02014-12-15 14:33:13 -08002250 mHwSupportsPause = false;
2251 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002252 bool supportsPause = false, supportsResume = false;
2253 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2254 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002255 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002256 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002257 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002258 } else if (supportsResume) {
2259 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002260 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002261 }
2262 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002263 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2264 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2265 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002266
Andy Hungfbfc3952015-01-15 13:33:51 -08002267 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2268 // For best precision, we use float instead of the associated output
2269 // device format (typically PCM 16 bit).
2270
2271 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2272 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2273 mBufferSize = mFrameSize * mFrameCount;
2274
2275 // TODO: We currently use the associated output device channel mask and sample rate.
2276 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2277 // (if a valid mask) to avoid premature downmix.
2278 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2279 // instead of the output device sample rate to avoid loss of high frequency information.
2280 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2281 }
2282
Andy Hung09a50072014-02-27 14:30:47 -08002283 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002284 double multiplier = 1.0;
2285 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2286 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002287 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2288 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002289
Eric Laurent81784c32012-11-19 14:55:58 -08002290 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2291 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2292 maxNormalFrameCount = maxNormalFrameCount & ~15;
2293 if (maxNormalFrameCount < minNormalFrameCount) {
2294 maxNormalFrameCount = minNormalFrameCount;
2295 }
2296 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2297 if (multiplier <= 1.0) {
2298 multiplier = 1.0;
2299 } else if (multiplier <= 2.0) {
2300 if (2 * mFrameCount <= maxNormalFrameCount) {
2301 multiplier = 2.0;
2302 } else {
2303 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2304 }
2305 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002306 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002307 }
2308 }
2309 mNormalFrameCount = multiplier * mFrameCount;
2310 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002311 if (mType == MIXER || mType == DUPLICATING) {
2312 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2313 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002314 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002315 mNormalFrameCount);
2316
Andy Hung08fb1742015-05-31 23:22:10 -07002317 // Check if we want to throttle the processing to no more than 2x normal rate
2318 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002319 mThreadThrottleTimeMs = 0;
2320 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002321 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2322
Andy Hung010a1a12014-03-13 13:57:33 -07002323 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2324 // Originally this was int16_t[] array, need to remove legacy implications.
2325 free(mSinkBuffer);
2326 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002327 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2328 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2329 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002330 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002331
Andy Hung69aed5f2014-02-25 17:24:40 -08002332 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2333 // drives the output.
2334 free(mMixerBuffer);
2335 mMixerBuffer = NULL;
2336 if (mMixerBufferEnabled) {
2337 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2338 mMixerBufferSize = mNormalFrameCount * mChannelCount
2339 * audio_bytes_per_sample(mMixerBufferFormat);
2340 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2341 }
Andy Hung98ef9782014-03-04 14:46:50 -08002342 free(mEffectBuffer);
2343 mEffectBuffer = NULL;
2344 if (mEffectBufferEnabled) {
2345 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2346 mEffectBufferSize = mNormalFrameCount * mChannelCount
2347 * audio_bytes_per_sample(mEffectBufferFormat);
2348 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2349 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002350
Eric Laurent81784c32012-11-19 14:55:58 -08002351 // force reconfiguration of effect chains and engines to take new buffer size and audio
2352 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002353 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002354 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2355 // matter.
2356 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2357 Vector< sp<EffectChain> > effectChains = mEffectChains;
2358 for (size_t i = 0; i < effectChains.size(); i ++) {
2359 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2360 }
2361}
2362
2363
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002364status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002365{
2366 if (halFrames == NULL || dspFrames == NULL) {
2367 return BAD_VALUE;
2368 }
2369 Mutex::Autolock _l(mLock);
2370 if (initCheck() != NO_ERROR) {
2371 return INVALID_OPERATION;
2372 }
Andy Hung818e7a32016-02-16 18:08:07 -08002373 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002374 *halFrames = framesWritten;
2375
2376 if (isSuspended()) {
2377 // return an estimation of rendered frames when the output is suspended
2378 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002379 *dspFrames = (uint32_t)
2380 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002381 return NO_ERROR;
2382 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002383 status_t status;
2384 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002385 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002386 *dspFrames = (size_t)frames;
2387 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002388 }
2389}
2390
Eric Laurent4c415062016-06-17 16:14:16 -07002391// hasAudioSession_l() must be called with ThreadBase::mLock held
2392uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002393{
Eric Laurent81784c32012-11-19 14:55:58 -08002394 uint32_t result = 0;
2395 if (getEffectChain_l(sessionId) != 0) {
2396 result = EFFECT_SESSION;
2397 }
2398
2399 for (size_t i = 0; i < mTracks.size(); ++i) {
2400 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002401 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002402 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002403 if (track->isFastTrack()) {
2404 result |= FAST_SESSION;
2405 }
Eric Laurent81784c32012-11-19 14:55:58 -08002406 break;
2407 }
2408 }
2409
2410 return result;
2411}
2412
Glenn Kastend848eb42016-03-08 13:42:11 -08002413uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002414{
2415 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2416 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2417 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2418 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2419 }
2420 for (size_t i = 0; i < mTracks.size(); i++) {
2421 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002422 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002423 return AudioSystem::getStrategyForStream(track->streamType());
2424 }
2425 }
2426 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2427}
2428
2429
Phil Burk062e67a2015-02-11 13:40:50 -08002430AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002431{
2432 Mutex::Autolock _l(mLock);
2433 return mOutput;
2434}
2435
Phil Burk062e67a2015-02-11 13:40:50 -08002436AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002437{
2438 Mutex::Autolock _l(mLock);
2439 AudioStreamOut *output = mOutput;
2440 mOutput = NULL;
2441 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2442 // must push a NULL and wait for ack
2443 mOutputSink.clear();
2444 mPipeSink.clear();
2445 mNormalSink.clear();
2446 return output;
2447}
2448
2449// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002450sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002451{
2452 if (mOutput == NULL) {
2453 return NULL;
2454 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002455 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002456}
2457
2458uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2459{
2460 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2461}
2462
2463status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2464{
2465 if (!isValidSyncEvent(event)) {
2466 return BAD_VALUE;
2467 }
2468
2469 Mutex::Autolock _l(mLock);
2470
2471 for (size_t i = 0; i < mTracks.size(); ++i) {
2472 sp<Track> track = mTracks[i];
2473 if (event->triggerSession() == track->sessionId()) {
2474 (void) track->setSyncEvent(event);
2475 return NO_ERROR;
2476 }
2477 }
2478
2479 return NAME_NOT_FOUND;
2480}
2481
2482bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2483{
2484 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2485}
2486
2487void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2488 const Vector< sp<Track> >& tracksToRemove)
2489{
2490 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002491 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002492 for (size_t i = 0 ; i < count ; i++) {
2493 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002494 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002495 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002496 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497#ifdef ADD_BATTERY_DATA
2498 // to track the speaker usage
2499 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2500#endif
2501 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002502 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002503 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002504 }
Eric Laurent81784c32012-11-19 14:55:58 -08002505 }
2506 }
2507 }
Eric Laurent81784c32012-11-19 14:55:58 -08002508}
2509
2510void AudioFlinger::PlaybackThread::checkSilentMode_l()
2511{
2512 if (!mMasterMute) {
2513 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002514 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2515 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2516 return;
2517 }
Eric Laurent81784c32012-11-19 14:55:58 -08002518 if (property_get("ro.audio.silent", value, "0") > 0) {
2519 char *endptr;
2520 unsigned long ul = strtoul(value, &endptr, 0);
2521 if (*endptr == '\0' && ul != 0) {
2522 ALOGD("Silence is golden");
2523 // The setprop command will not allow a property to be changed after
2524 // the first time it is set, so we don't have to worry about un-muting.
2525 setMasterMute_l(true);
2526 }
2527 }
2528 }
2529}
2530
2531// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002532ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002533{
Eric Laurent81784c32012-11-19 14:55:58 -08002534 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002535 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002536 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002537
2538 // If an NBAIO sink is present, use it to write the normal mixer's submix
2539 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002540
Andy Hung010a1a12014-03-13 13:57:33 -07002541 const size_t count = mBytesRemaining / mFrameSize;
2542
Simon Wilson2d590962012-11-29 15:18:50 -08002543 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002544 // update the setpoint when AudioFlinger::mScreenState changes
2545 uint32_t screenState = AudioFlinger::mScreenState;
2546 if (screenState != mScreenState) {
2547 mScreenState = screenState;
2548 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2549 if (pipe != NULL) {
2550 pipe->setAvgFrames((mScreenState & 1) ?
2551 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2552 }
2553 }
Andy Hung010a1a12014-03-13 13:57:33 -07002554 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002555 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002556 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002557 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002558 } else {
2559 bytesWritten = framesWritten;
2560 }
2561 // otherwise use the HAL / AudioStreamOut directly
2562 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002563 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002564
Eric Laurentbfb1b832013-01-07 09:53:42 -08002565 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002566 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2567 mWriteAckSequence += 2;
2568 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002569 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002570 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002571 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002572 // FIXME We should have an implementation of timestamps for direct output threads.
2573 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002574 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002575
Eric Laurentbfb1b832013-01-07 09:53:42 -08002576 if (mUseAsyncWrite &&
2577 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2578 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002579 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002580 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002581 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002582 }
Eric Laurent81784c32012-11-19 14:55:58 -08002583 }
2584
Eric Laurent81784c32012-11-19 14:55:58 -08002585 mNumWrites++;
2586 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002587 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002588 return bytesWritten;
2589}
2590
2591void AudioFlinger::PlaybackThread::threadLoop_drain()
2592{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002593 bool supportsDrain = false;
2594 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2596 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002597 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2598 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002600 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002601 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002602 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002603 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002604 }
2605}
2606
2607void AudioFlinger::PlaybackThread::threadLoop_exit()
2608{
Eric Laurent275e8e92014-11-30 15:14:47 -08002609 {
2610 Mutex::Autolock _l(mLock);
2611 for (size_t i = 0; i < mTracks.size(); i++) {
2612 sp<Track> track = mTracks[i];
2613 track->invalidate();
2614 }
2615 }
Eric Laurent81784c32012-11-19 14:55:58 -08002616}
2617
2618/*
2619The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002620 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002621 - mActiveSleepTimeUs from activeSleepTimeUs()
2622 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002623 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2624 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002625 - maxPeriod from frame count and sample rate (MIXER only)
2626
2627The parameters that affect these derived values are:
2628 - frame count
2629 - frame size
2630 - sample rate
2631 - device type: A2DP or not
2632 - device latency
2633 - format: PCM or not
2634 - active sleep time
2635 - idle sleep time
2636*/
2637
2638void AudioFlinger::PlaybackThread::cacheParameters_l()
2639{
Andy Hung25c2dac2014-02-27 14:56:00 -08002640 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002641 mActiveSleepTimeUs = activeSleepTimeUs();
2642 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002643
2644 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2645 // truncating audio when going to standby.
2646 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2647 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2648 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2649 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2650 }
2651 }
Eric Laurent81784c32012-11-19 14:55:58 -08002652}
2653
Eric Laurent13084622016-05-17 10:51:49 -07002654bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002655{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002656 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002657 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002658 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002659 size_t size = mTracks.size();
2660 for (size_t i = 0; i < size; i++) {
2661 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002662 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002663 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002664 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002665 }
2666 }
Eric Laurent13084622016-05-17 10:51:49 -07002667 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002668}
2669
Haynes Mathew George05317d22016-05-03 16:34:26 -07002670void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2671{
2672 Mutex::Autolock _l(mLock);
2673 invalidateTracks_l(streamType);
2674}
2675
Eric Laurent81784c32012-11-19 14:55:58 -08002676status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2677{
Glenn Kastend848eb42016-03-08 13:42:11 -08002678 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002679 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2680 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002681 bool ownsBuffer = false;
2682
2683 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002684 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002685 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002686 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002687 if (mType != DIRECT) {
2688 size_t numSamples = mNormalFrameCount * mChannelCount;
2689 buffer = new int16_t[numSamples];
2690 memset(buffer, 0, numSamples * sizeof(int16_t));
2691 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2692 ownsBuffer = true;
2693 }
2694
2695 // Attach all tracks with same session ID to this chain.
2696 for (size_t i = 0; i < mTracks.size(); ++i) {
2697 sp<Track> track = mTracks[i];
2698 if (session == track->sessionId()) {
2699 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2700 buffer);
2701 track->setMainBuffer(buffer);
2702 chain->incTrackCnt();
2703 }
2704 }
2705
2706 // indicate all active tracks in the chain
2707 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2708 sp<Track> track = mActiveTracks[i].promote();
2709 if (track == 0) {
2710 continue;
2711 }
2712 if (session == track->sessionId()) {
2713 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2714 chain->incActiveTrackCnt();
2715 }
2716 }
2717 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002718 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002719 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002720 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2721 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002722 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002723 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002724 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2725 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002726 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002727 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002728 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002729 // Effect chain for other sessions are inserted at beginning of effect
2730 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002731 // sessions is not important.
2732 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2733 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2734 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002735 size_t size = mEffectChains.size();
2736 size_t i = 0;
2737 for (i = 0; i < size; i++) {
2738 if (mEffectChains[i]->sessionId() < session) {
2739 break;
2740 }
2741 }
2742 mEffectChains.insertAt(chain, i);
2743 checkSuspendOnAddEffectChain_l(chain);
2744
2745 return NO_ERROR;
2746}
2747
2748size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2749{
Glenn Kastend848eb42016-03-08 13:42:11 -08002750 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002751
2752 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2753
2754 for (size_t i = 0; i < mEffectChains.size(); i++) {
2755 if (chain == mEffectChains[i]) {
2756 mEffectChains.removeAt(i);
2757 // detach all active tracks from the chain
2758 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2759 sp<Track> track = mActiveTracks[i].promote();
2760 if (track == 0) {
2761 continue;
2762 }
2763 if (session == track->sessionId()) {
2764 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2765 chain.get(), session);
2766 chain->decActiveTrackCnt();
2767 }
2768 }
2769
2770 // detach all tracks with same session ID from this chain
2771 for (size_t i = 0; i < mTracks.size(); ++i) {
2772 sp<Track> track = mTracks[i];
2773 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002774 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002775 chain->decTrackCnt();
2776 }
2777 }
2778 break;
2779 }
2780 }
2781 return mEffectChains.size();
2782}
2783
2784status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002785 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002786{
2787 Mutex::Autolock _l(mLock);
2788 return attachAuxEffect_l(track, EffectId);
2789}
2790
2791status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002792 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
2794 status_t status = NO_ERROR;
2795
2796 if (EffectId == 0) {
2797 track->setAuxBuffer(0, NULL);
2798 } else {
2799 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2800 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2801 if (effect != 0) {
2802 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2803 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2804 } else {
2805 status = INVALID_OPERATION;
2806 }
2807 } else {
2808 status = BAD_VALUE;
2809 }
2810 }
2811 return status;
2812}
2813
2814void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2815{
2816 for (size_t i = 0; i < mTracks.size(); ++i) {
2817 sp<Track> track = mTracks[i];
2818 if (track->auxEffectId() == effectId) {
2819 attachAuxEffect_l(track, 0);
2820 }
2821 }
2822}
2823
2824bool AudioFlinger::PlaybackThread::threadLoop()
2825{
2826 Vector< sp<Track> > tracksToRemove;
2827
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002828 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002829 nsecs_t lastWriteFinished = -1; // time last server write completed
2830 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002831
2832 // MIXER
2833 nsecs_t lastWarning = 0;
2834
2835 // DUPLICATING
2836 // FIXME could this be made local to while loop?
2837 writeFrames = 0;
2838
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002839 int lastGeneration = 0;
2840
Eric Laurent81784c32012-11-19 14:55:58 -08002841 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002842 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002843
2844 if (mType == MIXER) {
2845 sleepTimeShift = 0;
2846 }
2847
2848 CpuStats cpuStats;
2849 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2850
2851 acquireWakeLock();
2852
Glenn Kasten9e58b552013-01-18 15:09:48 -08002853 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2854 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2855 // and then that string will be logged at the next convenient opportunity.
2856 const char *logString = NULL;
2857
Eric Laurent664539d2013-09-23 18:24:31 -07002858 checkSilentMode_l();
2859
Eric Laurent81784c32012-11-19 14:55:58 -08002860 while (!exitPending())
2861 {
2862 cpuStats.sample(myName);
2863
2864 Vector< sp<EffectChain> > effectChains;
2865
Eric Laurent81784c32012-11-19 14:55:58 -08002866 { // scope for mLock
2867
2868 Mutex::Autolock _l(mLock);
2869
Eric Laurent021cf962014-05-13 10:18:14 -07002870 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002871
Glenn Kasten9e58b552013-01-18 15:09:48 -08002872 if (logString != NULL) {
2873 mNBLogWriter->logTimestamp();
2874 mNBLogWriter->log(logString);
2875 logString = NULL;
2876 }
2877
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002878 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002879 // and associate with the sink frames written out. We need
2880 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002881 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002882 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002883 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002884 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002885 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002886 ExtendedTimestamp timestamp; // use private copy to fetch
2887 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002888
2889 // We keep track of the last valid kernel position in case we are in underrun
2890 // and the normal mixer period is the same as the fast mixer period, or there
2891 // is some error from the HAL.
2892 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2893 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2894 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2895 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2896 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2897
2898 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2899 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2900 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2901 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002902 }
2903
2904 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2905 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002906 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002907 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002908 }
2909
Andy Hung818e7a32016-02-16 18:08:07 -08002910 // copy over kernel info
2911 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07002912 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
2913 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08002914 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2915 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002916 }
2917 // mFramesWritten for non-offloaded tracks are contiguous
2918 // even after standby() is called. This is useful for the track frame
2919 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07002920 bool serverLocationUpdate = false;
2921 if (mFramesWritten != lastFramesWritten) {
2922 serverLocationUpdate = true;
2923 lastFramesWritten = mFramesWritten;
2924 }
2925 // Only update timestamps if there is a meaningful change.
2926 // Either the kernel timestamp must be valid or we have written something.
2927 if (kernelLocationUpdate || serverLocationUpdate) {
2928 if (serverLocationUpdate) {
2929 // use the time before we called the HAL write - it is a bit more accurate
2930 // to when the server last read data than the current time here.
2931 //
2932 // If we haven't written anything, mLastWriteTime will be -1
2933 // and we use systemTime().
2934 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2935 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
2936 ? systemTime() : mLastWriteTime;
2937 }
2938 const size_t size = mActiveTracks.size();
2939 for (size_t i = 0; i < size; ++i) {
2940 sp<Track> t = mActiveTracks[i].promote();
2941 if (t != 0 && !t->isFastTrack()) {
2942 t->updateTrackFrameInfo(
2943 t->mAudioTrackServerProxy->framesReleased(),
2944 mFramesWritten,
2945 mTimestamp);
2946 }
Andy Hunge10393e2015-06-12 13:59:33 -07002947 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002948 }
2949
Eric Laurent81784c32012-11-19 14:55:58 -08002950 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002951 if (mSignalPending) {
2952 // A signal was raised while we were unlocked
2953 mSignalPending = false;
2954 } else if (waitingAsyncCallback_l()) {
2955 if (exitPending()) {
2956 break;
2957 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002958 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07002959 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07002960 releaseWakeLock_l();
2961 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07002962 mWakeLockUids.clear();
2963 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07002964 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002965 ALOGV("wait async completion");
2966 mWaitWorkCV.wait(mLock);
2967 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002968 if (released) {
2969 acquireWakeLock_l();
2970 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002971 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2972 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002973
2974 continue;
2975 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002976 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002977 isSuspended()) {
2978 // put audio hardware into standby after short delay
2979 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002980
2981 threadLoop_standby();
2982
2983 mStandby = true;
2984 }
2985
2986 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2987 // we're about to wait, flush the binder command buffer
2988 IPCThreadState::self()->flushCommands();
2989
2990 clearOutputTracks();
2991
2992 if (exitPending()) {
2993 break;
2994 }
2995
2996 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002997 mWakeLockUids.clear();
2998 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002999 // wait until we have something to do...
3000 ALOGV("%s going to sleep", myName.string());
3001 mWaitWorkCV.wait(mLock);
3002 ALOGV("%s waking up", myName.string());
3003 acquireWakeLock_l();
3004
3005 mMixerStatus = MIXER_IDLE;
3006 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3007 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003008 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003009 checkSilentMode_l();
3010
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003011 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3012 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003013 if (mType == MIXER) {
3014 sleepTimeShift = 0;
3015 }
3016
3017 continue;
3018 }
3019 }
Eric Laurent81784c32012-11-19 14:55:58 -08003020 // mMixerStatusIgnoringFastTracks is also updated internally
3021 mMixerStatus = prepareTracks_l(&tracksToRemove);
3022
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003023 // compare with previously applied list
3024 if (lastGeneration != mActiveTracksGeneration) {
3025 // update wakelock
3026 updateWakeLockUids_l(mWakeLockUids);
3027 lastGeneration = mActiveTracksGeneration;
3028 }
3029
Eric Laurent81784c32012-11-19 14:55:58 -08003030 // prevent any changes in effect chain list and in each effect chain
3031 // during mixing and effect process as the audio buffers could be deleted
3032 // or modified if an effect is created or deleted
3033 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003034 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003035
Eric Laurentbfb1b832013-01-07 09:53:42 -08003036 if (mBytesRemaining == 0) {
3037 mCurrentWriteLength = 0;
3038 if (mMixerStatus == MIXER_TRACKS_READY) {
3039 // threadLoop_mix() sets mCurrentWriteLength
3040 threadLoop_mix();
3041 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3042 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003043 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003044 // must be written to HAL
3045 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003046 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003047 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003048 }
3049 }
Andy Hung98ef9782014-03-04 14:46:50 -08003050 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003051 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003052 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3053 // or mSinkBuffer (if there are no effects).
3054 //
3055 // This is done pre-effects computation; if effects change to
3056 // support higher precision, this needs to move.
3057 //
3058 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003059 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003060 if (mMixerBufferValid) {
3061 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3062 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3063
Andy Hung2ddee192015-12-18 17:34:44 -08003064 // mono blend occurs for mixer threads only (not direct or offloaded)
3065 // and is handled here if we're going directly to the sink.
3066 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003067 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3068 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003069 }
3070
Andy Hung98ef9782014-03-04 14:46:50 -08003071 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3072 mNormalFrameCount * mChannelCount);
3073 }
3074
Eric Laurentbfb1b832013-01-07 09:53:42 -08003075 mBytesRemaining = mCurrentWriteLength;
3076 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003077 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3078 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3079 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3080 mBytesWritten += mBytesRemaining;
3081 mFramesWritten += framesRemaining;
3082 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003083 mBytesRemaining = 0;
3084 }
Eric Laurent81784c32012-11-19 14:55:58 -08003085
Eric Laurentbfb1b832013-01-07 09:53:42 -08003086 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003087 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003088 for (size_t i = 0; i < effectChains.size(); i ++) {
3089 effectChains[i]->process_l();
3090 }
Eric Laurent81784c32012-11-19 14:55:58 -08003091 }
3092 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003093 // Process effect chains for offloaded thread even if no audio
3094 // was read from audio track: process only updates effect state
3095 // and thus does have to be synchronized with audio writes but may have
3096 // to be called while waiting for async write callback
3097 if (mType == OFFLOAD) {
3098 for (size_t i = 0; i < effectChains.size(); i ++) {
3099 effectChains[i]->process_l();
3100 }
3101 }
Eric Laurent81784c32012-11-19 14:55:58 -08003102
Andy Hung98ef9782014-03-04 14:46:50 -08003103 // Only if the Effects buffer is enabled and there is data in the
3104 // Effects buffer (buffer valid), we need to
3105 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003106 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003107 if (mEffectBufferValid) {
3108 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003109
3110 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003111 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3112 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003113 }
3114
Andy Hung98ef9782014-03-04 14:46:50 -08003115 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3116 mNormalFrameCount * mChannelCount);
3117 }
3118
Eric Laurent81784c32012-11-19 14:55:58 -08003119 // enable changes in effect chain
3120 unlockEffectChains(effectChains);
3121
Eric Laurentbfb1b832013-01-07 09:53:42 -08003122 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003123 // mSleepTimeUs == 0 means we must write to audio hardware
3124 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003125 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003126 // We save lastWriteFinished here, as previousLastWriteFinished,
3127 // for throttling. On thread start, previousLastWriteFinished will be
3128 // set to -1, which properly results in no throttling after the first write.
3129 nsecs_t previousLastWriteFinished = lastWriteFinished;
3130 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003131 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003132 // FIXME rewrite to reduce number of system calls
3133 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003134 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003135 lastWriteFinished = systemTime();
3136 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003137 if (ret < 0) {
3138 mBytesRemaining = 0;
3139 } else {
3140 mBytesWritten += ret;
3141 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003142 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003143 }
3144 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3145 (mMixerStatus == MIXER_DRAIN_ALL)) {
3146 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003147 }
Andy Hung08fb1742015-05-31 23:22:10 -07003148 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003149 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003150 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003151 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003152 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003153 ATRACE_NAME("underrun");
3154 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003155 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003156 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003157 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003158 }
Andy Hung08fb1742015-05-31 23:22:10 -07003159
3160 if (mThreadThrottle
3161 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3162 && ret > 0) { // we wrote something
3163 // Limit MixerThread data processing to no more than twice the
3164 // expected processing rate.
3165 //
3166 // This helps prevent underruns with NuPlayer and other applications
3167 // which may set up buffers that are close to the minimum size, or use
3168 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3169 //
3170 // The throttle smooths out sudden large data drains from the device,
3171 // e.g. when it comes out of standby, which often causes problems with
3172 // (1) mixer threads without a fast mixer (which has its own warm-up)
3173 // (2) minimum buffer sized tracks (even if the track is full,
3174 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003175 //
3176 // Total time spent in last processing cycle equals time spent in
3177 // 1. threadLoop_write, as well as time spent in
3178 // 2. threadLoop_mix (significant for heavy mixing, especially
3179 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003180
Andy Hung69488c42016-05-16 18:43:33 -07003181 // it's OK if deltaMs is an overestimate.
3182 const int32_t deltaMs =
3183 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003184 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3185 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3186 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003187 // notify of throttle start on verbose log
3188 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3189 "mixer(%p) throttle begin:"
3190 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003191 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003192 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003193 // Throttle must be attributed to the previous mixer loop's write time
3194 // to allow back-to-back throttling.
3195 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003196 } else {
3197 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3198 if (diff > 0) {
3199 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003200 // but prevent spamming for bluetooth
3201 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3202 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003203 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3204 }
Andy Hung08fb1742015-05-31 23:22:10 -07003205 }
3206 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003207 }
Eric Laurent81784c32012-11-19 14:55:58 -08003208
Eric Laurentbfb1b832013-01-07 09:53:42 -08003209 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003210 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003211 Mutex::Autolock _l(mLock);
3212 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3213 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003214 }
Glenn Kastene7754022014-10-31 12:11:26 -07003215 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003216 }
Eric Laurent81784c32012-11-19 14:55:58 -08003217 }
3218
3219 // Finally let go of removed track(s), without the lock held
3220 // since we can't guarantee the destructors won't acquire that
3221 // same lock. This will also mutate and push a new fast mixer state.
3222 threadLoop_removeTracks(tracksToRemove);
3223 tracksToRemove.clear();
3224
3225 // FIXME I don't understand the need for this here;
3226 // it was in the original code but maybe the
3227 // assignment in saveOutputTracks() makes this unnecessary?
3228 clearOutputTracks();
3229
3230 // Effect chains will be actually deleted here if they were removed from
3231 // mEffectChains list during mixing or effects processing
3232 effectChains.clear();
3233
3234 // FIXME Note that the above .clear() is no longer necessary since effectChains
3235 // is now local to this block, but will keep it for now (at least until merge done).
3236 }
3237
Eric Laurentbfb1b832013-01-07 09:53:42 -08003238 threadLoop_exit();
3239
Eric Laurentcf817a22014-08-04 20:36:31 -07003240 if (!mStandby) {
3241 threadLoop_standby();
3242 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003243 }
3244
3245 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003246 mWakeLockUids.clear();
3247 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003248
3249 ALOGV("Thread %p type %d exiting", this, mType);
3250 return false;
3251}
3252
Eric Laurentbfb1b832013-01-07 09:53:42 -08003253// removeTracks_l() must be called with ThreadBase::mLock held
3254void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3255{
3256 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003257 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003258 for (size_t i=0 ; i<count ; i++) {
3259 const sp<Track>& track = tracksToRemove.itemAt(i);
3260 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003261 mWakeLockUids.remove(track->uid());
3262 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003263 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3264 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3265 if (chain != 0) {
3266 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3267 track->sessionId());
3268 chain->decActiveTrackCnt();
3269 }
3270 if (track->isTerminated()) {
3271 removeTrack_l(track);
3272 }
3273 }
3274 }
3275
3276}
Eric Laurent81784c32012-11-19 14:55:58 -08003277
Eric Laurentaccc1472013-09-20 09:36:34 -07003278status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3279{
3280 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003281 ExtendedTimestamp ets;
3282 status_t status = mNormalSink->getTimestamp(ets);
3283 if (status == NO_ERROR) {
3284 status = ets.getBestTimestamp(&timestamp);
3285 }
3286 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003287 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003288 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003289 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003290 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003291 timestamp.mPosition = (uint32_t)position64;
3292 return NO_ERROR;
3293 }
3294 }
3295 return INVALID_OPERATION;
3296}
Eric Laurent1c333e22014-05-20 10:48:17 -07003297
Eric Laurent054d9d32015-04-24 08:48:48 -07003298status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3299 audio_patch_handle_t *handle)
3300{
Andy Hungf60abce2016-08-26 11:37:54 -07003301 status_t status;
3302 if (property_get_bool("af.patch_park", false /* default_value */)) {
3303 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3304 // or if HAL does not properly lock against access.
3305 AutoPark<FastMixer> park(mFastMixer);
3306 status = PlaybackThread::createAudioPatch_l(patch, handle);
3307 } else {
3308 status = PlaybackThread::createAudioPatch_l(patch, handle);
3309 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003310 return status;
3311}
3312
Eric Laurent1c333e22014-05-20 10:48:17 -07003313status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3314 audio_patch_handle_t *handle)
3315{
3316 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003317
3318 // store new device and send to effects
3319 audio_devices_t type = AUDIO_DEVICE_NONE;
3320 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3321 type |= patch->sinks[i].ext.device.type;
3322 }
3323
3324#ifdef ADD_BATTERY_DATA
3325 // when changing the audio output device, call addBatteryData to notify
3326 // the change
3327 if (mOutDevice != type) {
3328 uint32_t params = 0;
3329 // check whether speaker is on
3330 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3331 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003332 }
3333
Eric Laurent054d9d32015-04-24 08:48:48 -07003334 audio_devices_t deviceWithoutSpeaker
3335 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3336 // check if any other device (except speaker) is on
3337 if (type & deviceWithoutSpeaker) {
3338 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3339 }
3340
3341 if (params != 0) {
3342 addBatteryData(params);
3343 }
3344 }
3345#endif
3346
3347 for (size_t i = 0; i < mEffectChains.size(); i++) {
3348 mEffectChains[i]->setDevice_l(type);
3349 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003350
3351 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3352 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3353 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003354 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003355 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003356
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003357 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003358 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3359 status = hwDevice->createAudioPatch(patch->num_sources,
3360 patch->sources,
3361 patch->num_sinks,
3362 patch->sinks,
3363 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003364 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003365 char *address;
3366 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3367 //FIXME: we only support address on first sink with HAL version < 3.0
3368 address = audio_device_address_to_parameter(
3369 patch->sinks[0].ext.device.type,
3370 patch->sinks[0].ext.device.address);
3371 } else {
3372 address = (char *)calloc(1, 1);
3373 }
3374 AudioParameter param = AudioParameter(String8(address));
3375 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003376 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003377 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003378 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003379 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003380 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003381 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003382 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3383 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003384 return status;
3385}
3386
Eric Laurent054d9d32015-04-24 08:48:48 -07003387status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3388{
Andy Hungf60abce2016-08-26 11:37:54 -07003389 status_t status;
3390 if (property_get_bool("af.patch_park", false /* default_value */)) {
3391 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3392 // or if HAL does not properly lock against access.
3393 AutoPark<FastMixer> park(mFastMixer);
3394 status = PlaybackThread::releaseAudioPatch_l(handle);
3395 } else {
3396 status = PlaybackThread::releaseAudioPatch_l(handle);
3397 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003398 return status;
3399}
3400
Eric Laurent1c333e22014-05-20 10:48:17 -07003401status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3402{
3403 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003404
3405 mOutDevice = AUDIO_DEVICE_NONE;
3406
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003407 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003408 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3409 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003410 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003411 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003412 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003413 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003414 }
3415 return status;
3416}
3417
Eric Laurent83b88082014-06-20 18:31:16 -07003418void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3419{
3420 Mutex::Autolock _l(mLock);
3421 mTracks.add(track);
3422}
3423
3424void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3425{
3426 Mutex::Autolock _l(mLock);
3427 destroyTrack_l(track);
3428}
3429
3430void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3431{
3432 ThreadBase::getAudioPortConfig(config);
3433 config->role = AUDIO_PORT_ROLE_SOURCE;
3434 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3435 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3436}
3437
Eric Laurent81784c32012-11-19 14:55:58 -08003438// ----------------------------------------------------------------------------
3439
3440AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003441 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3442 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003443 // mAudioMixer below
3444 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003445 mFastMixerFutex(0),
3446 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003447 // mOutputSink below
3448 // mPipeSink below
3449 // mNormalSink below
3450{
3451 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003452 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3453 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003454 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3455 mNormalFrameCount);
3456 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3457
Andy Hungfbfc3952015-01-15 13:33:51 -08003458 if (type == DUPLICATING) {
3459 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3460 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3461 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3462 return;
3463 }
Eric Laurent81784c32012-11-19 14:55:58 -08003464 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003465 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003466 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003467 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003468#if !LOG_NDEBUG
3469 ssize_t index =
3470#else
3471 (void)
3472#endif
3473 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003474 ALOG_ASSERT(index == 0);
3475
3476 // initialize fast mixer depending on configuration
3477 bool initFastMixer;
3478 switch (kUseFastMixer) {
3479 case FastMixer_Never:
3480 initFastMixer = false;
3481 break;
3482 case FastMixer_Always:
3483 initFastMixer = true;
3484 break;
3485 case FastMixer_Static:
3486 case FastMixer_Dynamic:
3487 initFastMixer = mFrameCount < mNormalFrameCount;
3488 break;
3489 }
3490 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003491 audio_format_t fastMixerFormat;
3492 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3493 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3494 } else {
3495 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3496 }
3497 if (mFormat != fastMixerFormat) {
3498 // change our Sink format to accept our intermediate precision
3499 mFormat = fastMixerFormat;
3500 free(mSinkBuffer);
3501 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3502 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3503 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3504 }
Eric Laurent81784c32012-11-19 14:55:58 -08003505
3506 // create a MonoPipe to connect our submix to FastMixer
3507 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003508#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003509 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003510#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003511 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003512 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003513 format.mFormat = fastMixerFormat;
3514 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3515
Eric Laurent81784c32012-11-19 14:55:58 -08003516 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3517 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3518 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3519 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3520 const NBAIO_Format offers[1] = {format};
3521 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003522#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003523 ssize_t index =
3524#else
3525 (void)
3526#endif
3527 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003528 ALOG_ASSERT(index == 0);
3529 monoPipe->setAvgFrames((mScreenState & 1) ?
3530 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3531 mPipeSink = monoPipe;
3532
Glenn Kasten46909e72013-02-26 09:20:22 -08003533#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003534 if (mTeeSinkOutputEnabled) {
3535 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003536 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3537 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003538 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003539 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003540 ALOG_ASSERT(index == 0);
3541 mTeeSink = teeSink;
3542 PipeReader *teeSource = new PipeReader(*teeSink);
3543 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003544 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003545 ALOG_ASSERT(index == 0);
3546 mTeeSource = teeSource;
3547 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003548#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003549
3550 // create fast mixer and configure it initially with just one fast track for our submix
3551 mFastMixer = new FastMixer();
3552 FastMixerStateQueue *sq = mFastMixer->sq();
3553#ifdef STATE_QUEUE_DUMP
3554 sq->setObserverDump(&mStateQueueObserverDump);
3555 sq->setMutatorDump(&mStateQueueMutatorDump);
3556#endif
3557 FastMixerState *state = sq->begin();
3558 FastTrack *fastTrack = &state->mFastTracks[0];
3559 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3560 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3561 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003562 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3563 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003564 fastTrack->mGeneration++;
3565 state->mFastTracksGen++;
3566 state->mTrackMask = 1;
3567 // fast mixer will use the HAL output sink
3568 state->mOutputSink = mOutputSink.get();
3569 state->mOutputSinkGen++;
3570 state->mFrameCount = mFrameCount;
3571 state->mCommand = FastMixerState::COLD_IDLE;
3572 // already done in constructor initialization list
3573 //mFastMixerFutex = 0;
3574 state->mColdFutexAddr = &mFastMixerFutex;
3575 state->mColdGen++;
3576 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003577#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003578 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003579#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003580 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3581 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003582 sq->end();
3583 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3584
3585 // start the fast mixer
3586 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3587 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003588 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003589
3590#ifdef AUDIO_WATCHDOG
3591 // create and start the watchdog
3592 mAudioWatchdog = new AudioWatchdog();
3593 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3594 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3595 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003596 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003597#endif
3598
Eric Laurent81784c32012-11-19 14:55:58 -08003599 }
3600
3601 switch (kUseFastMixer) {
3602 case FastMixer_Never:
3603 case FastMixer_Dynamic:
3604 mNormalSink = mOutputSink;
3605 break;
3606 case FastMixer_Always:
3607 mNormalSink = mPipeSink;
3608 break;
3609 case FastMixer_Static:
3610 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3611 break;
3612 }
3613}
3614
3615AudioFlinger::MixerThread::~MixerThread()
3616{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003617 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003618 FastMixerStateQueue *sq = mFastMixer->sq();
3619 FastMixerState *state = sq->begin();
3620 if (state->mCommand == FastMixerState::COLD_IDLE) {
3621 int32_t old = android_atomic_inc(&mFastMixerFutex);
3622 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003623 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003624 }
3625 }
3626 state->mCommand = FastMixerState::EXIT;
3627 sq->end();
3628 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3629 mFastMixer->join();
3630 // Though the fast mixer thread has exited, it's state queue is still valid.
3631 // We'll use that extract the final state which contains one remaining fast track
3632 // corresponding to our sub-mix.
3633 state = sq->begin();
3634 ALOG_ASSERT(state->mTrackMask == 1);
3635 FastTrack *fastTrack = &state->mFastTracks[0];
3636 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3637 delete fastTrack->mBufferProvider;
3638 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003639 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003640#ifdef AUDIO_WATCHDOG
3641 if (mAudioWatchdog != 0) {
3642 mAudioWatchdog->requestExit();
3643 mAudioWatchdog->requestExitAndWait();
3644 mAudioWatchdog.clear();
3645 }
3646#endif
3647 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003648 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003649 delete mAudioMixer;
3650}
3651
3652
3653uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3654{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003655 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003656 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3657 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3658 }
3659 return latency;
3660}
3661
3662
3663void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3664{
3665 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3666}
3667
Eric Laurentbfb1b832013-01-07 09:53:42 -08003668ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003669{
3670 // FIXME we should only do one push per cycle; confirm this is true
3671 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003672 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003673 FastMixerStateQueue *sq = mFastMixer->sq();
3674 FastMixerState *state = sq->begin();
3675 if (state->mCommand != FastMixerState::MIX_WRITE &&
3676 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3677 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003678
3679 // FIXME workaround for first HAL write being CPU bound on some devices
3680 ATRACE_BEGIN("write");
3681 mOutput->write((char *)mSinkBuffer, 0);
3682 ATRACE_END();
3683
Eric Laurent81784c32012-11-19 14:55:58 -08003684 int32_t old = android_atomic_inc(&mFastMixerFutex);
3685 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003686 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003687 }
3688#ifdef AUDIO_WATCHDOG
3689 if (mAudioWatchdog != 0) {
3690 mAudioWatchdog->resume();
3691 }
3692#endif
3693 }
3694 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003695#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003696 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003697 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003698#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003699 sq->end();
3700 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3701 if (kUseFastMixer == FastMixer_Dynamic) {
3702 mNormalSink = mPipeSink;
3703 }
3704 } else {
3705 sq->end(false /*didModify*/);
3706 }
3707 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003708 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003709}
3710
3711void AudioFlinger::MixerThread::threadLoop_standby()
3712{
3713 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003714 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003715 FastMixerStateQueue *sq = mFastMixer->sq();
3716 FastMixerState *state = sq->begin();
3717 if (!(state->mCommand & FastMixerState::IDLE)) {
3718 state->mCommand = FastMixerState::COLD_IDLE;
3719 state->mColdFutexAddr = &mFastMixerFutex;
3720 state->mColdGen++;
3721 mFastMixerFutex = 0;
3722 sq->end();
3723 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3724 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3725 if (kUseFastMixer == FastMixer_Dynamic) {
3726 mNormalSink = mOutputSink;
3727 }
3728#ifdef AUDIO_WATCHDOG
3729 if (mAudioWatchdog != 0) {
3730 mAudioWatchdog->pause();
3731 }
3732#endif
3733 } else {
3734 sq->end(false /*didModify*/);
3735 }
3736 }
3737 PlaybackThread::threadLoop_standby();
3738}
3739
Eric Laurentbfb1b832013-01-07 09:53:42 -08003740bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3741{
3742 return false;
3743}
3744
3745bool AudioFlinger::PlaybackThread::shouldStandby_l()
3746{
3747 return !mStandby;
3748}
3749
3750bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3751{
3752 Mutex::Autolock _l(mLock);
3753 return waitingAsyncCallback_l();
3754}
3755
Eric Laurent81784c32012-11-19 14:55:58 -08003756// shared by MIXER and DIRECT, overridden by DUPLICATING
3757void AudioFlinger::PlaybackThread::threadLoop_standby()
3758{
3759 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003760 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003761 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003762 // discard any pending drain or write ack by incrementing sequence
3763 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3764 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003765 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003766 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3767 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003768 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003769 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003770}
3771
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003772void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3773{
3774 ALOGV("signal playback thread");
3775 broadcast_l();
3776}
3777
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003778void AudioFlinger::PlaybackThread::onAsyncError()
3779{
3780 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3781 invalidateTracks((audio_stream_type_t)i);
3782 }
3783}
3784
Eric Laurent81784c32012-11-19 14:55:58 -08003785void AudioFlinger::MixerThread::threadLoop_mix()
3786{
Eric Laurent81784c32012-11-19 14:55:58 -08003787 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003788 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003789 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003790 // increase sleep time progressively when application underrun condition clears.
3791 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3792 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3793 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003794 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003795 sleepTimeShift--;
3796 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003797 mSleepTimeUs = 0;
3798 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003799 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003800
Eric Laurent81784c32012-11-19 14:55:58 -08003801}
3802
3803void AudioFlinger::MixerThread::threadLoop_sleepTime()
3804{
3805 // If no tracks are ready, sleep once for the duration of an output
3806 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003807 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003808 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003809 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3810 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3811 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003812 }
3813 // reduce sleep time in case of consecutive application underruns to avoid
3814 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3815 // duration we would end up writing less data than needed by the audio HAL if
3816 // the condition persists.
3817 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3818 sleepTimeShift++;
3819 }
3820 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003821 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003822 }
3823 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003824 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3825 // before effects processing or output.
3826 if (mMixerBufferValid) {
3827 memset(mMixerBuffer, 0, mMixerBufferSize);
3828 } else {
3829 memset(mSinkBuffer, 0, mSinkBufferSize);
3830 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003831 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003832 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3833 "anticipated start");
3834 }
3835 // TODO add standby time extension fct of effect tail
3836}
3837
3838// prepareTracks_l() must be called with ThreadBase::mLock held
3839AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3840 Vector< sp<Track> > *tracksToRemove)
3841{
3842
3843 mixer_state mixerStatus = MIXER_IDLE;
3844 // find out which tracks need to be processed
3845 size_t count = mActiveTracks.size();
3846 size_t mixedTracks = 0;
3847 size_t tracksWithEffect = 0;
3848 // counts only _active_ fast tracks
3849 size_t fastTracks = 0;
3850 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3851
3852 float masterVolume = mMasterVolume;
3853 bool masterMute = mMasterMute;
3854
3855 if (masterMute) {
3856 masterVolume = 0;
3857 }
3858 // Delegate master volume control to effect in output mix effect chain if needed
3859 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3860 if (chain != 0) {
3861 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3862 chain->setVolume_l(&v, &v);
3863 masterVolume = (float)((v + (1 << 23)) >> 24);
3864 chain.clear();
3865 }
3866
3867 // prepare a new state to push
3868 FastMixerStateQueue *sq = NULL;
3869 FastMixerState *state = NULL;
3870 bool didModify = false;
3871 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003872 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003873 sq = mFastMixer->sq();
3874 state = sq->begin();
3875 }
3876
Andy Hung69aed5f2014-02-25 17:24:40 -08003877 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003878 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003879
Eric Laurent81784c32012-11-19 14:55:58 -08003880 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003881 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003882 if (t == 0) {
3883 continue;
3884 }
3885
3886 // this const just means the local variable doesn't change
3887 Track* const track = t.get();
3888
3889 // process fast tracks
3890 if (track->isFastTrack()) {
3891
3892 // It's theoretically possible (though unlikely) for a fast track to be created
3893 // and then removed within the same normal mix cycle. This is not a problem, as
3894 // the track never becomes active so it's fast mixer slot is never touched.
3895 // The converse, of removing an (active) track and then creating a new track
3896 // at the identical fast mixer slot within the same normal mix cycle,
3897 // is impossible because the slot isn't marked available until the end of each cycle.
3898 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003899 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003900 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3901 FastTrack *fastTrack = &state->mFastTracks[j];
3902
3903 // Determine whether the track is currently in underrun condition,
3904 // and whether it had a recent underrun.
3905 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3906 FastTrackUnderruns underruns = ftDump->mUnderruns;
3907 uint32_t recentFull = (underruns.mBitFields.mFull -
3908 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3909 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3910 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3911 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3912 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3913 uint32_t recentUnderruns = recentPartial + recentEmpty;
3914 track->mObservedUnderruns = underruns;
3915 // don't count underruns that occur while stopping or pausing
3916 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003917 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3918 recentUnderruns > 0) {
3919 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3920 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003921 } else {
3922 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003923 }
3924
3925 // This is similar to the state machine for normal tracks,
3926 // with a few modifications for fast tracks.
3927 bool isActive = true;
3928 switch (track->mState) {
3929 case TrackBase::STOPPING_1:
3930 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003931 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003932 track->mState = TrackBase::STOPPING_2;
3933 }
3934 break;
3935 case TrackBase::PAUSING:
3936 // ramp down is not yet implemented
3937 track->setPaused();
3938 break;
3939 case TrackBase::RESUMING:
3940 // ramp up is not yet implemented
3941 track->mState = TrackBase::ACTIVE;
3942 break;
3943 case TrackBase::ACTIVE:
3944 if (recentFull > 0 || recentPartial > 0) {
3945 // track has provided at least some frames recently: reset retry count
3946 track->mRetryCount = kMaxTrackRetries;
3947 }
3948 if (recentUnderruns == 0) {
3949 // no recent underruns: stay active
3950 break;
3951 }
3952 // there has recently been an underrun of some kind
3953 if (track->sharedBuffer() == 0) {
3954 // were any of the recent underruns "empty" (no frames available)?
3955 if (recentEmpty == 0) {
3956 // no, then ignore the partial underruns as they are allowed indefinitely
3957 break;
3958 }
3959 // there has recently been an "empty" underrun: decrement the retry counter
3960 if (--(track->mRetryCount) > 0) {
3961 break;
3962 }
3963 // indicate to client process that the track was disabled because of underrun;
3964 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003965 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003966 // remove from active list, but state remains ACTIVE [confusing but true]
3967 isActive = false;
3968 break;
3969 }
3970 // fall through
3971 case TrackBase::STOPPING_2:
3972 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003973 case TrackBase::STOPPED:
3974 case TrackBase::FLUSHED: // flush() while active
3975 // Check for presentation complete if track is inactive
3976 // We have consumed all the buffers of this track.
3977 // This would be incomplete if we auto-paused on underrun
3978 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003979 uint32_t latency = 0;
3980 status_t result = mOutput->stream->getLatency(&latency);
3981 ALOGE_IF(result != OK,
3982 "Error when retrieving output stream latency: %d", result);
3983 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003984 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003985 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3986 // track stays in active list until presentation is complete
3987 break;
3988 }
3989 }
3990 if (track->isStopping_2()) {
3991 track->mState = TrackBase::STOPPED;
3992 }
3993 if (track->isStopped()) {
3994 // Can't reset directly, as fast mixer is still polling this track
3995 // track->reset();
3996 // So instead mark this track as needing to be reset after push with ack
3997 resetMask |= 1 << i;
3998 }
3999 isActive = false;
4000 break;
4001 case TrackBase::IDLE:
4002 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004003 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004004 }
4005
4006 if (isActive) {
4007 // was it previously inactive?
4008 if (!(state->mTrackMask & (1 << j))) {
4009 ExtendedAudioBufferProvider *eabp = track;
4010 VolumeProvider *vp = track;
4011 fastTrack->mBufferProvider = eabp;
4012 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004013 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004014 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004015 fastTrack->mGeneration++;
4016 state->mTrackMask |= 1 << j;
4017 didModify = true;
4018 // no acknowledgement required for newly active tracks
4019 }
4020 // cache the combined master volume and stream type volume for fast mixer; this
4021 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004022 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004023 ++fastTracks;
4024 } else {
4025 // was it previously active?
4026 if (state->mTrackMask & (1 << j)) {
4027 fastTrack->mBufferProvider = NULL;
4028 fastTrack->mGeneration++;
4029 state->mTrackMask &= ~(1 << j);
4030 didModify = true;
4031 // If any fast tracks were removed, we must wait for acknowledgement
4032 // because we're about to decrement the last sp<> on those tracks.
4033 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4034 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004035 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4036 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4037 j, track->mState, state->mTrackMask, recentUnderruns,
4038 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004039 }
4040 tracksToRemove->add(track);
4041 // Avoids a misleading display in dumpsys
4042 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4043 }
4044 continue;
4045 }
4046
4047 { // local variable scope to avoid goto warning
4048
4049 audio_track_cblk_t* cblk = track->cblk();
4050
4051 // The first time a track is added we wait
4052 // for all its buffers to be filled before processing it
4053 int name = track->name();
4054 // make sure that we have enough frames to mix one full buffer.
4055 // enforce this condition only once to enable draining the buffer in case the client
4056 // app does not call stop() and relies on underrun to stop:
4057 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4058 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004059 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004060 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004061 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004062
4063 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004064 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004065 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4066 // add frames already consumed but not yet released by the resampler
4067 // because mAudioTrackServerProxy->framesReady() will include these frames
4068 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4069
Eric Laurent81784c32012-11-19 14:55:58 -08004070 uint32_t minFrames = 1;
4071 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4072 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004073 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004074 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004075
4076 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004077 if (ATRACE_ENABLED()) {
4078 // I wish we had formatted trace names
4079 char traceName[16];
4080 strcpy(traceName, "nRdy");
4081 int name = track->name();
4082 if (AudioMixer::TRACK0 <= name &&
4083 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4084 name -= AudioMixer::TRACK0;
4085 traceName[4] = (name / 10) + '0';
4086 traceName[5] = (name % 10) + '0';
4087 } else {
4088 traceName[4] = '?';
4089 traceName[5] = '?';
4090 }
4091 traceName[6] = '\0';
4092 ATRACE_INT(traceName, framesReady);
4093 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004094 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004095 !track->isPaused() && !track->isTerminated())
4096 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004097 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004098
4099 mixedTracks++;
4100
Andy Hung69aed5f2014-02-25 17:24:40 -08004101 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4102 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004103 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004104 if (track->mainBuffer() != mSinkBuffer &&
4105 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004106 if (mEffectBufferEnabled) {
4107 mEffectBufferValid = true; // Later can set directly.
4108 }
Eric Laurent81784c32012-11-19 14:55:58 -08004109 chain = getEffectChain_l(track->sessionId());
4110 // Delegate volume control to effect in track effect chain if needed
4111 if (chain != 0) {
4112 tracksWithEffect++;
4113 } else {
4114 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4115 "session %d",
4116 name, track->sessionId());
4117 }
4118 }
4119
4120
4121 int param = AudioMixer::VOLUME;
4122 if (track->mFillingUpStatus == Track::FS_FILLED) {
4123 // no ramp for the first volume setting
4124 track->mFillingUpStatus = Track::FS_ACTIVE;
4125 if (track->mState == TrackBase::RESUMING) {
4126 track->mState = TrackBase::ACTIVE;
4127 param = AudioMixer::RAMP_VOLUME;
4128 }
4129 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004130 // FIXME should not make a decision based on mServer
4131 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004132 // If the track is stopped before the first frame was mixed,
4133 // do not apply ramp
4134 param = AudioMixer::RAMP_VOLUME;
4135 }
4136
4137 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004138 uint32_t vl, vr; // in U8.24 integer format
4139 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004140 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004141 vl = vr = 0;
4142 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004143 if (track->isPausing()) {
4144 track->setPaused();
4145 }
4146 } else {
4147
4148 // read original volumes with volume control
4149 float typeVolume = mStreamTypes[track->streamType()].volume;
4150 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004151 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004152 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004153 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4154 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004155 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004156 if (vlf > GAIN_FLOAT_UNITY) {
4157 ALOGV("Track left volume out of range: %.3g", vlf);
4158 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004159 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004160 if (vrf > GAIN_FLOAT_UNITY) {
4161 ALOGV("Track right volume out of range: %.3g", vrf);
4162 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004163 }
4164 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004165 vlf *= v;
4166 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004167 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004168 // then derive vl and vr as U8.24 versions for the effect chain
4169 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4170 vl = (uint32_t) (scaleto8_24 * vlf);
4171 vr = (uint32_t) (scaleto8_24 * vrf);
4172 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004173 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004174 // send level comes from shared memory and so may be corrupt
4175 if (sendLevel > MAX_GAIN_INT) {
4176 ALOGV("Track send level out of range: %04X", sendLevel);
4177 sendLevel = MAX_GAIN_INT;
4178 }
Andy Hung6be49402014-05-30 10:42:03 -07004179 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4180 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004181 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004182
Eric Laurent81784c32012-11-19 14:55:58 -08004183 // Delegate volume control to effect in track effect chain if needed
4184 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4185 // Do not ramp volume if volume is controlled by effect
4186 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004187 // Update remaining floating point volume levels
4188 vlf = (float)vl / (1 << 24);
4189 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004190 track->mHasVolumeController = true;
4191 } else {
4192 // force no volume ramp when volume controller was just disabled or removed
4193 // from effect chain to avoid volume spike
4194 if (track->mHasVolumeController) {
4195 param = AudioMixer::VOLUME;
4196 }
4197 track->mHasVolumeController = false;
4198 }
4199
Eric Laurent81784c32012-11-19 14:55:58 -08004200 // XXX: these things DON'T need to be done each time
4201 mAudioMixer->setBufferProvider(name, track);
4202 mAudioMixer->enable(name);
4203
Andy Hung6be49402014-05-30 10:42:03 -07004204 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4205 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4206 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004207 mAudioMixer->setParameter(
4208 name,
4209 AudioMixer::TRACK,
4210 AudioMixer::FORMAT, (void *)track->format());
4211 mAudioMixer->setParameter(
4212 name,
4213 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004214 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004215 mAudioMixer->setParameter(
4216 name,
4217 AudioMixer::TRACK,
4218 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004219 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004220 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004221 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004222 if (reqSampleRate == 0) {
4223 reqSampleRate = mSampleRate;
4224 } else if (reqSampleRate > maxSampleRate) {
4225 reqSampleRate = maxSampleRate;
4226 }
Eric Laurent81784c32012-11-19 14:55:58 -08004227 mAudioMixer->setParameter(
4228 name,
4229 AudioMixer::RESAMPLE,
4230 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004231 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004232
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004233 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004234 mAudioMixer->setParameter(
4235 name,
4236 AudioMixer::TIMESTRETCH,
4237 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004238 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004239
Andy Hung69aed5f2014-02-25 17:24:40 -08004240 /*
4241 * Select the appropriate output buffer for the track.
4242 *
Andy Hung98ef9782014-03-04 14:46:50 -08004243 * Tracks with effects go into their own effects chain buffer
4244 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004245 *
4246 * Other tracks can use mMixerBuffer for higher precision
4247 * channel accumulation. If this buffer is enabled
4248 * (mMixerBufferEnabled true), then selected tracks will accumulate
4249 * into it.
4250 *
4251 */
4252 if (mMixerBufferEnabled
4253 && (track->mainBuffer() == mSinkBuffer
4254 || track->mainBuffer() == mMixerBuffer)) {
4255 mAudioMixer->setParameter(
4256 name,
4257 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004258 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004259 mAudioMixer->setParameter(
4260 name,
4261 AudioMixer::TRACK,
4262 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4263 // TODO: override track->mainBuffer()?
4264 mMixerBufferValid = true;
4265 } else {
4266 mAudioMixer->setParameter(
4267 name,
4268 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004269 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004270 mAudioMixer->setParameter(
4271 name,
4272 AudioMixer::TRACK,
4273 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4274 }
Eric Laurent81784c32012-11-19 14:55:58 -08004275 mAudioMixer->setParameter(
4276 name,
4277 AudioMixer::TRACK,
4278 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4279
4280 // reset retry count
4281 track->mRetryCount = kMaxTrackRetries;
4282
4283 // If one track is ready, set the mixer ready if:
4284 // - the mixer was not ready during previous round OR
4285 // - no other track is not ready
4286 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4287 mixerStatus != MIXER_TRACKS_ENABLED) {
4288 mixerStatus = MIXER_TRACKS_READY;
4289 }
4290 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004291 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004292 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4293 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004294 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004295 } else {
4296 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004297 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004298
Eric Laurent81784c32012-11-19 14:55:58 -08004299 // clear effect chain input buffer if an active track underruns to avoid sending
4300 // previous audio buffer again to effects
4301 chain = getEffectChain_l(track->sessionId());
4302 if (chain != 0) {
4303 chain->clearInputBuffer();
4304 }
4305
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004306 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004307 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4308 track->isStopped() || track->isPaused()) {
4309 // We have consumed all the buffers of this track.
4310 // Remove it from the list of active tracks.
4311 // TODO: use actual buffer filling status instead of latency when available from
4312 // audio HAL
4313 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004314 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004315 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4316 if (track->isStopped()) {
4317 track->reset();
4318 }
4319 tracksToRemove->add(track);
4320 }
4321 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004322 // No buffers for this track. Give it a few chances to
4323 // fill a buffer, then remove it from active list.
4324 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004325 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004326 tracksToRemove->add(track);
4327 // indicate to client process that the track was disabled because of underrun;
4328 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004329 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004330 // If one track is not ready, mark the mixer also not ready if:
4331 // - the mixer was ready during previous round OR
4332 // - no other track is ready
4333 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4334 mixerStatus != MIXER_TRACKS_READY) {
4335 mixerStatus = MIXER_TRACKS_ENABLED;
4336 }
4337 }
4338 mAudioMixer->disable(name);
4339 }
4340
4341 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004342
4343 }
4344
4345 // Push the new FastMixer state if necessary
4346 bool pauseAudioWatchdog = false;
4347 if (didModify) {
4348 state->mFastTracksGen++;
4349 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4350 if (kUseFastMixer == FastMixer_Dynamic &&
4351 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4352 state->mCommand = FastMixerState::COLD_IDLE;
4353 state->mColdFutexAddr = &mFastMixerFutex;
4354 state->mColdGen++;
4355 mFastMixerFutex = 0;
4356 if (kUseFastMixer == FastMixer_Dynamic) {
4357 mNormalSink = mOutputSink;
4358 }
4359 // If we go into cold idle, need to wait for acknowledgement
4360 // so that fast mixer stops doing I/O.
4361 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4362 pauseAudioWatchdog = true;
4363 }
Eric Laurent81784c32012-11-19 14:55:58 -08004364 }
4365 if (sq != NULL) {
4366 sq->end(didModify);
4367 sq->push(block);
4368 }
4369#ifdef AUDIO_WATCHDOG
4370 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4371 mAudioWatchdog->pause();
4372 }
4373#endif
4374
4375 // Now perform the deferred reset on fast tracks that have stopped
4376 while (resetMask != 0) {
4377 size_t i = __builtin_ctz(resetMask);
4378 ALOG_ASSERT(i < count);
4379 resetMask &= ~(1 << i);
4380 sp<Track> t = mActiveTracks[i].promote();
4381 if (t == 0) {
4382 continue;
4383 }
4384 Track* track = t.get();
4385 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4386 track->reset();
4387 }
4388
4389 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004390 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004391
Eric Laurent97d547d2014-09-02 14:45:53 -07004392 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4393 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004394 }
4395
4396 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004397 // as long as there are effects we should clear the effects buffer, to avoid
4398 // passing a non-clean buffer to the effect chain
4399 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004400 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004401 // sink or mix buffer must be cleared if all tracks are connected to an
4402 // effect chain as in this case the mixer will not write to the sink or mix buffer
4403 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4405 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004406 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004407 if (mMixerBufferValid) {
4408 memset(mMixerBuffer, 0, mMixerBufferSize);
4409 // TODO: In testing, mSinkBuffer below need not be cleared because
4410 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4411 // after mixing.
4412 //
4413 // To enforce this guarantee:
4414 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4415 // (mixedTracks == 0 && fastTracks > 0))
4416 // must imply MIXER_TRACKS_READY.
4417 // Later, we may clear buffers regardless, and skip much of this logic.
4418 }
Andy Hung98ef9782014-03-04 14:46:50 -08004419 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004420 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004421 }
4422
4423 // if any fast tracks, then status is ready
4424 mMixerStatusIgnoringFastTracks = mixerStatus;
4425 if (fastTracks > 0) {
4426 mixerStatus = MIXER_TRACKS_READY;
4427 }
4428 return mixerStatus;
4429}
4430
Eric Laurentad7dd962016-09-22 12:38:37 -07004431// trackCountForUid_l() must be called with ThreadBase::mLock held
4432uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4433{
4434 uint32_t trackCount = 0;
4435 for (size_t i = 0; i < mTracks.size() ; i++) {
4436 if (mTracks[i]->uid() == (int)uid) {
4437 trackCount++;
4438 }
4439 }
4440 return trackCount;
4441}
4442
Eric Laurent81784c32012-11-19 14:55:58 -08004443// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004444int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004445 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004446{
Eric Laurentad7dd962016-09-22 12:38:37 -07004447 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4448 return -1;
4449 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004450 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004451}
4452
4453// deleteTrackName_l() must be called with ThreadBase::mLock held
4454void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4455{
4456 ALOGV("remove track (%d) and delete from mixer", name);
4457 mAudioMixer->deleteTrackName(name);
4458}
4459
Eric Laurent10351942014-05-08 18:49:52 -07004460// checkForNewParameter_l() must be called with ThreadBase::mLock held
4461bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4462 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004463{
Eric Laurent81784c32012-11-19 14:55:58 -08004464 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004465 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004466
Eric Laurent10351942014-05-08 18:49:52 -07004467 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004468
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004469 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004470
Eric Laurent10351942014-05-08 18:49:52 -07004471 AudioParameter param = AudioParameter(keyValuePair);
4472 int value;
4473 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4474 reconfig = true;
4475 }
4476 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004477 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004478 status = BAD_VALUE;
4479 } else {
4480 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004481 reconfig = true;
4482 }
Eric Laurent10351942014-05-08 18:49:52 -07004483 }
4484 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004485 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004486 status = BAD_VALUE;
4487 } else {
4488 // no need to save value, since it's constant
4489 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004490 }
Eric Laurent10351942014-05-08 18:49:52 -07004491 }
4492 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4493 // do not accept frame count changes if tracks are open as the track buffer
4494 // size depends on frame count and correct behavior would not be guaranteed
4495 // if frame count is changed after track creation
4496 if (!mTracks.isEmpty()) {
4497 status = INVALID_OPERATION;
4498 } else {
4499 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004500 }
Eric Laurent10351942014-05-08 18:49:52 -07004501 }
4502 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004503#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004504 // when changing the audio output device, call addBatteryData to notify
4505 // the change
4506 if (mOutDevice != value) {
4507 uint32_t params = 0;
4508 // check whether speaker is on
4509 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4510 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004511 }
Eric Laurent10351942014-05-08 18:49:52 -07004512
4513 audio_devices_t deviceWithoutSpeaker
4514 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4515 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004516 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004517 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4518 }
4519
4520 if (params != 0) {
4521 addBatteryData(params);
4522 }
4523 }
Eric Laurent81784c32012-11-19 14:55:58 -08004524#endif
4525
Eric Laurent10351942014-05-08 18:49:52 -07004526 // forward device change to effects that have requested to be
4527 // aware of attached audio device.
4528 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004529 a2dpDeviceChanged =
4530 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004531 mOutDevice = value;
4532 for (size_t i = 0; i < mEffectChains.size(); i++) {
4533 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004534 }
4535 }
Eric Laurent10351942014-05-08 18:49:52 -07004536 }
Eric Laurent81784c32012-11-19 14:55:58 -08004537
Eric Laurent10351942014-05-08 18:49:52 -07004538 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004539 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004540 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004541 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004542 mStandby = true;
4543 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004544 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004545 }
Eric Laurent10351942014-05-08 18:49:52 -07004546 if (status == NO_ERROR && reconfig) {
4547 readOutputParameters_l();
4548 delete mAudioMixer;
4549 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4550 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004551 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004552 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004553 if (name < 0) {
4554 break;
4555 }
4556 mTracks[i]->mName = name;
4557 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004558 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004559 }
Eric Laurent81784c32012-11-19 14:55:58 -08004560 }
4561
Eric Laurent42537be2016-01-08 17:16:42 -08004562 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004563}
4564
4565
4566void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4567{
Eric Laurent81784c32012-11-19 14:55:58 -08004568 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004569 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004570 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004571 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004572
4573 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004574 // while we are dumping it. It may be inconsistent, but it won't mutate!
4575 // This is a large object so we place it on the heap.
4576 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4577 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4578 copy->dump(fd);
4579 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004580
4581#ifdef STATE_QUEUE_DUMP
4582 // Similar for state queue
4583 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4584 observerCopy.dump(fd);
4585 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4586 mutatorCopy.dump(fd);
4587#endif
4588
Glenn Kasten46909e72013-02-26 09:20:22 -08004589#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004590 // Write the tee output to a .wav file
4591 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004592#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004593
4594#ifdef AUDIO_WATCHDOG
4595 if (mAudioWatchdog != 0) {
4596 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4597 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4598 wdCopy.dump(fd);
4599 }
4600#endif
4601}
4602
4603uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4604{
4605 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4606}
4607
4608uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4609{
4610 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4611}
4612
4613void AudioFlinger::MixerThread::cacheParameters_l()
4614{
4615 PlaybackThread::cacheParameters_l();
4616
4617 // FIXME: Relaxed timing because of a certain device that can't meet latency
4618 // Should be reduced to 2x after the vendor fixes the driver issue
4619 // increase threshold again due to low power audio mode. The way this warning
4620 // threshold is calculated and its usefulness should be reconsidered anyway.
4621 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4622}
4623
4624// ----------------------------------------------------------------------------
4625
4626AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004627 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4628 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004629 // mLeftVolFloat, mRightVolFloat
4630{
4631}
4632
Eric Laurentbfb1b832013-01-07 09:53:42 -08004633AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4634 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004635 ThreadBase::type_t type, bool systemReady)
4636 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004637 // mLeftVolFloat, mRightVolFloat
4638{
4639}
4640
Eric Laurent81784c32012-11-19 14:55:58 -08004641AudioFlinger::DirectOutputThread::~DirectOutputThread()
4642{
4643}
4644
Eric Laurentbfb1b832013-01-07 09:53:42 -08004645void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4646{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004647 float left, right;
4648
4649 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4650 left = right = 0;
4651 } else {
4652 float typeVolume = mStreamTypes[track->streamType()].volume;
4653 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004654 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004655 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4656 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4657 if (left > GAIN_FLOAT_UNITY) {
4658 left = GAIN_FLOAT_UNITY;
4659 }
4660 left *= v;
4661 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4662 if (right > GAIN_FLOAT_UNITY) {
4663 right = GAIN_FLOAT_UNITY;
4664 }
4665 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004666 }
4667
4668 if (lastTrack) {
4669 if (left != mLeftVolFloat || right != mRightVolFloat) {
4670 mLeftVolFloat = left;
4671 mRightVolFloat = right;
4672
4673 // Convert volumes from float to 8.24
4674 uint32_t vl = (uint32_t)(left * (1 << 24));
4675 uint32_t vr = (uint32_t)(right * (1 << 24));
4676
4677 // Delegate volume control to effect in track effect chain if needed
4678 // only one effect chain can be present on DirectOutputThread, so if
4679 // there is one, the track is connected to it
4680 if (!mEffectChains.isEmpty()) {
4681 mEffectChains[0]->setVolume_l(&vl, &vr);
4682 left = (float)vl / (1 << 24);
4683 right = (float)vr / (1 << 24);
4684 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004685 status_t result = mOutput->stream->setVolume(left, right);
4686 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004687 }
4688 }
4689}
4690
Phil Burk43b4dcc2015-06-09 16:53:44 -07004691void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4692{
4693 sp<Track> previousTrack = mPreviousTrack.promote();
4694 sp<Track> latestTrack = mLatestActiveTrack.promote();
4695
Eric Laurent0f0631e2015-07-06 18:01:25 -07004696 if (previousTrack != 0 && latestTrack != 0) {
4697 if (mType == DIRECT) {
4698 if (previousTrack.get() != latestTrack.get()) {
4699 mFlushPending = true;
4700 }
4701 } else /* mType == OFFLOAD */ {
4702 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4703 mFlushPending = true;
4704 }
4705 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004706 }
4707 PlaybackThread::onAddNewTrack_l();
4708}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004709
Eric Laurent81784c32012-11-19 14:55:58 -08004710AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4711 Vector< sp<Track> > *tracksToRemove
4712)
4713{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004714 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004715 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004716 bool doHwPause = false;
4717 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004718
4719 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004720 for (size_t i = 0; i < count; i++) {
4721 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004722 // The track died recently
4723 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004724 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004725 }
4726
Phil Burk43b4dcc2015-06-09 16:53:44 -07004727 if (t->isInvalid()) {
4728 ALOGW("An invalidated track shouldn't be in active list");
4729 tracksToRemove->add(t);
4730 continue;
4731 }
4732
Eric Laurent81784c32012-11-19 14:55:58 -08004733 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004734#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004735 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004736#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004737 // Only consider last track started for volume and mixer state control.
4738 // In theory an older track could underrun and restart after the new one starts
4739 // but as we only care about the transition phase between two tracks on a
4740 // direct output, it is not a problem to ignore the underrun case.
4741 sp<Track> l = mLatestActiveTrack.promote();
4742 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004743
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004744 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004745 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004746 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004747 doHwPause = true;
4748 mHwPaused = true;
4749 }
4750 tracksToRemove->add(track);
4751 } else if (track->isFlushPending()) {
4752 track->flushAck();
4753 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004754 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004755 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004756 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004757 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004758 if (last) {
4759 mLeftVolFloat = mRightVolFloat = -1.0;
4760 if (mHwPaused) {
4761 doHwResume = true;
4762 mHwPaused = false;
4763 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004764 }
4765 }
4766
Eric Laurent81784c32012-11-19 14:55:58 -08004767 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004768 // for all its buffers to be filled before processing it.
4769 // Allow draining the buffer in case the client
4770 // app does not call stop() and relies on underrun to stop:
4771 // hence the test on (track->mRetryCount > 1).
4772 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004773 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004774 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004775 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004776 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004777 minFrames = mNormalFrameCount;
4778 } else {
4779 minFrames = 1;
4780 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004781
Eric Laurentab5cdba2014-06-09 17:22:27 -07004782 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4783 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004784 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004785 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004786
4787 if (track->mFillingUpStatus == Track::FS_FILLED) {
4788 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004789 if (last) {
4790 // make sure processVolume_l() will apply new volume even if 0
4791 mLeftVolFloat = mRightVolFloat = -1.0;
4792 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004793 if (!mHwSupportsPause) {
4794 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004795 }
4796 }
4797
4798 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004799 processVolume_l(track, last);
4800 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004801 sp<Track> previousTrack = mPreviousTrack.promote();
4802 if (previousTrack != 0) {
4803 if (track != previousTrack.get()) {
4804 // Flush any data still being written from last track
4805 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004806 // Invalidate previous track to force a seek when resuming.
4807 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004808 }
4809 }
4810 mPreviousTrack = track;
4811
Eric Laurentd595b7c2013-04-03 17:27:56 -07004812 // reset retry count
4813 track->mRetryCount = kMaxTrackRetriesDirect;
4814 mActiveTrack = t;
4815 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004816 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004817 doHwResume = true;
4818 mHwPaused = false;
4819 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004820 }
Eric Laurent81784c32012-11-19 14:55:58 -08004821 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004822 // clear effect chain input buffer if the last active track started underruns
4823 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004824 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004825 mEffectChains[0]->clearInputBuffer();
4826 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004827 if (track->isStopping_1()) {
4828 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004829 if (last && mHwPaused) {
4830 doHwResume = true;
4831 mHwPaused = false;
4832 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004833 }
4834 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4835 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004836 // We have consumed all the buffers of this track.
4837 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004838 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004839 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004840 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4841 } else {
4842 audioHALFrames = 0;
4843 }
4844
Andy Hung818e7a32016-02-16 18:08:07 -08004845 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004846 if (mStandby || !last ||
4847 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004848 if (track->isStopping_2()) {
4849 track->mState = TrackBase::STOPPED;
4850 }
Eric Laurent81784c32012-11-19 14:55:58 -08004851 if (track->isStopped()) {
4852 track->reset();
4853 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004854 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004855 }
4856 } else {
4857 // No buffers for this track. Give it a few chances to
4858 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004859 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004860 if (--(track->mRetryCount) <= 0) {
4861 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004862 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004863 // indicate to client process that the track was disabled because of underrun;
4864 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004865 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004866 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004867 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4868 "minFrames = %u, mFormat = %#x",
4869 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004870 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004871 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004872 doHwPause = true;
4873 mHwPaused = true;
4874 }
Eric Laurent81784c32012-11-19 14:55:58 -08004875 }
4876 }
4877 }
4878 }
4879
Eric Laurentd1f69b02014-12-15 14:33:13 -08004880 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004881 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004882 for (size_t i = 0; i < mTracks.size(); i++) {
4883 if (mTracks[i]->isFlushPending()) {
4884 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004885 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004886 }
4887 }
4888 }
4889
4890 // make sure the pause/flush/resume sequence is executed in the right order.
4891 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4892 // before flush and then resume HW. This can happen in case of pause/flush/resume
4893 // if resume is received before pause is executed.
4894 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004895 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004896 status_t result = mOutput->stream->pause();
4897 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004898 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004899 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004900 flushHw_l();
4901 }
4902 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004903 status_t result = mOutput->stream->resume();
4904 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004905 }
Eric Laurent81784c32012-11-19 14:55:58 -08004906 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004907 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004908
4909 return mixerStatus;
4910}
4911
4912void AudioFlinger::DirectOutputThread::threadLoop_mix()
4913{
Eric Laurent81784c32012-11-19 14:55:58 -08004914 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004915 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004916 // output audio to hardware
4917 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004918 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004919 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004920 status_t status = mActiveTrack->getNextBuffer(&buffer);
4921 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004922 // no need to pad with 0 for compressed audio
4923 if (audio_has_proportional_frames(mFormat)) {
4924 memset(curBuf, 0, frameCount * mFrameSize);
4925 }
Eric Laurent81784c32012-11-19 14:55:58 -08004926 break;
4927 }
4928 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4929 frameCount -= buffer.frameCount;
4930 curBuf += buffer.frameCount * mFrameSize;
4931 mActiveTrack->releaseBuffer(&buffer);
4932 }
Andy Hung2098f272014-02-27 14:00:06 -08004933 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004934 mSleepTimeUs = 0;
4935 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004936 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004937}
4938
4939void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4940{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004941 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004942 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004943 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004944 return;
4945 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004946 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004947 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07004948 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004949 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004950 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004951 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004952 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004953 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004954 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004955 }
4956}
4957
Eric Laurentd1f69b02014-12-15 14:33:13 -08004958void AudioFlinger::DirectOutputThread::threadLoop_exit()
4959{
4960 {
4961 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004962 for (size_t i = 0; i < mTracks.size(); i++) {
4963 if (mTracks[i]->isFlushPending()) {
4964 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004965 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004966 }
4967 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004968 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004969 flushHw_l();
4970 }
4971 }
4972 PlaybackThread::threadLoop_exit();
4973}
4974
4975// must be called with thread mutex locked
4976bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4977{
4978 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004979 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004980
vivek mehta9cd7ad12016-03-17 00:18:29 -07004981 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4982 return !mStandby;
4983 }
4984
Eric Laurentd1f69b02014-12-15 14:33:13 -08004985 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4986 // after a timeout and we will enter standby then.
4987 if (mTracks.size() > 0) {
4988 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004989 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4990 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004991 }
4992
Eric Laurent5cff4032015-05-26 13:49:58 -07004993 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004994}
4995
Eric Laurent81784c32012-11-19 14:55:58 -08004996// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004997int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07004998 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004999{
Eric Laurentad7dd962016-09-22 12:38:37 -07005000 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5001 return -1;
5002 }
Eric Laurent81784c32012-11-19 14:55:58 -08005003 return 0;
5004}
5005
5006// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005007void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005008{
5009}
5010
Eric Laurent10351942014-05-08 18:49:52 -07005011// checkForNewParameter_l() must be called with ThreadBase::mLock held
5012bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5013 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005014{
5015 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005016 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005017
Eric Laurent10351942014-05-08 18:49:52 -07005018 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005019
Eric Laurent10351942014-05-08 18:49:52 -07005020 AudioParameter param = AudioParameter(keyValuePair);
5021 int value;
5022 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5023 // forward device change to effects that have requested to be
5024 // aware of attached audio device.
5025 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005026 a2dpDeviceChanged =
5027 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005028 mOutDevice = value;
5029 for (size_t i = 0; i < mEffectChains.size(); i++) {
5030 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005031 }
5032 }
Eric Laurent81784c32012-11-19 14:55:58 -08005033 }
Eric Laurent10351942014-05-08 18:49:52 -07005034 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5035 // do not accept frame count changes if tracks are open as the track buffer
5036 // size depends on frame count and correct behavior would not be garantied
5037 // if frame count is changed after track creation
5038 if (!mTracks.isEmpty()) {
5039 status = INVALID_OPERATION;
5040 } else {
5041 reconfig = true;
5042 }
5043 }
5044 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005045 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005046 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005047 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005048 mStandby = true;
5049 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005050 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005051 }
5052 if (status == NO_ERROR && reconfig) {
5053 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005054 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005055 }
5056 }
5057
Eric Laurent42537be2016-01-08 17:16:42 -08005058 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005059}
5060
5061uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5062{
5063 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005064 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005065 time = PlaybackThread::activeSleepTimeUs();
5066 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005067 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005068 }
5069 return time;
5070}
5071
5072uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5073{
5074 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005075 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005076 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5077 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005078 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005079 }
5080 return time;
5081}
5082
5083uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5084{
5085 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005086 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005087 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5088 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005089 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005090 }
5091 return time;
5092}
5093
5094void AudioFlinger::DirectOutputThread::cacheParameters_l()
5095{
5096 PlaybackThread::cacheParameters_l();
5097
5098 // use shorter standby delay as on normal output to release
5099 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005100 // no delay on outputs with HW A/V sync
5101 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005102 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005103 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005104 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005105 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005106 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005107 }
Eric Laurent81784c32012-11-19 14:55:58 -08005108}
5109
Eric Laurente659ef42014-09-29 13:06:46 -07005110void AudioFlinger::DirectOutputThread::flushHw_l()
5111{
Phil Burk062e67a2015-02-11 13:40:50 -08005112 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005113 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005114 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005115}
5116
Eric Laurent81784c32012-11-19 14:55:58 -08005117// ----------------------------------------------------------------------------
5118
Eric Laurentbfb1b832013-01-07 09:53:42 -08005119AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005120 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005121 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005122 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005123 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005124 mDrainSequence(0),
5125 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005126{
5127}
5128
5129AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5130{
5131}
5132
5133void AudioFlinger::AsyncCallbackThread::onFirstRef()
5134{
5135 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5136}
5137
5138bool AudioFlinger::AsyncCallbackThread::threadLoop()
5139{
5140 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005141 uint32_t writeAckSequence;
5142 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005143 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005144
5145 {
5146 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005147 while (!((mWriteAckSequence & 1) ||
5148 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005149 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005150 exitPending())) {
5151 mWaitWorkCV.wait(mLock);
5152 }
5153
Eric Laurentbfb1b832013-01-07 09:53:42 -08005154 if (exitPending()) {
5155 break;
5156 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005157 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5158 mWriteAckSequence, mDrainSequence);
5159 writeAckSequence = mWriteAckSequence;
5160 mWriteAckSequence &= ~1;
5161 drainSequence = mDrainSequence;
5162 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005163 asyncError = mAsyncError;
5164 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005165 }
5166 {
Eric Laurent4de95592013-09-26 15:28:21 -07005167 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5168 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005169 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005170 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005171 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005172 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005173 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005174 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005175 if (asyncError) {
5176 playbackThread->onAsyncError();
5177 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005178 }
5179 }
5180 }
5181 return false;
5182}
5183
5184void AudioFlinger::AsyncCallbackThread::exit()
5185{
5186 ALOGV("AsyncCallbackThread::exit");
5187 Mutex::Autolock _l(mLock);
5188 requestExit();
5189 mWaitWorkCV.broadcast();
5190}
5191
Eric Laurent3b4529e2013-09-05 18:09:19 -07005192void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005193{
5194 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005195 // bit 0 is cleared
5196 mWriteAckSequence = sequence << 1;
5197}
5198
5199void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5200{
5201 Mutex::Autolock _l(mLock);
5202 // ignore unexpected callbacks
5203 if (mWriteAckSequence & 2) {
5204 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005205 mWaitWorkCV.signal();
5206 }
5207}
5208
Eric Laurent3b4529e2013-09-05 18:09:19 -07005209void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005210{
5211 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005212 // bit 0 is cleared
5213 mDrainSequence = sequence << 1;
5214}
5215
5216void AudioFlinger::AsyncCallbackThread::resetDraining()
5217{
5218 Mutex::Autolock _l(mLock);
5219 // ignore unexpected callbacks
5220 if (mDrainSequence & 2) {
5221 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005222 mWaitWorkCV.signal();
5223 }
5224}
5225
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005226void AudioFlinger::AsyncCallbackThread::setAsyncError()
5227{
5228 Mutex::Autolock _l(mLock);
5229 mAsyncError = true;
5230 mWaitWorkCV.signal();
5231}
5232
Eric Laurentbfb1b832013-01-07 09:53:42 -08005233
5234// ----------------------------------------------------------------------------
5235AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005236 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5237 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005238 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5239 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005240{
Eric Laurentfd477972013-10-25 18:10:40 -07005241 //FIXME: mStandby should be set to true by ThreadBase constructor
5242 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005243 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005244}
5245
Eric Laurentbfb1b832013-01-07 09:53:42 -08005246void AudioFlinger::OffloadThread::threadLoop_exit()
5247{
5248 if (mFlushPending || mHwPaused) {
5249 // If a flush is pending or track was paused, just discard buffered data
5250 flushHw_l();
5251 } else {
5252 mMixerStatus = MIXER_DRAIN_ALL;
5253 threadLoop_drain();
5254 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005255 if (mUseAsyncWrite) {
5256 ALOG_ASSERT(mCallbackThread != 0);
5257 mCallbackThread->exit();
5258 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005259 PlaybackThread::threadLoop_exit();
5260}
5261
5262AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5263 Vector< sp<Track> > *tracksToRemove
5264)
5265{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005266 size_t count = mActiveTracks.size();
5267
5268 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005269 bool doHwPause = false;
5270 bool doHwResume = false;
5271
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005272 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005273
Eric Laurentbfb1b832013-01-07 09:53:42 -08005274 // find out which tracks need to be processed
5275 for (size_t i = 0; i < count; i++) {
5276 sp<Track> t = mActiveTracks[i].promote();
5277 // The track died recently
5278 if (t == 0) {
5279 continue;
5280 }
5281 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005282#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005283 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005284#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005285 // Only consider last track started for volume and mixer state control.
5286 // In theory an older track could underrun and restart after the new one starts
5287 // but as we only care about the transition phase between two tracks on a
5288 // direct output, it is not a problem to ignore the underrun case.
5289 sp<Track> l = mLatestActiveTrack.promote();
5290 bool last = l.get() == track;
5291
Haynes Mathew George7844f672014-01-15 12:32:55 -08005292 if (track->isInvalid()) {
5293 ALOGW("An invalidated track shouldn't be in active list");
5294 tracksToRemove->add(track);
5295 continue;
5296 }
5297
5298 if (track->mState == TrackBase::IDLE) {
5299 ALOGW("An idle track shouldn't be in active list");
5300 continue;
5301 }
5302
Eric Laurentbfb1b832013-01-07 09:53:42 -08005303 if (track->isPausing()) {
5304 track->setPaused();
5305 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005306 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005307 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308 mHwPaused = true;
5309 }
5310 // If we were part way through writing the mixbuffer to
5311 // the HAL we must save this until we resume
5312 // BUG - this will be wrong if a different track is made active,
5313 // in that case we want to discard the pending data in the
5314 // mixbuffer and tell the client to present it again when the
5315 // track is resumed
5316 mPausedWriteLength = mCurrentWriteLength;
5317 mPausedBytesRemaining = mBytesRemaining;
5318 mBytesRemaining = 0; // stop writing
5319 }
5320 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005321 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005322 if (track->isStopping_1()) {
5323 track->mRetryCount = kMaxTrackStopRetriesOffload;
5324 } else {
5325 track->mRetryCount = kMaxTrackRetriesOffload;
5326 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005327 track->flushAck();
5328 if (last) {
5329 mFlushPending = true;
5330 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005331 } else if (track->isResumePending()){
5332 track->resumeAck();
5333 if (last) {
5334 if (mPausedBytesRemaining) {
5335 // Need to continue write that was interrupted
5336 mCurrentWriteLength = mPausedWriteLength;
5337 mBytesRemaining = mPausedBytesRemaining;
5338 mPausedBytesRemaining = 0;
5339 }
5340 if (mHwPaused) {
5341 doHwResume = true;
5342 mHwPaused = false;
5343 // threadLoop_mix() will handle the case that we need to
5344 // resume an interrupted write
5345 }
5346 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005347 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005348
Eric Laurent3df841a2016-07-15 15:15:40 -07005349 mLeftVolFloat = mRightVolFloat = -1.0;
5350
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005351 // Do not handle new data in this iteration even if track->framesReady()
5352 mixerStatus = MIXER_TRACKS_ENABLED;
5353 }
5354 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005355 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005356 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005357 if (track->mFillingUpStatus == Track::FS_FILLED) {
5358 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005359 if (last) {
5360 // make sure processVolume_l() will apply new volume even if 0
5361 mLeftVolFloat = mRightVolFloat = -1.0;
5362 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005363 }
5364
5365 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005366 sp<Track> previousTrack = mPreviousTrack.promote();
5367 if (previousTrack != 0) {
5368 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005369 // Flush any data still being written from last track
5370 mBytesRemaining = 0;
5371 if (mPausedBytesRemaining) {
5372 // Last track was paused so we also need to flush saved
5373 // mixbuffer state and invalidate track so that it will
5374 // re-submit that unwritten data when it is next resumed
5375 mPausedBytesRemaining = 0;
5376 // Invalidate is a bit drastic - would be more efficient
5377 // to have a flag to tell client that some of the
5378 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005379 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005380 }
5381 // flush data already sent to the DSP if changing audio session as audio
5382 // comes from a different source. Also invalidate previous track to force a
5383 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005384 if (previousTrack->sessionId() != track->sessionId()) {
5385 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005386 }
5387 }
5388 }
5389 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005390 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005391 if (track->isStopping_1()) {
5392 track->mRetryCount = kMaxTrackStopRetriesOffload;
5393 } else {
5394 track->mRetryCount = kMaxTrackRetriesOffload;
5395 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005396 mActiveTrack = t;
5397 mixerStatus = MIXER_TRACKS_READY;
5398 }
5399 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005400 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005401 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005402 if (--(track->mRetryCount) <= 0) {
5403 // Hardware buffer can hold a large amount of audio so we must
5404 // wait for all current track's data to drain before we say
5405 // that the track is stopped.
5406 if (mBytesRemaining == 0) {
5407 // Only start draining when all data in mixbuffer
5408 // has been written
5409 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5410 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5411 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5412 if (last && !mStandby) {
5413 // do not modify drain sequence if we are already draining. This happens
5414 // when resuming from pause after drain.
5415 if ((mDrainSequence & 1) == 0) {
5416 mSleepTimeUs = 0;
5417 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5418 mixerStatus = MIXER_DRAIN_TRACK;
5419 mDrainSequence += 2;
5420 }
5421 if (mHwPaused) {
5422 // It is possible to move from PAUSED to STOPPING_1 without
5423 // a resume so we must ensure hardware is running
5424 doHwResume = true;
5425 mHwPaused = false;
5426 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005427 }
5428 }
Eric Laurente93cc032016-05-05 10:15:10 -07005429 } else if (last) {
5430 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5431 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 }
5433 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005434 // Drain has completed or we are in standby, signal presentation complete
5435 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005436 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005437 uint32_t latency = 0;
5438 status_t result = mOutput->stream->getLatency(&latency);
5439 ALOGE_IF(result != OK,
5440 "Error when retrieving output stream latency: %d", result);
5441 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005442 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005443 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005444 track->presentationComplete(framesWritten, audioHALFrames);
5445 track->reset();
5446 tracksToRemove->add(track);
5447 }
5448 } else {
5449 // No buffers for this track. Give it a few chances to
5450 // fill a buffer, then remove it from active list.
5451 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005452 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005453 uint64_t position = 0;
5454 struct timespec unused;
5455 // The running check restarts the retry counter at least once.
5456 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5457 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5458 running = true;
5459 mOffloadUnderrunPosition = position;
5460 }
5461 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005462 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5463 (long long)position, (long long)mOffloadUnderrunPosition);
5464 }
5465 if (running) { // still running, give us more time.
5466 track->mRetryCount = kMaxTrackRetriesOffload;
5467 } else {
5468 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5469 track->name());
5470 tracksToRemove->add(track);
5471 // indicate to client process that the track was disabled because of underrun;
5472 // it will then automatically call start() when data is available
5473 track->disable();
5474 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005475 } else if (last){
5476 mixerStatus = MIXER_TRACKS_ENABLED;
5477 }
5478 }
5479 }
5480 // compute volume for this track
5481 processVolume_l(track, last);
5482 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005483
Eric Laurentea0fade2013-10-04 16:23:48 -07005484 // make sure the pause/flush/resume sequence is executed in the right order.
5485 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5486 // before flush and then resume HW. This can happen in case of pause/flush/resume
5487 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005488 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005489 status_t result = mOutput->stream->pause();
5490 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005491 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005492 if (mFlushPending) {
5493 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005494 }
Eric Laurentfd477972013-10-25 18:10:40 -07005495 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005496 status_t result = mOutput->stream->resume();
5497 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005498 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005499
Eric Laurentbfb1b832013-01-07 09:53:42 -08005500 // remove all the tracks that need to be...
5501 removeTracks_l(*tracksToRemove);
5502
5503 return mixerStatus;
5504}
5505
Eric Laurentbfb1b832013-01-07 09:53:42 -08005506// must be called with thread mutex locked
5507bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5508{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005509 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5510 mWriteAckSequence, mDrainSequence);
5511 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005512 return true;
5513 }
5514 return false;
5515}
5516
Eric Laurentbfb1b832013-01-07 09:53:42 -08005517bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5518{
5519 Mutex::Autolock _l(mLock);
5520 return waitingAsyncCallback_l();
5521}
5522
5523void AudioFlinger::OffloadThread::flushHw_l()
5524{
Eric Laurente659ef42014-09-29 13:06:46 -07005525 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005526 // Flush anything still waiting in the mixbuffer
5527 mCurrentWriteLength = 0;
5528 mBytesRemaining = 0;
5529 mPausedWriteLength = 0;
5530 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005531 // reset bytes written count to reflect that DSP buffers are empty after flush.
5532 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005533 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005534
Eric Laurentbfb1b832013-01-07 09:53:42 -08005535 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005536 // discard any pending drain or write ack by incrementing sequence
5537 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5538 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005539 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005540 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5541 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005542 }
5543}
5544
Haynes Mathew George05317d22016-05-03 16:34:26 -07005545void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5546{
5547 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005548 if (PlaybackThread::invalidateTracks_l(streamType)) {
5549 mFlushPending = true;
5550 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005551}
5552
Eric Laurentbfb1b832013-01-07 09:53:42 -08005553// ----------------------------------------------------------------------------
5554
Eric Laurent81784c32012-11-19 14:55:58 -08005555AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005556 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005557 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005558 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005559 mWaitTimeMs(UINT_MAX)
5560{
5561 addOutputTrack(mainThread);
5562}
5563
5564AudioFlinger::DuplicatingThread::~DuplicatingThread()
5565{
5566 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5567 mOutputTracks[i]->destroy();
5568 }
5569}
5570
5571void AudioFlinger::DuplicatingThread::threadLoop_mix()
5572{
5573 // mix buffers...
5574 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005575 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005576 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005577 if (mMixerBufferValid) {
5578 memset(mMixerBuffer, 0, mMixerBufferSize);
5579 } else {
5580 memset(mSinkBuffer, 0, mSinkBufferSize);
5581 }
Eric Laurent81784c32012-11-19 14:55:58 -08005582 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005583 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005584 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005585 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005586 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005587}
5588
5589void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5590{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005591 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005592 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005593 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005594 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005595 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005596 }
5597 } else if (mBytesWritten != 0) {
5598 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5599 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005600 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005601 } else {
5602 // flush remaining overflow buffers in output tracks
5603 writeFrames = 0;
5604 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005605 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005606 }
5607}
5608
Eric Laurentbfb1b832013-01-07 09:53:42 -08005609ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005610{
5611 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005612 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005613 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005614 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005615 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005616}
5617
5618void AudioFlinger::DuplicatingThread::threadLoop_standby()
5619{
5620 // DuplicatingThread implements standby by stopping all tracks
5621 for (size_t i = 0; i < outputTracks.size(); i++) {
5622 outputTracks[i]->stop();
5623 }
5624}
5625
5626void AudioFlinger::DuplicatingThread::saveOutputTracks()
5627{
5628 outputTracks = mOutputTracks;
5629}
5630
5631void AudioFlinger::DuplicatingThread::clearOutputTracks()
5632{
5633 outputTracks.clear();
5634}
5635
5636void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5637{
5638 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005639 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5640 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5641 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5642 const size_t frameCount =
5643 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5644 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5645 // from different OutputTracks and their associated MixerThreads (e.g. one may
5646 // nearly empty and the other may be dropping data).
5647
5648 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005649 this,
5650 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005651 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005652 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005653 frameCount,
5654 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005655 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5656 if (status != NO_ERROR) {
5657 ALOGE("addOutputTrack() initCheck failed %d", status);
5658 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005659 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005660 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5661 mOutputTracks.add(outputTrack);
5662 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5663 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005664}
5665
5666void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5667{
5668 Mutex::Autolock _l(mLock);
5669 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5670 if (mOutputTracks[i]->thread() == thread) {
5671 mOutputTracks[i]->destroy();
5672 mOutputTracks.removeAt(i);
5673 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005674 if (thread->getOutput() == mOutput) {
5675 mOutput = NULL;
5676 }
Eric Laurent81784c32012-11-19 14:55:58 -08005677 return;
5678 }
5679 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005680 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005681}
5682
5683// caller must hold mLock
5684void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5685{
5686 mWaitTimeMs = UINT_MAX;
5687 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5688 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5689 if (strong != 0) {
5690 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5691 if (waitTimeMs < mWaitTimeMs) {
5692 mWaitTimeMs = waitTimeMs;
5693 }
5694 }
5695 }
5696}
5697
5698
5699bool AudioFlinger::DuplicatingThread::outputsReady(
5700 const SortedVector< sp<OutputTrack> > &outputTracks)
5701{
5702 for (size_t i = 0; i < outputTracks.size(); i++) {
5703 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5704 if (thread == 0) {
5705 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5706 outputTracks[i].get());
5707 return false;
5708 }
5709 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5710 // see note at standby() declaration
5711 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5712 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5713 thread.get());
5714 return false;
5715 }
5716 }
5717 return true;
5718}
5719
5720uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5721{
5722 return (mWaitTimeMs * 1000) / 2;
5723}
5724
5725void AudioFlinger::DuplicatingThread::cacheParameters_l()
5726{
5727 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5728 updateWaitTime_l();
5729
5730 MixerThread::cacheParameters_l();
5731}
5732
5733// ----------------------------------------------------------------------------
5734// Record
5735// ----------------------------------------------------------------------------
5736
5737AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5738 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005739 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005740 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005741 audio_devices_t inDevice,
5742 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005743#ifdef TEE_SINK
5744 , const sp<NBAIO_Sink>& teeSink
5745#endif
5746 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005747 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005748 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005749 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005750 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005751#ifdef TEE_SINK
5752 , mTeeSink(teeSink)
5753#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005754 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5755 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005756 // mFastCapture below
5757 , mFastCaptureFutex(0)
5758 // mInputSource
5759 // mPipeSink
5760 // mPipeSource
5761 , mPipeFramesP2(0)
5762 // mPipeMemory
5763 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005764 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005765{
Glenn Kastend7dca052015-03-05 16:05:54 -08005766 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5767 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005768
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005769 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005770
5771 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005772 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005773 size_t numCounterOffers = 0;
5774 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005775#if !LOG_NDEBUG
5776 ssize_t index =
5777#else
5778 (void)
5779#endif
5780 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005781 ALOG_ASSERT(index == 0);
5782
5783 // initialize fast capture depending on configuration
5784 bool initFastCapture;
5785 switch (kUseFastCapture) {
5786 case FastCapture_Never:
5787 initFastCapture = false;
5788 break;
5789 case FastCapture_Always:
5790 initFastCapture = true;
5791 break;
5792 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005793 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005794 break;
5795 // case FastCapture_Dynamic:
5796 }
5797
5798 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005799 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005800 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005801 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5802 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005803 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5804 void *pipeBuffer;
5805 const sp<MemoryDealer> roHeap(readOnlyHeap());
5806 sp<IMemory> pipeMemory;
5807 if ((roHeap == 0) ||
5808 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5809 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5810 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5811 goto failed;
5812 }
5813 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5814 memset(pipeBuffer, 0, pipeSize);
5815 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5816 const NBAIO_Format offers[1] = {format};
5817 size_t numCounterOffers = 0;
5818 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5819 ALOG_ASSERT(index == 0);
5820 mPipeSink = pipe;
5821 PipeReader *pipeReader = new PipeReader(*pipe);
5822 numCounterOffers = 0;
5823 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5824 ALOG_ASSERT(index == 0);
5825 mPipeSource = pipeReader;
5826 mPipeFramesP2 = pipeFramesP2;
5827 mPipeMemory = pipeMemory;
5828
5829 // create fast capture
5830 mFastCapture = new FastCapture();
5831 FastCaptureStateQueue *sq = mFastCapture->sq();
5832#ifdef STATE_QUEUE_DUMP
5833 // FIXME
5834#endif
5835 FastCaptureState *state = sq->begin();
5836 state->mCblk = NULL;
5837 state->mInputSource = mInputSource.get();
5838 state->mInputSourceGen++;
5839 state->mPipeSink = pipe;
5840 state->mPipeSinkGen++;
5841 state->mFrameCount = mFrameCount;
5842 state->mCommand = FastCaptureState::COLD_IDLE;
5843 // already done in constructor initialization list
5844 //mFastCaptureFutex = 0;
5845 state->mColdFutexAddr = &mFastCaptureFutex;
5846 state->mColdGen++;
5847 state->mDumpState = &mFastCaptureDumpState;
5848#ifdef TEE_SINK
5849 // FIXME
5850#endif
5851 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5852 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5853 sq->end();
5854 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5855
5856 // start the fast capture
5857 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5858 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005859 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005860#ifdef AUDIO_WATCHDOG
5861 // FIXME
5862#endif
5863
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005864 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005865 }
5866failed: ;
5867
5868 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005869}
5870
Eric Laurent81784c32012-11-19 14:55:58 -08005871AudioFlinger::RecordThread::~RecordThread()
5872{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005873 if (mFastCapture != 0) {
5874 FastCaptureStateQueue *sq = mFastCapture->sq();
5875 FastCaptureState *state = sq->begin();
5876 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5877 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5878 if (old == -1) {
5879 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5880 }
5881 }
5882 state->mCommand = FastCaptureState::EXIT;
5883 sq->end();
5884 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5885 mFastCapture->join();
5886 mFastCapture.clear();
5887 }
5888 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005889 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005890 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005891}
5892
5893void AudioFlinger::RecordThread::onFirstRef()
5894{
Glenn Kastend7dca052015-03-05 16:05:54 -08005895 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005896}
5897
Eric Laurent81784c32012-11-19 14:55:58 -08005898bool AudioFlinger::RecordThread::threadLoop()
5899{
Eric Laurent81784c32012-11-19 14:55:58 -08005900 nsecs_t lastWarning = 0;
5901
5902 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005903
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005904reacquire_wakelock:
5905 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005906 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005907 {
5908 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005909 size_t size = mActiveTracks.size();
5910 activeTracksGen = mActiveTracksGen;
5911 if (size > 0) {
5912 // FIXME an arbitrary choice
5913 activeTrack = mActiveTracks[0];
5914 acquireWakeLock_l(activeTrack->uid());
5915 if (size > 1) {
5916 SortedVector<int> tmp;
5917 for (size_t i = 0; i < size; i++) {
5918 tmp.add(mActiveTracks[i]->uid());
5919 }
5920 updateWakeLockUids_l(tmp);
5921 }
5922 } else {
5923 acquireWakeLock_l(-1);
5924 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005925 }
5926
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005927 // used to request a deferred sleep, to be executed later while mutex is unlocked
5928 uint32_t sleepUs = 0;
5929
5930 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005931 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005932 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005933
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005934 // activeTracks accumulates a copy of a subset of mActiveTracks
5935 Vector< sp<RecordTrack> > activeTracks;
5936
Glenn Kasten735f45f2014-08-18 15:51:59 -07005937 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005938 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005939
Glenn Kasten735f45f2014-08-18 15:51:59 -07005940 // reference to a fast track which is about to be removed
5941 sp<RecordTrack> fastTrackToRemove;
5942
Eric Laurent81784c32012-11-19 14:55:58 -08005943 { // scope for mLock
5944 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005945
Eric Laurent021cf962014-05-13 10:18:14 -07005946 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005947
Eric Laurent000a4192014-01-29 15:17:32 -08005948 // check exitPending here because checkForNewParameters_l() and
5949 // checkForNewParameters_l() can temporarily release mLock
5950 if (exitPending()) {
5951 break;
5952 }
5953
Eric Laurent5c25d562016-07-13 17:17:45 -07005954 // sleep with mutex unlocked
5955 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07005956 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07005957 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
5958 ATRACE_END();
5959 sleepUs = 0;
5960 continue;
5961 }
5962
Glenn Kasten2b806402013-11-20 16:37:38 -08005963 // if no active track(s), then standby and release wakelock
5964 size_t size = mActiveTracks.size();
5965 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005966 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005967 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005968 releaseWakeLock_l();
5969 ALOGV("RecordThread: loop stopping");
5970 // go to sleep
5971 mWaitWorkCV.wait(mLock);
5972 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005973 goto reacquire_wakelock;
5974 }
5975
Glenn Kasten2b806402013-11-20 16:37:38 -08005976 if (mActiveTracksGen != activeTracksGen) {
5977 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005978 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005979 for (size_t i = 0; i < size; i++) {
5980 tmp.add(mActiveTracks[i]->uid());
5981 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005982 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005983 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005984
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005985 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07005986 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005987 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005988
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005989 activeTrack = mActiveTracks[i];
5990 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005991 if (activeTrack->isFastTrack()) {
5992 ALOG_ASSERT(fastTrackToRemove == 0);
5993 fastTrackToRemove = activeTrack;
5994 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005995 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005996 mActiveTracks.remove(activeTrack);
5997 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005998 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005999 continue;
6000 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006001
6002 TrackBase::track_state activeTrackState = activeTrack->mState;
6003 switch (activeTrackState) {
6004
6005 case TrackBase::PAUSING:
6006 mActiveTracks.remove(activeTrack);
6007 mActiveTracksGen++;
6008 doBroadcast = true;
6009 size--;
6010 continue;
6011
6012 case TrackBase::STARTING_1:
6013 sleepUs = 10000;
6014 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006015 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006016 continue;
6017
6018 case TrackBase::STARTING_2:
6019 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006020 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006021 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006022 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006023 break;
6024
6025 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006026 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006027 break;
6028
6029 case TrackBase::IDLE:
6030 i++;
6031 continue;
6032
6033 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006034 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006035 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006036
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006037 activeTracks.add(activeTrack);
6038 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006039
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006040 if (activeTrack->isFastTrack()) {
6041 ALOG_ASSERT(!mFastTrackAvail);
6042 ALOG_ASSERT(fastTrack == 0);
6043 fastTrack = activeTrack;
6044 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006045 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006046
6047 if (allStopped) {
6048 standbyIfNotAlreadyInStandby();
6049 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006050 if (doBroadcast) {
6051 mStartStopCond.broadcast();
6052 }
6053
6054 // sleep if there are no active tracks to process
6055 if (activeTracks.size() == 0) {
6056 if (sleepUs == 0) {
6057 sleepUs = kRecordThreadSleepUs;
6058 }
6059 continue;
6060 }
6061 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006062
Eric Laurent81784c32012-11-19 14:55:58 -08006063 lockEffectChains_l(effectChains);
6064 }
6065
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006066 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006067
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006068 size_t size = effectChains.size();
6069 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006070 // thread mutex is not locked, but effect chain is locked
6071 effectChains[i]->process_l();
6072 }
6073
Glenn Kasten735f45f2014-08-18 15:51:59 -07006074 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006075 if (mFastCapture != 0) {
6076 FastCaptureStateQueue *sq = mFastCapture->sq();
6077 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006078 bool didModify = false;
6079 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006080 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6081 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6082 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6083 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6084 if (old == -1) {
6085 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6086 }
6087 }
6088 state->mCommand = FastCaptureState::READ_WRITE;
6089#if 0 // FIXME
6090 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006091 FastThreadDumpState::kSamplingNforLowRamDevice :
6092 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006093#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006094 didModify = true;
6095 }
6096 audio_track_cblk_t *cblkOld = state->mCblk;
6097 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6098 if (cblkNew != cblkOld) {
6099 state->mCblk = cblkNew;
6100 // block until acked if removing a fast track
6101 if (cblkOld != NULL) {
6102 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6103 }
6104 didModify = true;
6105 }
6106 sq->end(didModify);
6107 if (didModify) {
6108 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006109#if 0
6110 if (kUseFastCapture == FastCapture_Dynamic) {
6111 mNormalSource = mPipeSource;
6112 }
6113#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006114 }
6115 }
6116
Glenn Kasten735f45f2014-08-18 15:51:59 -07006117 // now run the fast track destructor with thread mutex unlocked
6118 fastTrackToRemove.clear();
6119
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006120 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6121 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6122 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6123 // If destination is non-contiguous, first read past the nominal end of buffer, then
6124 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006125
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006126 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006127 ssize_t framesRead;
6128
6129 // If an NBAIO source is present, use it to read the normal capture's data
6130 if (mPipeSource != 0) {
6131 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006132 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006133 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006134 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006135 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6136 // buffer size or at least for 20ms.
6137 size_t sleepFrames = max(
6138 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6139 if (framesRead <= (ssize_t) sleepFrames) {
6140 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6141 }
6142 if (framesRead < 0) {
6143 status_t status = (status_t) framesRead;
6144 switch (status) {
6145 case OVERRUN:
6146 ALOGW("overrun on read from pipe");
6147 framesRead = 0;
6148 break;
6149 case NEGOTIATE:
6150 ALOGE("re-negotiation is needed");
6151 framesRead = -1; // Will cause an attempt to recover.
6152 break;
6153 default:
6154 ALOGE("unknown error %d on read from pipe", status);
6155 break;
6156 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006157 }
6158 // otherwise use the HAL / AudioStreamIn directly
6159 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006160 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006161 size_t bytesRead;
6162 status_t result = mInput->stream->read(
6163 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006164 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006165 if (result < 0) {
6166 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006167 } else {
6168 framesRead = bytesRead / mFrameSize;
6169 }
6170 }
6171
Andy Hung3f0c9022016-01-15 17:49:46 -08006172 // Update server timestamp with server stats
6173 // systemTime() is optional if the hardware supports timestamps.
6174 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6175 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6176
6177 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006178 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006179 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006180 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006181 if (ret == NO_ERROR) {
6182 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6183 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6184 // Note: In general record buffers should tend to be empty in
6185 // a properly running pipeline.
6186 //
6187 // Also, it is not advantageous to call get_presentation_position during the read
6188 // as the read obtains a lock, preventing the timestamp call from executing.
6189 }
6190 }
6191 // Use this to track timestamp information
6192 // ALOGD("%s", mTimestamp.toString().c_str());
6193
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006194 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006195 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006196 // Force input into standby so that it tries to recover at next read attempt
6197 inputStandBy();
6198 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006199 }
6200 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006201 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006202 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006203 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006204
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006205 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006206 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006207 }
6208 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006209 {
6210 size_t part1 = mRsmpInFramesP2 - rear;
6211 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006212 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006213 (framesRead - part1) * mFrameSize);
6214 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006215 }
6216 rear = mRsmpInRear += framesRead;
6217
6218 size = activeTracks.size();
6219 // loop over each active track
6220 for (size_t i = 0; i < size; i++) {
6221 activeTrack = activeTracks[i];
6222
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006223 // skip fast tracks, as those are handled directly by FastCapture
6224 if (activeTrack->isFastTrack()) {
6225 continue;
6226 }
6227
Andy Hung73c02e42015-03-29 01:13:58 -07006228 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006229 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6230
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006231 enum {
6232 OVERRUN_UNKNOWN,
6233 OVERRUN_TRUE,
6234 OVERRUN_FALSE
6235 } overrun = OVERRUN_UNKNOWN;
6236
6237 // loop over getNextBuffer to handle circular sink
6238 for (;;) {
6239
6240 activeTrack->mSink.frameCount = ~0;
6241 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6242 size_t framesOut = activeTrack->mSink.frameCount;
6243 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6244
Andy Hung73c02e42015-03-29 01:13:58 -07006245 // check available frames and handle overrun conditions
6246 // if the record track isn't draining fast enough.
6247 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006248 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006249 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6250 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006251 overrun = OVERRUN_TRUE;
6252 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006253 if (framesOut == 0 || framesIn == 0) {
6254 break;
6255 }
6256
Andy Hung6770c6f2015-04-07 13:43:36 -07006257 // Don't allow framesOut to be larger than what is possible with resampling
6258 // from framesIn.
6259 // This isn't strictly necessary but helps limit buffer resizing in
6260 // RecordBufferConverter. TODO: remove when no longer needed.
6261 framesOut = min(framesOut,
6262 destinationFramesPossible(
6263 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006264 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6265 framesOut = activeTrack->mRecordBufferConverter->convert(
6266 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006267
6268 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6269 overrun = OVERRUN_FALSE;
6270 }
6271
6272 if (activeTrack->mFramesToDrop == 0) {
6273 if (framesOut > 0) {
6274 activeTrack->mSink.frameCount = framesOut;
6275 activeTrack->releaseBuffer(&activeTrack->mSink);
6276 }
6277 } else {
6278 // FIXME could do a partial drop of framesOut
6279 if (activeTrack->mFramesToDrop > 0) {
6280 activeTrack->mFramesToDrop -= framesOut;
6281 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006282 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006283 }
6284 } else {
6285 activeTrack->mFramesToDrop += framesOut;
6286 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6287 activeTrack->mSyncStartEvent->isCancelled()) {
6288 ALOGW("Synced record %s, session %d, trigger session %d",
6289 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6290 activeTrack->sessionId(),
6291 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006292 activeTrack->mSyncStartEvent->triggerSession() :
6293 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006294 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006295 }
6296 }
6297 }
6298
6299 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006300 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006301 }
6302 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006303
6304 switch (overrun) {
6305 case OVERRUN_TRUE:
6306 // client isn't retrieving buffers fast enough
6307 if (!activeTrack->setOverflow()) {
6308 nsecs_t now = systemTime();
6309 // FIXME should lastWarning per track?
6310 if ((now - lastWarning) > kWarningThrottleNs) {
6311 ALOGW("RecordThread: buffer overflow");
6312 lastWarning = now;
6313 }
6314 }
6315 break;
6316 case OVERRUN_FALSE:
6317 activeTrack->clearOverflow();
6318 break;
6319 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006320 break;
6321 }
6322
Andy Hung3f0c9022016-01-15 17:49:46 -08006323 // update frame information and push timestamp out
6324 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006325 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006326 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6327 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006328 }
6329
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006330unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006331 // enable changes in effect chain
6332 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006333 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006334 }
6335
Glenn Kasten93e471f2013-08-19 08:40:07 -07006336 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006337
6338 {
6339 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006340 for (size_t i = 0; i < mTracks.size(); i++) {
6341 sp<RecordTrack> track = mTracks[i];
6342 track->invalidate();
6343 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006344 mActiveTracks.clear();
6345 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006346 mStartStopCond.broadcast();
6347 }
6348
6349 releaseWakeLock();
6350
6351 ALOGV("RecordThread %p exiting", this);
6352 return false;
6353}
6354
Glenn Kasten93e471f2013-08-19 08:40:07 -07006355void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006356{
6357 if (!mStandby) {
6358 inputStandBy();
6359 mStandby = true;
6360 }
6361}
6362
6363void AudioFlinger::RecordThread::inputStandBy()
6364{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006365 // Idle the fast capture if it's currently running
6366 if (mFastCapture != 0) {
6367 FastCaptureStateQueue *sq = mFastCapture->sq();
6368 FastCaptureState *state = sq->begin();
6369 if (!(state->mCommand & FastCaptureState::IDLE)) {
6370 state->mCommand = FastCaptureState::COLD_IDLE;
6371 state->mColdFutexAddr = &mFastCaptureFutex;
6372 state->mColdGen++;
6373 mFastCaptureFutex = 0;
6374 sq->end();
6375 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6376 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6377#if 0
6378 if (kUseFastCapture == FastCapture_Dynamic) {
6379 // FIXME
6380 }
6381#endif
6382#ifdef AUDIO_WATCHDOG
6383 // FIXME
6384#endif
6385 } else {
6386 sq->end(false /*didModify*/);
6387 }
6388 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006389 status_t result = mInput->stream->standby();
6390 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006391
6392 // If going into standby, flush the pipe source.
6393 if (mPipeSource.get() != nullptr) {
6394 const ssize_t flushed = mPipeSource->flush();
6395 if (flushed > 0) {
6396 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6397 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6398 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6399 }
6400 }
Eric Laurent81784c32012-11-19 14:55:58 -08006401}
6402
Glenn Kasten05997e22014-03-13 15:08:33 -07006403// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006404sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006405 const sp<AudioFlinger::Client>& client,
6406 uint32_t sampleRate,
6407 audio_format_t format,
6408 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006409 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006410 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006411 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006412 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006413 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006414 pid_t tid,
6415 status_t *status)
6416{
Glenn Kasten74935e42013-12-19 08:56:45 -08006417 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006418 sp<RecordTrack> track;
6419 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006420 audio_input_flags_t inputFlags = mInput->flags;
6421
6422 // special case for FAST flag considered OK if fast capture is present
6423 if (hasFastCapture()) {
6424 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6425 }
6426
6427 // Check if requested flags are compatible with output stream flags
6428 if ((*flags & inputFlags) != *flags) {
6429 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6430 " input flags (%08x)",
6431 *flags, inputFlags);
6432 *flags = (audio_input_flags_t)(*flags & inputFlags);
6433 }
Eric Laurent81784c32012-11-19 14:55:58 -08006434
Glenn Kasten90e58b12013-07-31 16:16:02 -07006435 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006436 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006437 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006438 // we formerly checked for a callback handler (non-0 tid),
6439 // but that is no longer required for TRANSFER_OBTAIN mode
6440 //
Glenn Kasten74105912014-07-03 12:28:53 -07006441 // frame count is not specified, or is exactly the pipe depth
6442 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006443 // PCM data
6444 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006445 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006446 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006447 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006448 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006449 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006450 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006451 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006452 hasFastCapture() &&
6453 // there are sufficient fast track slots available
6454 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006455 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006456 // check compatibility with audio effects.
6457 Mutex::Autolock _l(mLock);
6458 // Do not accept FAST flag if the session has software effects
6459 sp<EffectChain> chain = getEffectChain_l(sessionId);
6460 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006461 audio_input_flags_t old = *flags;
6462 chain->checkInputFlagCompatibility(flags);
6463 if (old != *flags) {
6464 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6465 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006466 }
6467 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006468 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006469 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6470 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006471 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006472 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006473 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006474 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006475 frameCount, mFrameCount, mPipeFramesP2,
6476 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6477 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006478 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006479 }
6480 }
6481
6482 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006483 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006484 // fast track: frame count is exactly the pipe depth
6485 frameCount = mPipeFramesP2;
6486 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6487 *notificationFrames = mFrameCount;
6488 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006489 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6490 // or 20 ms if there is a fast capture
6491 // TODO This could be a roundupRatio inline, and const
6492 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6493 * sampleRate + mSampleRate - 1) / mSampleRate;
6494 // minimum number of notification periods is at least kMinNotifications,
6495 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6496 static const size_t kMinNotifications = 3;
6497 static const uint32_t kMinMs = 30;
6498 // TODO This could be a roundupRatio inline
6499 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6500 // TODO This could be a roundupRatio inline
6501 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6502 maxNotificationFrames;
6503 const size_t minFrameCount = maxNotificationFrames *
6504 max(kMinNotifications, minNotificationsByMs);
6505 frameCount = max(frameCount, minFrameCount);
6506 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6507 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006508 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006509 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006510 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006511
Glenn Kasten15e57982013-09-24 11:52:37 -07006512 lStatus = initCheck();
6513 if (lStatus != NO_ERROR) {
6514 ALOGE("createRecordTrack_l() audio driver not initialized");
6515 goto Exit;
6516 }
Eric Laurent81784c32012-11-19 14:55:58 -08006517
6518 { // scope for mLock
6519 Mutex::Autolock _l(mLock);
6520
6521 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006522 format, channelMask, frameCount, NULL, sessionId, uid,
6523 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006524
Glenn Kasten03003332013-08-06 15:40:54 -07006525 lStatus = track->initCheck();
6526 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006527 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006528 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006529 goto Exit;
6530 }
6531 mTracks.add(track);
6532
6533 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6534 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6535 mAudioFlinger->btNrecIsOff();
6536 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6537 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006538
Eric Laurent05067782016-06-01 18:27:28 -07006539 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006540 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6541 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6542 // so ask activity manager to do this on our behalf
6543 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6544 }
Eric Laurent81784c32012-11-19 14:55:58 -08006545 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006546
Eric Laurent81784c32012-11-19 14:55:58 -08006547 lStatus = NO_ERROR;
6548
6549Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006550 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006551 return track;
6552}
6553
6554status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6555 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006556 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006557{
6558 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6559 sp<ThreadBase> strongMe = this;
6560 status_t status = NO_ERROR;
6561
6562 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006563 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006564 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006565 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006566 triggerSession,
6567 recordTrack->sessionId(),
6568 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006569 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006570 // Sync event can be cancelled by the trigger session if the track is not in a
6571 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006572 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006573 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006574 } else {
6575 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006576 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006577 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006578 }
6579 }
6580
6581 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006582 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006583 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006584 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6585 if (recordTrack->mState == TrackBase::PAUSING) {
6586 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006587 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006588 } else {
6589 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006590 }
6591 return status;
6592 }
6593
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006594 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6595 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6596 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006597 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006598 mActiveTracks.add(recordTrack);
6599 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006600 status_t status = NO_ERROR;
6601 if (recordTrack->isExternalTrack()) {
6602 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006603 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006604 mLock.lock();
6605 // FIXME should verify that recordTrack is still in mActiveTracks
6606 if (status != NO_ERROR) {
6607 mActiveTracks.remove(recordTrack);
6608 mActiveTracksGen++;
6609 recordTrack->clearSyncStartEvent();
6610 ALOGV("RecordThread::start error %d", status);
6611 return status;
6612 }
Eric Laurent81784c32012-11-19 14:55:58 -08006613 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006614 // Catch up with current buffer indices if thread is already running.
6615 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6616 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6617 // see previously buffered data before it called start(), but with greater risk of overrun.
6618
Andy Hung73c02e42015-03-29 01:13:58 -07006619 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006620 // clear any converter state as new data will be discontinuous
6621 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006622 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006623 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006624 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006625 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006626 ALOGV("Record failed to start");
6627 status = BAD_VALUE;
6628 goto startError;
6629 }
Eric Laurent81784c32012-11-19 14:55:58 -08006630 return status;
6631 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006632
Eric Laurent81784c32012-11-19 14:55:58 -08006633startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006634 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006635 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006636 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006637 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006638 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006639 return status;
6640}
6641
Eric Laurent81784c32012-11-19 14:55:58 -08006642void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6643{
6644 sp<SyncEvent> strongEvent = event.promote();
6645
6646 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006647 sp<RefBase> ptr = strongEvent->cookie().promote();
6648 if (ptr != 0) {
6649 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6650 recordTrack->handleSyncStartEvent(strongEvent);
6651 }
Eric Laurent81784c32012-11-19 14:55:58 -08006652 }
6653}
6654
Glenn Kastena8356f62013-07-25 14:37:52 -07006655bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006656 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006657 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006658 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006659 return false;
6660 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006661 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006662 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006663 // signal thread to stop
6664 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006665 // do not wait for mStartStopCond if exiting
6666 if (exitPending()) {
6667 return true;
6668 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006669 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006670 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006671 // if we have been restarted, recordTrack is in mActiveTracks here
6672 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006673 ALOGV("Record stopped OK");
6674 return true;
6675 }
6676 return false;
6677}
6678
Glenn Kasten0f11b512014-01-31 16:18:54 -08006679bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006680{
6681 return false;
6682}
6683
Glenn Kasten0f11b512014-01-31 16:18:54 -08006684status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006685{
6686#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6687 if (!isValidSyncEvent(event)) {
6688 return BAD_VALUE;
6689 }
6690
Glenn Kastend848eb42016-03-08 13:42:11 -08006691 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006692 status_t ret = NAME_NOT_FOUND;
6693
6694 Mutex::Autolock _l(mLock);
6695
6696 for (size_t i = 0; i < mTracks.size(); i++) {
6697 sp<RecordTrack> track = mTracks[i];
6698 if (eventSession == track->sessionId()) {
6699 (void) track->setSyncEvent(event);
6700 ret = NO_ERROR;
6701 }
6702 }
6703 return ret;
6704#else
6705 return BAD_VALUE;
6706#endif
6707}
6708
6709// destroyTrack_l() must be called with ThreadBase::mLock held
6710void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6711{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006712 track->terminate();
6713 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006714 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006715 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006716 removeTrack_l(track);
6717 }
6718}
6719
6720void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6721{
6722 mTracks.remove(track);
6723 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006724 if (track->isFastTrack()) {
6725 ALOG_ASSERT(!mFastTrackAvail);
6726 mFastTrackAvail = true;
6727 }
Eric Laurent81784c32012-11-19 14:55:58 -08006728}
6729
6730void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6731{
6732 dumpInternals(fd, args);
6733 dumpTracks(fd, args);
6734 dumpEffectChains(fd, args);
6735}
6736
6737void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6738{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006739 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006740
Glenn Kasten44182c22015-03-05 17:12:23 -08006741 dumpBase(fd, args);
6742
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006743 AudioStreamIn *input = mInput;
6744 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6745 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6746 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006747 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006748 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006749 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006750 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006751 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006752
Glenn Kasten2f90c512015-12-02 11:40:09 -08006753 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6754 // while we are dumping it. It may be inconsistent, but it won't mutate!
6755 // This is a large object so we place it on the heap.
6756 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6757 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6758 copy->dump(fd);
6759 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006760}
6761
Glenn Kasten0f11b512014-01-31 16:18:54 -08006762void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006763{
6764 const size_t SIZE = 256;
6765 char buffer[SIZE];
6766 String8 result;
6767
Marco Nelissenb2208842014-02-07 14:00:50 -08006768 size_t numtracks = mTracks.size();
6769 size_t numactive = mActiveTracks.size();
6770 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006771 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006772 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006773 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006774 RecordTrack::appendDumpHeader(result);
6775 for (size_t i = 0; i < numtracks ; ++i) {
6776 sp<RecordTrack> track = mTracks[i];
6777 if (track != 0) {
6778 bool active = mActiveTracks.indexOf(track) >= 0;
6779 if (active) {
6780 numactiveseen++;
6781 }
6782 track->dump(buffer, SIZE, active);
6783 result.append(buffer);
6784 }
Eric Laurent81784c32012-11-19 14:55:58 -08006785 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006786 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006787 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006788 }
6789
Marco Nelissenb2208842014-02-07 14:00:50 -08006790 if (numactiveseen != numactive) {
6791 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6792 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006793 result.append(buffer);
6794 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006795 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006796 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006797 if (mTracks.indexOf(track) < 0) {
6798 track->dump(buffer, SIZE, true);
6799 result.append(buffer);
6800 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006801 }
Eric Laurent81784c32012-11-19 14:55:58 -08006802
6803 }
6804 write(fd, result.string(), result.size());
6805}
6806
Andy Hung73c02e42015-03-29 01:13:58 -07006807
6808void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6809{
6810 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6811 RecordThread *recordThread = (RecordThread *) threadBase.get();
6812 mRsmpInFront = recordThread->mRsmpInRear;
6813 mRsmpInUnrel = 0;
6814}
6815
6816void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6817 size_t *framesAvailable, bool *hasOverrun)
6818{
6819 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6820 RecordThread *recordThread = (RecordThread *) threadBase.get();
6821 const int32_t rear = recordThread->mRsmpInRear;
6822 const int32_t front = mRsmpInFront;
6823 const ssize_t filled = rear - front;
6824
6825 size_t framesIn;
6826 bool overrun = false;
6827 if (filled < 0) {
6828 // should not happen, but treat like a massive overrun and re-sync
6829 framesIn = 0;
6830 mRsmpInFront = rear;
6831 overrun = true;
6832 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6833 framesIn = (size_t) filled;
6834 } else {
6835 // client is not keeping up with server, but give it latest data
6836 framesIn = recordThread->mRsmpInFrames;
6837 mRsmpInFront = /* front = */ rear - framesIn;
6838 overrun = true;
6839 }
6840 if (framesAvailable != NULL) {
6841 *framesAvailable = framesIn;
6842 }
6843 if (hasOverrun != NULL) {
6844 *hasOverrun = overrun;
6845 }
6846}
6847
Eric Laurent81784c32012-11-19 14:55:58 -08006848// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006849status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006850 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006851{
Andy Hung73c02e42015-03-29 01:13:58 -07006852 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006853 if (threadBase == 0) {
6854 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006855 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006856 return NOT_ENOUGH_DATA;
6857 }
6858 RecordThread *recordThread = (RecordThread *) threadBase.get();
6859 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006860 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006861 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006862 // FIXME should not be P2 (don't want to increase latency)
6863 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006864 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006865 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006866 front &= recordThread->mRsmpInFramesP2 - 1;
6867 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006868 if (part1 > (size_t) filled) {
6869 part1 = filled;
6870 }
6871 size_t ask = buffer->frameCount;
6872 ALOG_ASSERT(ask > 0);
6873 if (part1 > ask) {
6874 part1 = ask;
6875 }
6876 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006877 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006878 buffer->raw = NULL;
6879 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006880 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006881 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006882 }
6883
Andy Hung57446612015-04-19 23:56:46 -07006884 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006885 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006886 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006887 return NO_ERROR;
6888}
6889
6890// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006891void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6892 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006893{
Glenn Kasten85948432013-08-19 12:09:05 -07006894 size_t stepCount = buffer->frameCount;
6895 if (stepCount == 0) {
6896 return;
6897 }
Andy Hung73c02e42015-03-29 01:13:58 -07006898 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6899 mRsmpInUnrel -= stepCount;
6900 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006901 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006902 buffer->frameCount = 0;
6903}
6904
Andy Hung97a893e2015-03-29 01:03:07 -07006905AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6906 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6907 uint32_t srcSampleRate,
6908 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6909 uint32_t dstSampleRate) :
6910 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6911 // mSrcFormat
6912 // mSrcSampleRate
6913 // mDstChannelMask
6914 // mDstFormat
6915 // mDstSampleRate
6916 // mSrcChannelCount
6917 // mDstChannelCount
6918 // mDstFrameSize
6919 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006920 mResampler(NULL),
6921 mIsLegacyDownmix(false),
6922 mIsLegacyUpmix(false),
6923 mRequiresFloat(false),
6924 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006925{
6926 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6927 dstChannelMask, dstFormat, dstSampleRate);
6928}
6929
6930AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6931 free(mBuf);
6932 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006933 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006934}
6935
6936size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6937 AudioBufferProvider *provider, size_t frames)
6938{
Andy Hungd330ee42015-04-20 13:23:41 -07006939 if (mInputConverterProvider != NULL) {
6940 mInputConverterProvider->setBufferProvider(provider);
6941 provider = mInputConverterProvider;
6942 }
6943
6944 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006945 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6946 mSrcSampleRate, mSrcFormat, mDstFormat);
6947
6948 AudioBufferProvider::Buffer buffer;
6949 for (size_t i = frames; i > 0; ) {
6950 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006951 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006952 if (status != OK || buffer.frameCount == 0) {
6953 frames -= i; // cannot fill request.
6954 break;
6955 }
Andy Hungd330ee42015-04-20 13:23:41 -07006956 // format convert to destination buffer
6957 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006958
6959 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6960 i -= buffer.frameCount;
6961 provider->releaseBuffer(&buffer);
6962 }
6963 } else {
6964 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6965 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6966
Andy Hungd330ee42015-04-20 13:23:41 -07006967 // reallocate buffer if needed
6968 if (mBufFrameSize != 0 && mBufFrames < frames) {
6969 free(mBuf);
6970 mBufFrames = frames;
6971 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6972 }
Andy Hung97a893e2015-03-29 01:03:07 -07006973 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006974 memset(mBuf, 0, frames * mBufFrameSize);
6975 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6976 // format convert to destination buffer
6977 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006978 }
6979 return frames;
6980}
6981
6982status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6983 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6984 uint32_t srcSampleRate,
6985 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6986 uint32_t dstSampleRate)
6987{
6988 // quick evaluation if there is any change.
6989 if (mSrcFormat == srcFormat
6990 && mSrcChannelMask == srcChannelMask
6991 && mSrcSampleRate == srcSampleRate
6992 && mDstFormat == dstFormat
6993 && mDstChannelMask == dstChannelMask
6994 && mDstSampleRate == dstSampleRate) {
6995 return NO_ERROR;
6996 }
6997
Andy Hungdb4c0312015-05-06 08:46:52 -07006998 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6999 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7000 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007001 const bool valid =
7002 audio_is_input_channel(srcChannelMask)
7003 && audio_is_input_channel(dstChannelMask)
7004 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7005 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7006 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7007 ; // no upsampling checks for now
7008 if (!valid) {
7009 return BAD_VALUE;
7010 }
7011
7012 mSrcFormat = srcFormat;
7013 mSrcChannelMask = srcChannelMask;
7014 mSrcSampleRate = srcSampleRate;
7015 mDstFormat = dstFormat;
7016 mDstChannelMask = dstChannelMask;
7017 mDstSampleRate = dstSampleRate;
7018
7019 // compute derived parameters
7020 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7021 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7022 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7023
Andy Hungd330ee42015-04-20 13:23:41 -07007024 // do we need to resample?
7025 delete mResampler;
7026 mResampler = NULL;
7027 if (mSrcSampleRate != mDstSampleRate) {
7028 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7029 mSrcChannelCount, mDstSampleRate);
7030 mResampler->setSampleRate(mSrcSampleRate);
7031 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7032 }
7033
7034 // are we running legacy channel conversion modes?
7035 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7036 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7037 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7038 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7039 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7040 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7041
7042 // do we need to process in float?
7043 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7044
7045 // do we need a staging buffer to convert for destination (we can still optimize this)?
7046 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7047 if (mResampler != NULL) {
7048 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7049 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007050 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007051 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7052 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007053 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7054 } else {
7055 mBufFrameSize = 0;
7056 }
7057 mBufFrames = 0; // force the buffer to be resized.
7058
Andy Hungd330ee42015-04-20 13:23:41 -07007059 // do we need an input converter buffer provider to give us float?
7060 delete mInputConverterProvider;
7061 mInputConverterProvider = NULL;
7062 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7063 mInputConverterProvider = new ReformatBufferProvider(
7064 audio_channel_count_from_in_mask(mSrcChannelMask),
7065 mSrcFormat,
7066 AUDIO_FORMAT_PCM_FLOAT,
7067 256 /* provider buffer frame count */);
7068 }
7069
7070 // do we need a remixer to do channel mask conversion
7071 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7072 (void) memcpy_by_index_array_initialization_from_channel_mask(
7073 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007074 }
7075 return NO_ERROR;
7076}
7077
Andy Hungd330ee42015-04-20 13:23:41 -07007078void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7079 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007080{
Andy Hungd330ee42015-04-20 13:23:41 -07007081 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007082 if (mBufFrameSize != 0 && mBufFrames < frames) {
7083 free(mBuf);
7084 mBufFrames = frames;
7085 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7086 }
Andy Hungd330ee42015-04-20 13:23:41 -07007087 // do we need to do legacy upmix and downmix?
7088 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007089 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007090 if (mIsLegacyUpmix) {
7091 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7092 (const float *)src, frames);
7093 } else /*mIsLegacyDownmix */ {
7094 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7095 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007096 }
Andy Hungd330ee42015-04-20 13:23:41 -07007097 if (mBuf != NULL) {
7098 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7099 frames * mDstChannelCount);
7100 }
7101 return;
7102 }
7103 // do we need to do channel mask conversion?
7104 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007105 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007106 memcpy_by_index_array(dstBuf, mDstChannelCount,
7107 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7108 if (dstBuf == dst) {
7109 return; // format is the same
7110 }
7111 }
7112 // convert to destination buffer
7113 const void *convertBuf = mBuf != NULL ? mBuf : src;
7114 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7115 frames * mDstChannelCount);
7116}
7117
7118void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7119 void *dst, /*not-a-const*/ void *src, size_t frames)
7120{
7121 // src buffer format is ALWAYS float when entering this routine
7122 if (mIsLegacyUpmix) {
7123 ; // mono to stereo already handled by resampler
7124 } else if (mIsLegacyDownmix
7125 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7126 // the resampler outputs stereo for mono input channel (a feature?)
7127 // must convert to mono
7128 downmix_to_mono_float_from_stereo_float((float *)src,
7129 (const float *)src, frames);
7130 } else if (mSrcChannelMask != mDstChannelMask) {
7131 // convert to mono channel again for channel mask conversion (could be skipped
7132 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007133 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007134 downmix_to_mono_float_from_stereo_float((float *)src,
7135 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007136 }
Andy Hungd330ee42015-04-20 13:23:41 -07007137 // convert to destination format (in place, OK as float is larger than other types)
7138 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7139 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7140 frames * mSrcChannelCount);
7141 }
7142 // channel convert and save to dst
7143 memcpy_by_index_array(dst, mDstChannelCount,
7144 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7145 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007146 }
Andy Hungd330ee42015-04-20 13:23:41 -07007147 // convert to destination format and save to dst
7148 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7149 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007150}
7151
Eric Laurent10351942014-05-08 18:49:52 -07007152bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7153 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007154{
7155 bool reconfig = false;
7156
Eric Laurent10351942014-05-08 18:49:52 -07007157 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007158
Eric Laurent10351942014-05-08 18:49:52 -07007159 audio_format_t reqFormat = mFormat;
7160 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007161 // 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 -07007162 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7163
7164 AudioParameter param = AudioParameter(keyValuePair);
7165 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007166
7167 // scope for AutoPark extends to end of method
7168 AutoPark<FastCapture> park(mFastCapture);
7169
Eric Laurent10351942014-05-08 18:49:52 -07007170 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7171 // channel count change can be requested. Do we mandate the first client defines the
7172 // HAL sampling rate and channel count or do we allow changes on the fly?
7173 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7174 samplingRate = value;
7175 reconfig = true;
7176 }
7177 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007178 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007179 status = BAD_VALUE;
7180 } else {
7181 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007182 reconfig = true;
7183 }
Eric Laurent10351942014-05-08 18:49:52 -07007184 }
7185 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7186 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007187 if (!audio_is_input_channel(mask) ||
7188 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007189 status = BAD_VALUE;
7190 } else {
7191 channelMask = mask;
7192 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007193 }
Eric Laurent10351942014-05-08 18:49:52 -07007194 }
7195 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7196 // do not accept frame count changes if tracks are open as the track buffer
7197 // size depends on frame count and correct behavior would not be guaranteed
7198 // if frame count is changed after track creation
7199 if (mActiveTracks.size() > 0) {
7200 status = INVALID_OPERATION;
7201 } else {
7202 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007203 }
Eric Laurent10351942014-05-08 18:49:52 -07007204 }
7205 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7206 // forward device change to effects that have requested to be
7207 // aware of attached audio device.
7208 for (size_t i = 0; i < mEffectChains.size(); i++) {
7209 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007210 }
Eric Laurent81784c32012-11-19 14:55:58 -08007211
Eric Laurent10351942014-05-08 18:49:52 -07007212 // store input device and output device but do not forward output device to audio HAL.
7213 // Note that status is ignored by the caller for output device
7214 // (see AudioFlinger::setParameters()
7215 if (audio_is_output_devices(value)) {
7216 mOutDevice = value;
7217 status = BAD_VALUE;
7218 } else {
7219 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007220 if (value != AUDIO_DEVICE_NONE) {
7221 mPrevInDevice = value;
7222 }
Eric Laurent10351942014-05-08 18:49:52 -07007223 // disable AEC and NS if the device is a BT SCO headset supporting those
7224 // pre processings
7225 if (mTracks.size() > 0) {
7226 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7227 mAudioFlinger->btNrecIsOff();
7228 for (size_t i = 0; i < mTracks.size(); i++) {
7229 sp<RecordTrack> track = mTracks[i];
7230 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7231 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007232 }
7233 }
7234 }
Eric Laurent10351942014-05-08 18:49:52 -07007235 }
7236 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7237 mAudioSource != (audio_source_t)value) {
7238 // forward device change to effects that have requested to be
7239 // aware of attached audio device.
7240 for (size_t i = 0; i < mEffectChains.size(); i++) {
7241 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007242 }
Eric Laurent10351942014-05-08 18:49:52 -07007243 mAudioSource = (audio_source_t)value;
7244 }
Glenn Kastene198c362013-08-13 09:13:36 -07007245
Eric Laurent10351942014-05-08 18:49:52 -07007246 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007247 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007248 if (status == INVALID_OPERATION) {
7249 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007250 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007251 }
7252 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007253 if (status == BAD_VALUE) {
7254 uint32_t sRate;
7255 audio_channel_mask_t channelMask;
7256 audio_format_t format;
7257 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7258 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7259 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7260 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7261 status = NO_ERROR;
7262 }
Eric Laurent81784c32012-11-19 14:55:58 -08007263 }
Eric Laurent10351942014-05-08 18:49:52 -07007264 if (status == NO_ERROR) {
7265 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007266 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007267 }
7268 }
Eric Laurent81784c32012-11-19 14:55:58 -08007269 }
Eric Laurent10351942014-05-08 18:49:52 -07007270
Eric Laurent81784c32012-11-19 14:55:58 -08007271 return reconfig;
7272}
7273
7274String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7275{
Eric Laurent81784c32012-11-19 14:55:58 -08007276 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007277 if (initCheck() == NO_ERROR) {
7278 String8 out_s8;
7279 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7280 return out_s8;
7281 }
Eric Laurent81784c32012-11-19 14:55:58 -08007282 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007283 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007284}
7285
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007286void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007287 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7288
7289 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007290
7291 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007292 case AUDIO_INPUT_OPENED:
7293 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007294 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007295 desc->mChannelMask = mChannelMask;
7296 desc->mSamplingRate = mSampleRate;
7297 desc->mFormat = mFormat;
7298 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007299 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007300 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007301 break;
7302
Eric Laurent73e26b62015-04-27 16:55:58 -07007303 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007304 default:
7305 break;
7306 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007307 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007308}
7309
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007310void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007311{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007312 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7313 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007314 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007315 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007316 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007317 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7318 result = mInput->stream->getFrameSize(&mFrameSize);
7319 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7320 result = mInput->stream->getBufferSize(&mBufferSize);
7321 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007322 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007323 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007324 // 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 -07007325 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007326 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007327 // A larger value should allow more old data to be read after a track calls start(),
7328 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007329 //
7330 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007331 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007332 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007333 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007334 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007335
7336 // TODO optimize audio capture buffer sizes ...
7337 // Here we calculate the size of the sliding buffer used as a source
7338 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7339 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7340 // be better to have it derived from the pipe depth in the long term.
7341 // The current value is higher than necessary. However it should not add to latency.
7342
Glenn Kasten85948432013-08-19 12:09:05 -07007343 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007344 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7345 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7346 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007347
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007348 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7349 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007350}
7351
Glenn Kasten5f972c02014-01-13 09:59:31 -08007352uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007353{
7354 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007355 uint32_t result;
7356 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7357 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007358 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007359 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007360}
7361
Eric Laurent4c415062016-06-17 16:14:16 -07007362// hasAudioSession_l() must be called with ThreadBase::mLock held
7363uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007364{
Eric Laurent81784c32012-11-19 14:55:58 -08007365 uint32_t result = 0;
7366 if (getEffectChain_l(sessionId) != 0) {
7367 result = EFFECT_SESSION;
7368 }
7369
7370 for (size_t i = 0; i < mTracks.size(); ++i) {
7371 if (sessionId == mTracks[i]->sessionId()) {
7372 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007373 if (mTracks[i]->isFastTrack()) {
7374 result |= FAST_SESSION;
7375 }
Eric Laurent81784c32012-11-19 14:55:58 -08007376 break;
7377 }
7378 }
7379
7380 return result;
7381}
7382
Glenn Kastend848eb42016-03-08 13:42:11 -08007383KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007384{
Glenn Kastend848eb42016-03-08 13:42:11 -08007385 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007386 Mutex::Autolock _l(mLock);
7387 for (size_t j = 0; j < mTracks.size(); ++j) {
7388 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007389 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007390 if (ids.indexOfKey(sessionId) < 0) {
7391 ids.add(sessionId, true);
7392 }
7393 }
7394 return ids;
7395}
7396
7397AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7398{
7399 Mutex::Autolock _l(mLock);
7400 AudioStreamIn *input = mInput;
7401 mInput = NULL;
7402 return input;
7403}
7404
7405// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007406sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007407{
7408 if (mInput == NULL) {
7409 return NULL;
7410 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007411 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007412}
7413
7414status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7415{
7416 // only one chain per input thread
7417 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007418 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007419 return INVALID_OPERATION;
7420 }
7421 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007422 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007423 chain->setInBuffer(NULL);
7424 chain->setOutBuffer(NULL);
7425
7426 checkSuspendOnAddEffectChain_l(chain);
7427
Eric Laurent1b928682014-10-02 19:41:47 -07007428 // make sure enabled pre processing effects state is communicated to the HAL as we
7429 // just moved them to a new input stream.
7430 chain->syncHalEffectsState();
7431
Eric Laurent81784c32012-11-19 14:55:58 -08007432 mEffectChains.add(chain);
7433
7434 return NO_ERROR;
7435}
7436
7437size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7438{
7439 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7440 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007441 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007442 chain.get(), mEffectChains.size(), this);
7443 if (mEffectChains.size() == 1) {
7444 mEffectChains.removeAt(0);
7445 }
7446 return 0;
7447}
7448
Eric Laurent1c333e22014-05-20 10:48:17 -07007449status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7450 audio_patch_handle_t *handle)
7451{
7452 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007453
7454 // store new device and send to effects
7455 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007456 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007457 for (size_t i = 0; i < mEffectChains.size(); i++) {
7458 mEffectChains[i]->setDevice_l(mInDevice);
7459 }
7460
7461 // disable AEC and NS if the device is a BT SCO headset supporting those
7462 // pre processings
7463 if (mTracks.size() > 0) {
7464 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7465 mAudioFlinger->btNrecIsOff();
7466 for (size_t i = 0; i < mTracks.size(); i++) {
7467 sp<RecordTrack> track = mTracks[i];
7468 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7469 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7470 }
7471 }
7472
7473 // store new source and send to effects
7474 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7475 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007476 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007477 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007478 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007479 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007480
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007481 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007482 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7483 status = hwDevice->createAudioPatch(patch->num_sources,
7484 patch->sources,
7485 patch->num_sinks,
7486 patch->sinks,
7487 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007488 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007489 char *address;
7490 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7491 address = audio_device_address_to_parameter(
7492 patch->sources[0].ext.device.type,
7493 patch->sources[0].ext.device.address);
7494 } else {
7495 address = (char *)calloc(1, 1);
7496 }
7497 AudioParameter param = AudioParameter(String8(address));
7498 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007499 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007500 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007501 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007502 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007503 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007504 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007505 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007506
Eric Laurente8726fe2015-06-26 09:39:24 -07007507 if (mInDevice != mPrevInDevice) {
7508 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7509 mPrevInDevice = mInDevice;
7510 }
Eric Laurent296fb132015-05-01 11:38:42 -07007511
Eric Laurent1c333e22014-05-20 10:48:17 -07007512 return status;
7513}
7514
7515status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7516{
7517 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007518
7519 mInDevice = AUDIO_DEVICE_NONE;
7520
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007521 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007522 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7523 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007524 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007525 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007526 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007527 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007528 }
7529 return status;
7530}
7531
Eric Laurent83b88082014-06-20 18:31:16 -07007532void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7533{
7534 Mutex::Autolock _l(mLock);
7535 mTracks.add(record);
7536}
7537
7538void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7539{
7540 Mutex::Autolock _l(mLock);
7541 destroyTrack_l(record);
7542}
7543
7544void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7545{
7546 ThreadBase::getAudioPortConfig(config);
7547 config->role = AUDIO_PORT_ROLE_SINK;
7548 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7549 config->ext.mix.usecase.source = mAudioSource;
7550}
Eric Laurent1c333e22014-05-20 10:48:17 -07007551
Glenn Kasten63238ef2015-03-02 15:50:29 -08007552} // namespace android