blob: abfbf0f300a2dff83d3e37582e0c47a216dc58f1 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070032#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080034#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080035
36#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070037#include <private/android_filesystem_config.h>
Andy Hung2ddee192015-12-18 17:34:44 -080038#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080039#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070042#include <system/audio_effects/effect_ns.h>
43#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045
46// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070047#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080048#include <media/nbaio/AudioStreamOutSink.h>
49#include <media/nbaio/MonoPipe.h>
50#include <media/nbaio/MonoPipeReader.h>
51#include <media/nbaio/Pipe.h>
52#include <media/nbaio/PipeReader.h>
53#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080054#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080055
56#include <powermanager/PowerManager.h>
57
Eric Laurent81784c32012-11-19 14:55:58 -080058#include "AudioFlinger.h"
59#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070060#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070064#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080065
Eric Laurent81784c32012-11-19 14:55:58 -080066#ifdef ADD_BATTERY_DATA
67#include <media/IMediaPlayerService.h>
68#include <media/IMediaDeathNotifier.h>
69#endif
70
Eric Laurent81784c32012-11-19 14:55:58 -080071#ifdef DEBUG_CPU_USAGE
72#include <cpustats/CentralTendencyStatistics.h>
73#include <cpustats/ThreadCpuUsage.h>
74#endif
75
Glenn Kastenc05b8d72016-03-24 09:48:17 -070076#include "AutoPark.h"
77
Eric Laurent81784c32012-11-19 14:55:58 -080078// ----------------------------------------------------------------------------
79
80// Note: the following macro is used for extremely verbose logging message. In
81// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
82// 0; but one side effect of this is to turn all LOGV's as well. Some messages
83// are so verbose that we want to suppress them even when we have ALOG_ASSERT
84// turned on. Do not uncomment the #def below unless you really know what you
85// are doing and want to see all of the extremely verbose messages.
86//#define VERY_VERY_VERBOSE_LOGGING
87#ifdef VERY_VERY_VERBOSE_LOGGING
88#define ALOGVV ALOGV
89#else
90#define ALOGVV(a...) do { } while(0)
91#endif
92
Andy Hung6770c6f2015-04-07 13:43:36 -070093// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070094#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070095template <typename T>
96static inline T min(const T& a, const T& b)
97{
98 return a < b ? a : b;
99}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700100
Andy Hungd330ee42015-04-20 13:23:41 -0700101#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700102#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700103#endif
104
Eric Laurent81784c32012-11-19 14:55:58 -0800105namespace android {
106
107// retry counts for buffer fill timeout
108// 50 * ~20msecs = 1 second
109static const int8_t kMaxTrackRetries = 50;
110static const int8_t kMaxTrackStartupRetries = 50;
111// allow less retry attempts on direct output thread.
112// direct outputs can be a scarce resource in audio hardware and should
113// be released as quickly as possible.
114static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700115
Eric Laurent51716182016-02-29 18:00:56 -0800116
Eric Laurent81784c32012-11-19 14:55:58 -0800117
118// don't warn about blocked writes or record buffer overflows more often than this
119static const nsecs_t kWarningThrottleNs = seconds(5);
120
121// RecordThread loop sleep time upon application overrun or audio HAL read error
122static const int kRecordThreadSleepUs = 5000;
123
Eric Laurent10351942014-05-08 18:49:52 -0700124// maximum time to wait in sendConfigEvent_l() for a status to be received
125static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800126
127// minimum sleep time for the mixer thread loop when tracks are active but in underrun
128static const uint32_t kMinThreadSleepTimeUs = 5000;
129// maximum divider applied to the active sleep time in the mixer thread loop
130static const uint32_t kMaxThreadSleepTimeShift = 2;
131
Andy Hung09a50072014-02-27 14:30:47 -0800132// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700133// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800134static const uint32_t kMinNormalSinkBufferSizeMs = 20;
135// maximum normal sink buffer size
136static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800137
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700138// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
139// FIXME This should be based on experimentally observed scheduling jitter
140static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
141
Eric Laurent972a1732013-09-04 09:42:59 -0700142// Offloaded output thread standby delay: allows track transition without going to standby
143static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
144
Eric Laurent51716182016-02-29 18:00:56 -0800145// Direct output thread minimum sleep time in idle or active(underrun) state
146static const nsecs_t kDirectMinSleepTimeUs = 10000;
147
Glenn Kasten1b291842016-07-18 14:55:21 -0700148// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
149// balance between power consumption and latency, and allows threads to be scheduled reliably
150// by the CFS scheduler.
151// FIXME Express other hardcoded references to 20ms with references to this constant and move
152// it appropriately.
153#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800154
Eric Laurent81784c32012-11-19 14:55:58 -0800155// Whether to use fast mixer
156static const enum {
157 FastMixer_Never, // never initialize or use: for debugging only
158 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
159 // normal mixer multiplier is 1
160 FastMixer_Static, // initialize if needed, then use all the time if initialized,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
163 // multiplier is calculated based on min & max normal mixer buffer size
164 // FIXME for FastMixer_Dynamic:
165 // Supporting this option will require fixing HALs that can't handle large writes.
166 // For example, one HAL implementation returns an error from a large write,
167 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
168 // We could either fix the HAL implementations, or provide a wrapper that breaks
169 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
170} kUseFastMixer = FastMixer_Static;
171
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700172// Whether to use fast capture
173static const enum {
174 FastCapture_Never, // never initialize or use: for debugging only
175 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
176 FastCapture_Static, // initialize if needed, then use all the time if initialized
177} kUseFastCapture = FastCapture_Static;
178
Eric Laurent81784c32012-11-19 14:55:58 -0800179// Priorities for requestPriority
180static const int kPriorityAudioApp = 2;
181static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700182static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800183
Glenn Kastenea38ee72016-04-18 11:08:01 -0700184// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
185// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
186// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700187
188// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800189static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800190
Glenn Kasten03490092014-05-27 12:30:54 -0700191// The minimum and maximum allowed values
192static const int kFastTrackMultiplierMin = 1;
193static const int kFastTrackMultiplierMax = 2;
194
195// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
196static int sFastTrackMultiplier = kFastTrackMultiplier;
197
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700198// See Thread::readOnlyHeap().
199// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
200// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
201// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700202static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700203
Eric Laurent81784c32012-11-19 14:55:58 -0800204// ----------------------------------------------------------------------------
205
Glenn Kasten03490092014-05-27 12:30:54 -0700206static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
207
208static void sFastTrackMultiplierInit()
209{
210 char value[PROPERTY_VALUE_MAX];
211 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
212 char *endptr;
213 unsigned long ul = strtoul(value, &endptr, 0);
214 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
215 sFastTrackMultiplier = (int) ul;
216 }
217 }
218}
219
220// ----------------------------------------------------------------------------
221
Eric Laurent81784c32012-11-19 14:55:58 -0800222#ifdef ADD_BATTERY_DATA
223// To collect the amplifier usage
224static void addBatteryData(uint32_t params) {
225 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
226 if (service == NULL) {
227 // it already logged
228 return;
229 }
230
231 service->addBatteryData(params);
232}
233#endif
234
Andy Hung3f0c9022016-01-15 17:49:46 -0800235// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
236struct {
237 // call when you acquire a partial wakelock
238 void acquire(const sp<IBinder> &wakeLockToken) {
239 pthread_mutex_lock(&mLock);
240 if (wakeLockToken.get() == nullptr) {
241 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
242 } else {
243 if (mCount == 0) {
244 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
245 }
246 ++mCount;
247 }
248 pthread_mutex_unlock(&mLock);
249 }
250
251 // call when you release a partial wakelock.
252 void release(const sp<IBinder> &wakeLockToken) {
253 if (wakeLockToken.get() == nullptr) {
254 return;
255 }
256 pthread_mutex_lock(&mLock);
257 if (--mCount < 0) {
258 ALOGE("negative wakelock count");
259 mCount = 0;
260 }
261 pthread_mutex_unlock(&mLock);
262 }
263
264 // retrieves the boottime timebase offset from monotonic.
265 int64_t getBoottimeOffset() {
266 pthread_mutex_lock(&mLock);
267 int64_t boottimeOffset = mBoottimeOffset;
268 pthread_mutex_unlock(&mLock);
269 return boottimeOffset;
270 }
271
272 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
273 // and the selected timebase.
274 // Currently only TIMEBASE_BOOTTIME is allowed.
275 //
276 // This only needs to be called upon acquiring the first partial wakelock
277 // after all other partial wakelocks are released.
278 //
279 // We do an empirical measurement of the offset rather than parsing
280 // /proc/timer_list since the latter is not a formal kernel ABI.
281 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
282 int clockbase;
283 switch (timebase) {
284 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
285 clockbase = SYSTEM_TIME_BOOTTIME;
286 break;
287 default:
288 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
289 break;
290 }
291 // try three times to get the clock offset, choose the one
292 // with the minimum gap in measurements.
293 const int tries = 3;
294 nsecs_t bestGap, measured;
295 for (int i = 0; i < tries; ++i) {
296 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t tbase = systemTime(clockbase);
298 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
299 const nsecs_t gap = tmono2 - tmono;
300 if (i == 0 || gap < bestGap) {
301 bestGap = gap;
302 measured = tbase - ((tmono + tmono2) >> 1);
303 }
304 }
305
306 // to avoid micro-adjusting, we don't change the timebase
307 // unless it is significantly different.
308 //
309 // Assumption: It probably takes more than toleranceNs to
310 // suspend and resume the device.
311 static int64_t toleranceNs = 10000; // 10 us
312 if (llabs(*offset - measured) > toleranceNs) {
313 ALOGV("Adjusting timebase offset old: %lld new: %lld",
314 (long long)*offset, (long long)measured);
315 *offset = measured;
316 }
317 }
318
319 pthread_mutex_t mLock;
320 int32_t mCount;
321 int64_t mBoottimeOffset;
322} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800323
324// ----------------------------------------------------------------------------
325// CPU Stats
326// ----------------------------------------------------------------------------
327
328class CpuStats {
329public:
330 CpuStats();
331 void sample(const String8 &title);
332#ifdef DEBUG_CPU_USAGE
333private:
334 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
335 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
336
337 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
338
339 int mCpuNum; // thread's current CPU number
340 int mCpukHz; // frequency of thread's current CPU in kHz
341#endif
342};
343
344CpuStats::CpuStats()
345#ifdef DEBUG_CPU_USAGE
346 : mCpuNum(-1), mCpukHz(-1)
347#endif
348{
349}
350
Glenn Kasten0f11b512014-01-31 16:18:54 -0800351void CpuStats::sample(const String8 &title
352#ifndef DEBUG_CPU_USAGE
353 __unused
354#endif
355 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800356#ifdef DEBUG_CPU_USAGE
357 // get current thread's delta CPU time in wall clock ns
358 double wcNs;
359 bool valid = mCpuUsage.sampleAndEnable(wcNs);
360
361 // record sample for wall clock statistics
362 if (valid) {
363 mWcStats.sample(wcNs);
364 }
365
366 // get the current CPU number
367 int cpuNum = sched_getcpu();
368
369 // get the current CPU frequency in kHz
370 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
371
372 // check if either CPU number or frequency changed
373 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
374 mCpuNum = cpuNum;
375 mCpukHz = cpukHz;
376 // ignore sample for purposes of cycles
377 valid = false;
378 }
379
380 // if no change in CPU number or frequency, then record sample for cycle statistics
381 if (valid && mCpukHz > 0) {
382 double cycles = wcNs * cpukHz * 0.000001;
383 mHzStats.sample(cycles);
384 }
385
386 unsigned n = mWcStats.n();
387 // mCpuUsage.elapsed() is expensive, so don't call it every loop
388 if ((n & 127) == 1) {
389 long long elapsed = mCpuUsage.elapsed();
390 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
391 double perLoop = elapsed / (double) n;
392 double perLoop100 = perLoop * 0.01;
393 double perLoop1k = perLoop * 0.001;
394 double mean = mWcStats.mean();
395 double stddev = mWcStats.stddev();
396 double minimum = mWcStats.minimum();
397 double maximum = mWcStats.maximum();
398 double meanCycles = mHzStats.mean();
399 double stddevCycles = mHzStats.stddev();
400 double minCycles = mHzStats.minimum();
401 double maxCycles = mHzStats.maximum();
402 mCpuUsage.resetElapsed();
403 mWcStats.reset();
404 mHzStats.reset();
405 ALOGD("CPU usage for %s over past %.1f secs\n"
406 " (%u mixer loops at %.1f mean ms per loop):\n"
407 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
408 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
409 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
410 title.string(),
411 elapsed * .000000001, n, perLoop * .000001,
412 mean * .001,
413 stddev * .001,
414 minimum * .001,
415 maximum * .001,
416 mean / perLoop100,
417 stddev / perLoop100,
418 minimum / perLoop100,
419 maximum / perLoop100,
420 meanCycles / perLoop1k,
421 stddevCycles / perLoop1k,
422 minCycles / perLoop1k,
423 maxCycles / perLoop1k);
424
425 }
426 }
427#endif
428};
429
430// ----------------------------------------------------------------------------
431// ThreadBase
432// ----------------------------------------------------------------------------
433
Glenn Kasten97b7b752014-09-28 13:04:24 -0700434// static
435const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
436{
437 switch (type) {
438 case MIXER:
439 return "MIXER";
440 case DIRECT:
441 return "DIRECT";
442 case DUPLICATING:
443 return "DUPLICATING";
444 case RECORD:
445 return "RECORD";
446 case OFFLOAD:
447 return "OFFLOAD";
448 default:
449 return "unknown";
450 }
451}
452
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700453std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 }
461 return result;
462}
463
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 std::string result;
467 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475 return result;
476}
477
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800478const char *sourceToString(audio_source_t source)
479{
480 switch (source) {
481 case AUDIO_SOURCE_DEFAULT: return "default";
482 case AUDIO_SOURCE_MIC: return "mic";
483 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
484 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
485 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
486 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
487 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
488 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
489 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800490 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800491 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
492 case AUDIO_SOURCE_HOTWORD: return "hotword";
493 default: return "unknown";
494 }
495}
496
Eric Laurent81784c32012-11-19 14:55:58 -0800497AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700498 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800499 : Thread(false /*canCallJava*/),
500 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700501 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700502 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800503 // are set by PlaybackThread::readOutputParameters_l() or
504 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700505 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800506 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700507 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
508 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800509 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700510 mDeathRecipient(new PMDeathRecipient(this)),
Andy Hungdae27702016-10-31 14:01:16 -0700511 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800512{
Eric Laurent296fb132015-05-01 11:38:42 -0700513 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800514}
515
516AudioFlinger::ThreadBase::~ThreadBase()
517{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700518 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 mConfigEvents.clear();
520
Eric Laurent81784c32012-11-19 14:55:58 -0800521 // do not lock the mutex in destructor
522 releaseWakeLock_l();
523 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800524 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800525 binder->unlinkToDeath(mDeathRecipient);
526 }
527}
528
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700529status_t AudioFlinger::ThreadBase::readyToRun()
530{
531 status_t status = initCheck();
532 if (status == NO_ERROR) {
533 ALOGI("AudioFlinger's thread %p ready to run", this);
534 } else {
535 ALOGE("No working audio driver found.");
536 }
537 return status;
538}
539
Eric Laurent81784c32012-11-19 14:55:58 -0800540void AudioFlinger::ThreadBase::exit()
541{
542 ALOGV("ThreadBase::exit");
543 // do any cleanup required for exit to succeed
544 preExit();
545 {
546 // This lock prevents the following race in thread (uniprocessor for illustration):
547 // if (!exitPending()) {
548 // // context switch from here to exit()
549 // // exit() calls requestExit(), what exitPending() observes
550 // // exit() calls signal(), which is dropped since no waiters
551 // // context switch back from exit() to here
552 // mWaitWorkCV.wait(...);
553 // // now thread is hung
554 // }
555 AutoMutex lock(mLock);
556 requestExit();
557 mWaitWorkCV.broadcast();
558 }
559 // When Thread::requestExitAndWait is made virtual and this method is renamed to
560 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
561 requestExitAndWait();
562}
563
564status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
565{
Eric Laurent81784c32012-11-19 14:55:58 -0800566 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
567 Mutex::Autolock _l(mLock);
568
Eric Laurent10351942014-05-08 18:49:52 -0700569 return sendSetParameterConfigEvent_l(keyValuePairs);
570}
571
572// sendConfigEvent_l() must be called with ThreadBase::mLock held
573// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
574status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
575{
576 status_t status = NO_ERROR;
577
Eric Laurent72e3f392015-05-20 14:43:50 -0700578 if (event->mRequiresSystemReady && !mSystemReady) {
579 event->mWaitStatus = false;
580 mPendingConfigEvents.add(event);
581 return status;
582 }
Eric Laurent10351942014-05-08 18:49:52 -0700583 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700584 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800585 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700586 mLock.unlock();
587 {
588 Mutex::Autolock _l(event->mLock);
589 while (event->mWaitStatus) {
590 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
591 event->mStatus = TIMED_OUT;
592 event->mWaitStatus = false;
593 }
594 }
595 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800596 }
Eric Laurent10351942014-05-08 18:49:52 -0700597 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800598 return status;
599}
600
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700601void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800602{
603 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700604 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800605}
606
607// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700608void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800609{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700610 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700611 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800612}
613
Eric Laurent72e3f392015-05-20 14:43:50 -0700614void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
615{
616 Mutex::Autolock _l(mLock);
617 sendPrioConfigEvent_l(pid, tid, prio);
618}
619
Eric Laurent81784c32012-11-19 14:55:58 -0800620// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
621void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
622{
Eric Laurent10351942014-05-08 18:49:52 -0700623 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
624 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800625}
626
Eric Laurent10351942014-05-08 18:49:52 -0700627// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
628status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800629{
Andy Hung2ddee192015-12-18 17:34:44 -0800630 sp<ConfigEvent> configEvent;
631 AudioParameter param(keyValuePair);
632 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700633 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800634 setMasterMono_l(value != 0);
635 if (param.size() == 1) {
636 return NO_ERROR; // should be a solo parameter - we don't pass down
637 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700638 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800639 configEvent = new SetParameterConfigEvent(param.toString());
640 } else {
641 configEvent = new SetParameterConfigEvent(keyValuePair);
642 }
Eric Laurent10351942014-05-08 18:49:52 -0700643 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700644}
645
Eric Laurent1c333e22014-05-20 10:48:17 -0700646status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
647 const struct audio_patch *patch,
648 audio_patch_handle_t *handle)
649{
650 Mutex::Autolock _l(mLock);
651 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
652 status_t status = sendConfigEvent_l(configEvent);
653 if (status == NO_ERROR) {
654 CreateAudioPatchConfigEventData *data =
655 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
656 *handle = data->mHandle;
657 }
658 return status;
659}
660
661status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
662 const audio_patch_handle_t handle)
663{
664 Mutex::Autolock _l(mLock);
665 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
666 return sendConfigEvent_l(configEvent);
667}
668
669
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700670// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700671void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700672{
Eric Laurent10351942014-05-08 18:49:52 -0700673 bool configChanged = false;
674
Eric Laurent81784c32012-11-19 14:55:58 -0800675 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700676 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700677 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800678 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700679 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700680 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700681 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
682 // FIXME Need to understand why this has to be done asynchronously
683 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700684 true /*asynchronous*/);
685 if (err != 0) {
686 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700687 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700688 }
689 } break;
690 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700691 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700692 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700693 } break;
694 case CFG_EVENT_SET_PARAMETER: {
695 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
696 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
697 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700698 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700699 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700700 case CFG_EVENT_CREATE_AUDIO_PATCH: {
701 CreateAudioPatchConfigEventData *data =
702 (CreateAudioPatchConfigEventData *)event->mData.get();
703 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
704 } break;
705 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
706 ReleaseAudioPatchConfigEventData *data =
707 (ReleaseAudioPatchConfigEventData *)event->mData.get();
708 event->mStatus = releaseAudioPatch_l(data->mHandle);
709 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700710 default:
Eric Laurent10351942014-05-08 18:49:52 -0700711 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700712 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800713 }
Eric Laurent10351942014-05-08 18:49:52 -0700714 {
715 Mutex::Autolock _l(event->mLock);
716 if (event->mWaitStatus) {
717 event->mWaitStatus = false;
718 event->mCond.signal();
719 }
720 }
721 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
722 }
723
724 if (configChanged) {
725 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800726 }
Eric Laurent81784c32012-11-19 14:55:58 -0800727}
728
Marco Nelissenb2208842014-02-07 14:00:50 -0800729String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
730 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700731 const audio_channel_representation_t representation =
732 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700733
734 switch (representation) {
735 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
736 if (output) {
737 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
738 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
739 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
740 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
741 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
742 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
743 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
744 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
745 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
746 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
747 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
748 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
749 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
750 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
751 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
753 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
754 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
755 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
756 } else {
757 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
758 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
759 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
760 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
761 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
762 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
763 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
764 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
765 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
766 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
767 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
768 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
769 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
770 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
771 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
772 }
773 const int len = s.length();
774 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700775 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700776 s.unlockBuffer(len - 2); // remove trailing ", "
777 }
778 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800779 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700780 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
781 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
782 return s;
783 default:
784 s.appendFormat("unknown mask, representation:%d bits:%#x",
785 representation, audio_channel_mask_get_bits(mask));
786 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800787 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800788}
789
Glenn Kasten0f11b512014-01-31 16:18:54 -0800790void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800791{
792 const size_t SIZE = 256;
793 char buffer[SIZE];
794 String8 result;
795
796 bool locked = AudioFlinger::dumpTryLock(mLock);
797 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700798 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800799 }
800
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800801 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700802 dprintf(fd, " I/O handle: %d\n", mId);
803 dprintf(fd, " TID: %d\n", getTid());
804 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700805 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700806 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700807 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700808 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700809 dprintf(fd, " Channel count: %u\n", mChannelCount);
810 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800811 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700812 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700813 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700814 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800815 size_t numConfig = mConfigEvents.size();
816 if (numConfig) {
817 for (size_t i = 0; i < numConfig; i++) {
818 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800820 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800822 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700823 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800824 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700825 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
826 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800827 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800828
829 if (locked) {
830 mLock.unlock();
831 }
832}
833
834void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
835{
836 const size_t SIZE = 256;
837 char buffer[SIZE];
838 String8 result;
839
Marco Nelissenb2208842014-02-07 14:00:50 -0800840 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000841 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800842 write(fd, buffer, strlen(buffer));
843
Marco Nelissenb2208842014-02-07 14:00:50 -0800844 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800845 sp<EffectChain> chain = mEffectChains[i];
846 if (chain != 0) {
847 chain->dump(fd, args);
848 }
849 }
850}
851
Andy Hungdae27702016-10-31 14:01:16 -0700852void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800853{
854 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700855 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800856}
857
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100858String16 AudioFlinger::ThreadBase::getWakeLockTag()
859{
860 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800861 case MIXER:
862 return String16("AudioMix");
863 case DIRECT:
864 return String16("AudioDirectOut");
865 case DUPLICATING:
866 return String16("AudioDup");
867 case RECORD:
868 return String16("AudioIn");
869 case OFFLOAD:
870 return String16("AudioOffload");
871 default:
872 ALOG_ASSERT(false);
873 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100874 }
875}
876
Andy Hungdae27702016-10-31 14:01:16 -0700877void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800878{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800879 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800880 if (mPowerManager != 0) {
881 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700882 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
883 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700884 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100885 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700886 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700887 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800888 if (status == NO_ERROR) {
889 mWakeLockToken = binder;
890 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800891 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800892 }
Wei Jia3f273d12015-11-24 09:06:49 -0800893
Andy Hung3f0c9022016-01-15 17:49:46 -0800894 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800895 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
896 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800897}
898
899void AudioFlinger::ThreadBase::releaseWakeLock()
900{
901 Mutex::Autolock _l(mLock);
902 releaseWakeLock_l();
903}
904
905void AudioFlinger::ThreadBase::releaseWakeLock_l()
906{
Andy Hung3f0c9022016-01-15 17:49:46 -0800907 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800908 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800909 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700911 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
912 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800913 }
914 mWakeLockToken.clear();
915 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800916}
917
918void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700919 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800920 // use checkService() to avoid blocking if power service is not up yet
921 sp<IBinder> binder =
922 defaultServiceManager()->checkService(String16("power"));
923 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800924 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800925 } else {
926 mPowerManager = interface_cast<IPowerManager>(binder);
927 binder->linkToDeath(mDeathRecipient);
928 }
929 }
930}
931
Andy Hungd01b0f12016-11-07 16:10:30 -0800932void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800933 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700934
935#if !LOG_NDEBUG
936 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800937 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700938 s << uid << " ";
939 }
940 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
941#endif
942
Andy Hung438e7572015-12-14 15:51:17 -0800943 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
944 if (mSystemReady) {
945 ALOGE("no wake lock to update, but system ready!");
946 } else {
947 ALOGW("no wake lock to update, system not ready yet");
948 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800949 return;
950 }
951 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800952 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
953 status_t status = mPowerManager->updateWakeLockUids(
954 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
955 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800956 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957 }
958}
959
Eric Laurent81784c32012-11-19 14:55:58 -0800960void AudioFlinger::ThreadBase::clearPowerManager()
961{
962 Mutex::Autolock _l(mLock);
963 releaseWakeLock_l();
964 mPowerManager.clear();
965}
966
Glenn Kasten0f11b512014-01-31 16:18:54 -0800967void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800968{
969 sp<ThreadBase> thread = mThread.promote();
970 if (thread != 0) {
971 thread->clearPowerManager();
972 }
973 ALOGW("power manager service died !!!");
974}
975
976void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800977 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800978{
979 Mutex::Autolock _l(mLock);
980 setEffectSuspended_l(type, suspend, sessionId);
981}
982
983void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800984 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800985{
986 sp<EffectChain> chain = getEffectChain_l(sessionId);
987 if (chain != 0) {
988 if (type != NULL) {
989 chain->setEffectSuspended_l(type, suspend);
990 } else {
991 chain->setEffectSuspendedAll_l(suspend);
992 }
993 }
994
995 updateSuspendedSessions_l(type, suspend, sessionId);
996}
997
998void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
999{
1000 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1001 if (index < 0) {
1002 return;
1003 }
1004
1005 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1006 mSuspendedSessions.valueAt(index);
1007
1008 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001009 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001010 for (int j = 0; j < desc->mRefCount; j++) {
1011 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1012 chain->setEffectSuspendedAll_l(true);
1013 } else {
1014 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1015 desc->mType.timeLow);
1016 chain->setEffectSuspended_l(&desc->mType, true);
1017 }
1018 }
1019 }
1020}
1021
1022void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1023 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001024 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001025{
1026 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1027
1028 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1029
1030 if (suspend) {
1031 if (index >= 0) {
1032 sessionEffects = mSuspendedSessions.valueAt(index);
1033 } else {
1034 mSuspendedSessions.add(sessionId, sessionEffects);
1035 }
1036 } else {
1037 if (index < 0) {
1038 return;
1039 }
1040 sessionEffects = mSuspendedSessions.valueAt(index);
1041 }
1042
1043
1044 int key = EffectChain::kKeyForSuspendAll;
1045 if (type != NULL) {
1046 key = type->timeLow;
1047 }
1048 index = sessionEffects.indexOfKey(key);
1049
1050 sp<SuspendedSessionDesc> desc;
1051 if (suspend) {
1052 if (index >= 0) {
1053 desc = sessionEffects.valueAt(index);
1054 } else {
1055 desc = new SuspendedSessionDesc();
1056 if (type != NULL) {
1057 desc->mType = *type;
1058 }
1059 sessionEffects.add(key, desc);
1060 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1061 }
1062 desc->mRefCount++;
1063 } else {
1064 if (index < 0) {
1065 return;
1066 }
1067 desc = sessionEffects.valueAt(index);
1068 if (--desc->mRefCount == 0) {
1069 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1070 sessionEffects.removeItemsAt(index);
1071 if (sessionEffects.isEmpty()) {
1072 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1073 sessionId);
1074 mSuspendedSessions.removeItem(sessionId);
1075 }
1076 }
1077 }
1078 if (!sessionEffects.isEmpty()) {
1079 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1080 }
1081}
1082
1083void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1084 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001085 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001086{
1087 Mutex::Autolock _l(mLock);
1088 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1089}
1090
1091void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1092 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001093 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001094{
1095 if (mType != RECORD) {
1096 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1097 // another session. This gives the priority to well behaved effect control panels
1098 // and applications not using global effects.
1099 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1100 // global effects
1101 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1102 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1103 }
1104 }
1105
1106 sp<EffectChain> chain = getEffectChain_l(sessionId);
1107 if (chain != 0) {
1108 chain->checkSuspendOnEffectEnabled(effect, enabled);
1109 }
1110}
1111
Eric Laurent4c415062016-06-17 16:14:16 -07001112// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1113status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1114 const effect_descriptor_t *desc, audio_session_t sessionId)
1115{
1116 // No global effect sessions on record threads
1117 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1118 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1119 desc->name, mThreadName);
1120 return BAD_VALUE;
1121 }
1122 // only pre processing effects on record thread
1123 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1124 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1125 desc->name, mThreadName);
1126 return BAD_VALUE;
1127 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001128
1129 // always allow effects without processing load or latency
1130 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1131 return NO_ERROR;
1132 }
1133
Eric Laurent4c415062016-06-17 16:14:16 -07001134 audio_input_flags_t flags = mInput->flags;
1135 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1136 if (flags & AUDIO_INPUT_FLAG_RAW) {
1137 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1138 desc->name, mThreadName);
1139 return BAD_VALUE;
1140 }
1141 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1142 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1143 desc->name, mThreadName);
1144 return BAD_VALUE;
1145 }
1146 }
1147 return NO_ERROR;
1148}
1149
1150// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1151status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1152 const effect_descriptor_t *desc, audio_session_t sessionId)
1153{
1154 // no preprocessing on playback threads
1155 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1156 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1157 " thread %s", desc->name, mThreadName);
1158 return BAD_VALUE;
1159 }
1160
1161 switch (mType) {
1162 case MIXER: {
1163 // Reject any effect on mixer multichannel sinks.
1164 // TODO: fix both format and multichannel issues with effects.
1165 if (mChannelCount != FCC_2) {
1166 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1167 " thread %s", desc->name, mChannelCount, mThreadName);
1168 return BAD_VALUE;
1169 }
1170 audio_output_flags_t flags = mOutput->flags;
1171 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1172 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1173 // global effects are applied only to non fast tracks if they are SW
1174 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1175 break;
1176 }
1177 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1178 // only post processing on output stage session
1179 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1180 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1181 " on output stage session", desc->name);
1182 return BAD_VALUE;
1183 }
1184 } else {
1185 // no restriction on effects applied on non fast tracks
1186 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1187 break;
1188 }
1189 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001190
1191 // always allow effects without processing load or latency
1192 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1193 break;
1194 }
Eric Laurent4c415062016-06-17 16:14:16 -07001195 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1196 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1197 desc->name);
1198 return BAD_VALUE;
1199 }
1200 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1201 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1202 " in fast mode", desc->name);
1203 return BAD_VALUE;
1204 }
1205 }
1206 } break;
1207 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001208 // nothing actionable on offload threads, if the effect:
1209 // - is offloadable: the effect can be created
1210 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1211 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001212 break;
1213 case DIRECT:
1214 // Reject any effect on Direct output threads for now, since the format of
1215 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1216 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1217 desc->name, mThreadName);
1218 return BAD_VALUE;
1219 case DUPLICATING:
1220 // Reject any effect on mixer multichannel sinks.
1221 // TODO: fix both format and multichannel issues with effects.
1222 if (mChannelCount != FCC_2) {
1223 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1224 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1225 return BAD_VALUE;
1226 }
1227 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1228 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1229 " thread %s", desc->name, mThreadName);
1230 return BAD_VALUE;
1231 }
1232 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1233 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1234 " DUPLICATING thread %s", desc->name, mThreadName);
1235 return BAD_VALUE;
1236 }
1237 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1238 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1239 " DUPLICATING thread %s", desc->name, mThreadName);
1240 return BAD_VALUE;
1241 }
1242 break;
1243 default:
1244 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1245 }
1246
1247 return NO_ERROR;
1248}
1249
Eric Laurent81784c32012-11-19 14:55:58 -08001250// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1251sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1252 const sp<AudioFlinger::Client>& client,
1253 const sp<IEffectClient>& effectClient,
1254 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001255 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001256 effect_descriptor_t *desc,
1257 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001258 status_t *status,
1259 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001260{
1261 sp<EffectModule> effect;
1262 sp<EffectHandle> handle;
1263 status_t lStatus;
1264 sp<EffectChain> chain;
1265 bool chainCreated = false;
1266 bool effectCreated = false;
1267 bool effectRegistered = false;
1268
1269 lStatus = initCheck();
1270 if (lStatus != NO_ERROR) {
1271 ALOGW("createEffect_l() Audio driver not initialized.");
1272 goto Exit;
1273 }
1274
Eric Laurent81784c32012-11-19 14:55:58 -08001275 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1276
1277 { // scope for mLock
1278 Mutex::Autolock _l(mLock);
1279
Eric Laurent4c415062016-06-17 16:14:16 -07001280 lStatus = checkEffectCompatibility_l(desc, sessionId);
1281 if (lStatus != NO_ERROR) {
1282 goto Exit;
1283 }
1284
Eric Laurent81784c32012-11-19 14:55:58 -08001285 // check for existing effect chain with the requested audio session
1286 chain = getEffectChain_l(sessionId);
1287 if (chain == 0) {
1288 // create a new chain for this session
1289 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1290 chain = new EffectChain(this, sessionId);
1291 addEffectChain_l(chain);
1292 chain->setStrategy(getStrategyForSession_l(sessionId));
1293 chainCreated = true;
1294 } else {
1295 effect = chain->getEffectFromDesc_l(desc);
1296 }
1297
1298 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1299
1300 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001301 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001302 // Check CPU and memory usage
1303 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1304 if (lStatus != NO_ERROR) {
1305 goto Exit;
1306 }
1307 effectRegistered = true;
1308 // create a new effect module if none present in the chain
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001309 lStatus = chain->createEffect_l(effect, this, desc, id, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001310 if (lStatus != NO_ERROR) {
1311 goto Exit;
1312 }
1313 effectCreated = true;
1314
1315 effect->setDevice(mOutDevice);
1316 effect->setDevice(mInDevice);
1317 effect->setMode(mAudioFlinger->getMode());
1318 effect->setAudioSource(mAudioSource);
1319 }
1320 // create effect handle and connect it to effect module
1321 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001322 lStatus = handle->initCheck();
1323 if (lStatus == OK) {
1324 lStatus = effect->addHandle(handle.get());
1325 }
Eric Laurent81784c32012-11-19 14:55:58 -08001326 if (enabled != NULL) {
1327 *enabled = (int)effect->isEnabled();
1328 }
1329 }
1330
1331Exit:
1332 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1333 Mutex::Autolock _l(mLock);
1334 if (effectCreated) {
1335 chain->removeEffect_l(effect);
1336 }
1337 if (effectRegistered) {
1338 AudioSystem::unregisterEffect(effect->id());
1339 }
1340 if (chainCreated) {
1341 removeEffectChain_l(chain);
1342 }
1343 handle.clear();
1344 }
1345
Glenn Kasten9156ef32013-08-06 15:39:08 -07001346 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001347 return handle;
1348}
1349
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001350void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1351 bool unpinIfLast)
1352{
1353 bool remove = false;
1354 sp<EffectModule> effect;
1355 {
1356 Mutex::Autolock _l(mLock);
1357
1358 effect = handle->effect().promote();
1359 if (effect == 0) {
1360 return;
1361 }
1362 // restore suspended effects if the disconnected handle was enabled and the last one.
1363 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1364 if (remove) {
1365 removeEffect_l(effect, true);
1366 }
1367 }
1368 if (remove) {
1369 mAudioFlinger->updateOrphanEffectChains(effect);
1370 AudioSystem::unregisterEffect(effect->id());
1371 if (handle->enabled()) {
1372 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1373 }
1374 }
1375}
1376
Glenn Kastend848eb42016-03-08 13:42:11 -08001377sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1378 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001379{
1380 Mutex::Autolock _l(mLock);
1381 return getEffect_l(sessionId, effectId);
1382}
1383
Glenn Kastend848eb42016-03-08 13:42:11 -08001384sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1385 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001386{
1387 sp<EffectChain> chain = getEffectChain_l(sessionId);
1388 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1389}
1390
1391// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1392// PlaybackThread::mLock held
1393status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1394{
1395 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001396 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001397 sp<EffectChain> chain = getEffectChain_l(sessionId);
1398 bool chainCreated = false;
1399
Eric Laurent5baf2af2013-09-12 17:37:00 -07001400 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1401 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1402 this, effect->desc().name, effect->desc().flags);
1403
Eric Laurent81784c32012-11-19 14:55:58 -08001404 if (chain == 0) {
1405 // create a new chain for this session
1406 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1407 chain = new EffectChain(this, sessionId);
1408 addEffectChain_l(chain);
1409 chain->setStrategy(getStrategyForSession_l(sessionId));
1410 chainCreated = true;
1411 }
1412 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1413
1414 if (chain->getEffectFromId_l(effect->id()) != 0) {
1415 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1416 this, effect->desc().name, chain.get());
1417 return BAD_VALUE;
1418 }
1419
Eric Laurent5baf2af2013-09-12 17:37:00 -07001420 effect->setOffloaded(mType == OFFLOAD, mId);
1421
Eric Laurent81784c32012-11-19 14:55:58 -08001422 status_t status = chain->addEffect_l(effect);
1423 if (status != NO_ERROR) {
1424 if (chainCreated) {
1425 removeEffectChain_l(chain);
1426 }
1427 return status;
1428 }
1429
1430 effect->setDevice(mOutDevice);
1431 effect->setDevice(mInDevice);
1432 effect->setMode(mAudioFlinger->getMode());
1433 effect->setAudioSource(mAudioSource);
1434 return NO_ERROR;
1435}
1436
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001437void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001438
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001439 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001440 effect_descriptor_t desc = effect->desc();
1441 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1442 detachAuxEffect_l(effect->id());
1443 }
1444
1445 sp<EffectChain> chain = effect->chain().promote();
1446 if (chain != 0) {
1447 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001448 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001449 removeEffectChain_l(chain);
1450 }
1451 } else {
1452 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1453 }
1454}
1455
1456void AudioFlinger::ThreadBase::lockEffectChains_l(
1457 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1458{
1459 effectChains = mEffectChains;
1460 for (size_t i = 0; i < mEffectChains.size(); i++) {
1461 mEffectChains[i]->lock();
1462 }
1463}
1464
1465void AudioFlinger::ThreadBase::unlockEffectChains(
1466 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1467{
1468 for (size_t i = 0; i < effectChains.size(); i++) {
1469 effectChains[i]->unlock();
1470 }
1471}
1472
Glenn Kastend848eb42016-03-08 13:42:11 -08001473sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001474{
1475 Mutex::Autolock _l(mLock);
1476 return getEffectChain_l(sessionId);
1477}
1478
Glenn Kastend848eb42016-03-08 13:42:11 -08001479sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1480 const
Eric Laurent81784c32012-11-19 14:55:58 -08001481{
1482 size_t size = mEffectChains.size();
1483 for (size_t i = 0; i < size; i++) {
1484 if (mEffectChains[i]->sessionId() == sessionId) {
1485 return mEffectChains[i];
1486 }
1487 }
1488 return 0;
1489}
1490
1491void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1492{
1493 Mutex::Autolock _l(mLock);
1494 size_t size = mEffectChains.size();
1495 for (size_t i = 0; i < size; i++) {
1496 mEffectChains[i]->setMode_l(mode);
1497 }
1498}
1499
Eric Laurent83b88082014-06-20 18:31:16 -07001500void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1501{
1502 config->type = AUDIO_PORT_TYPE_MIX;
1503 config->ext.mix.handle = mId;
1504 config->sample_rate = mSampleRate;
1505 config->format = mFormat;
1506 config->channel_mask = mChannelMask;
1507 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1508 AUDIO_PORT_CONFIG_FORMAT;
1509}
1510
Eric Laurent72e3f392015-05-20 14:43:50 -07001511void AudioFlinger::ThreadBase::systemReady()
1512{
1513 Mutex::Autolock _l(mLock);
1514 if (mSystemReady) {
1515 return;
1516 }
1517 mSystemReady = true;
1518
1519 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1520 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1521 }
1522 mPendingConfigEvents.clear();
1523}
1524
Andy Hungdae27702016-10-31 14:01:16 -07001525template <typename T>
1526ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1527 ssize_t index = mActiveTracks.indexOf(track);
1528 if (index >= 0) {
1529 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1530 return index;
1531 }
1532 mActiveTracksGeneration++;
1533 mLatestActiveTrack = track;
1534 ++mBatteryCounter[track->uid()].second;
1535 return mActiveTracks.add(track);
1536}
1537
1538template <typename T>
1539ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1540 ssize_t index = mActiveTracks.remove(track);
1541 if (index < 0) {
1542 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1543 return index;
1544 }
1545 mActiveTracksGeneration++;
1546 --mBatteryCounter[track->uid()].second;
1547 // mLatestActiveTrack is not cleared even if is the same as track.
1548 return index;
1549}
1550
1551template <typename T>
1552void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1553 for (const sp<T> &track : mActiveTracks) {
1554 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1555 }
1556 mLastActiveTracksGeneration = mActiveTracksGeneration;
1557 mActiveTracks.clear();
1558 mLatestActiveTrack.clear();
1559 mBatteryCounter.clear();
1560}
1561
1562template <typename T>
1563void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1564 sp<ThreadBase> thread, bool force) {
1565 // Updates ActiveTracks client uids to the thread wakelock.
1566 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1567 thread->updateWakeLockUids_l(getWakeLockUids());
1568 mLastActiveTracksGeneration = mActiveTracksGeneration;
1569 }
1570
1571 // Updates BatteryNotifier uids
1572 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1573 const uid_t uid = it->first;
1574 ssize_t &previous = it->second.first;
1575 ssize_t &current = it->second.second;
1576 if (current > 0) {
1577 if (previous == 0) {
1578 BatteryNotifier::getInstance().noteStartAudio(uid);
1579 }
1580 previous = current;
1581 ++it;
1582 } else if (current == 0) {
1583 if (previous > 0) {
1584 BatteryNotifier::getInstance().noteStopAudio(uid);
1585 }
1586 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1587 } else /* (current < 0) */ {
1588 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1589 }
1590 }
1591}
Eric Laurent83b88082014-06-20 18:31:16 -07001592
Eric Laurent81784c32012-11-19 14:55:58 -08001593// ----------------------------------------------------------------------------
1594// Playback
1595// ----------------------------------------------------------------------------
1596
1597AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1598 AudioStreamOut* output,
1599 audio_io_handle_t id,
1600 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001601 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001602 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001603 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001604 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001605 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001606 mMixerBuffer(NULL),
1607 mMixerBufferSize(0),
1608 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1609 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001610 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001611 mEffectBuffer(NULL),
1612 mEffectBufferSize(0),
1613 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1614 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001615 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001616 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001617 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001618 // mStreamTypes[] initialized in constructor body
1619 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001620 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001621 mMixerStatus(MIXER_IDLE),
1622 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001623 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001624 mBytesRemaining(0),
1625 mCurrentWriteLength(0),
1626 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001627 mWriteAckSequence(0),
1628 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001629 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001630 mScreenState(AudioFlinger::mScreenState),
1631 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001632 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001633 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001634{
Glenn Kastend7dca052015-03-05 16:05:54 -08001635 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1636 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001637
1638 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1639 // it would be safer to explicitly pass initial masterVolume/masterMute as
1640 // parameter.
1641 //
1642 // If the HAL we are using has support for master volume or master mute,
1643 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1644 // and the mute set to false).
1645 mMasterVolume = audioFlinger->masterVolume_l();
1646 mMasterMute = audioFlinger->masterMute_l();
1647 if (mOutput && mOutput->audioHwDev) {
1648 if (mOutput->audioHwDev->canSetMasterVolume()) {
1649 mMasterVolume = 1.0;
1650 }
1651
1652 if (mOutput->audioHwDev->canSetMasterMute()) {
1653 mMasterMute = false;
1654 }
1655 }
1656
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001657 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001658
Eric Laurent223fd5c2014-11-11 13:43:36 -08001659 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001660 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001661 stream = (audio_stream_type_t) (stream + 1)) {
1662 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1663 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1664 }
Eric Laurent81784c32012-11-19 14:55:58 -08001665}
1666
1667AudioFlinger::PlaybackThread::~PlaybackThread()
1668{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001669 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001670 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001671 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001672 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001673}
1674
1675void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1676{
1677 dumpInternals(fd, args);
1678 dumpTracks(fd, args);
1679 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001680 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001681}
1682
Glenn Kasten0f11b512014-01-31 16:18:54 -08001683void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001684{
1685 const size_t SIZE = 256;
1686 char buffer[SIZE];
1687 String8 result;
1688
Marco Nelissenb2208842014-02-07 14:00:50 -08001689 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001690 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1691 const stream_type_t *st = &mStreamTypes[i];
1692 if (i > 0) {
1693 result.appendFormat(", ");
1694 }
1695 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1696 if (st->mute) {
1697 result.append("M");
1698 }
1699 }
1700 result.append("\n");
1701 write(fd, result.string(), result.length());
1702 result.clear();
1703
Eric Laurent81784c32012-11-19 14:55:58 -08001704 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1705 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001706 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001707 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001708
1709 size_t numtracks = mTracks.size();
1710 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001711 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001712 size_t numactiveseen = 0;
1713 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001714 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001715 Track::appendDumpHeader(result);
1716 for (size_t i = 0; i < numtracks; ++i) {
1717 sp<Track> track = mTracks[i];
1718 if (track != 0) {
1719 bool active = mActiveTracks.indexOf(track) >= 0;
1720 if (active) {
1721 numactiveseen++;
1722 }
1723 track->dump(buffer, SIZE, active);
1724 result.append(buffer);
1725 }
1726 }
1727 } else {
1728 result.append("\n");
1729 }
1730 if (numactiveseen != numactive) {
1731 // some tracks in the active list were not in the tracks list
1732 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1733 " not in the track list\n");
1734 result.append(buffer);
1735 Track::appendDumpHeader(result);
1736 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001737 sp<Track> track = mActiveTracks[i];
1738 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001739 track->dump(buffer, SIZE, true);
1740 result.append(buffer);
1741 }
1742 }
1743 }
1744
1745 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001746}
1747
1748void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1749{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001750 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001751
1752 dumpBase(fd, args);
1753
Elliott Hughes87cebad2014-05-22 10:14:43 -07001754 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001755 dprintf(fd, " Last write occurred (msecs): %llu\n",
1756 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001757 dprintf(fd, " Total writes: %d\n", mNumWrites);
1758 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1759 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1760 dprintf(fd, " Suspend count: %d\n", mSuspended);
1761 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1762 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1763 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1764 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001765 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001766 AudioStreamOut *output = mOutput;
1767 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001768 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1769 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001770 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1771 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1772 if (mPipeSink.get() != nullptr) {
1773 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1774 }
1775 if (output != nullptr) {
1776 dprintf(fd, " Hal stream dump:\n");
1777 (void)output->stream->dump(fd);
1778 }
Eric Laurent81784c32012-11-19 14:55:58 -08001779}
1780
1781// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001782
1783void AudioFlinger::PlaybackThread::onFirstRef()
1784{
Glenn Kastend7dca052015-03-05 16:05:54 -08001785 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001786}
1787
1788// ThreadBase virtuals
1789void AudioFlinger::PlaybackThread::preExit()
1790{
1791 ALOGV(" preExit()");
1792 // FIXME this is using hard-coded strings but in the future, this functionality will be
1793 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001794 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1795 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001796}
1797
1798// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1799sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1800 const sp<AudioFlinger::Client>& client,
1801 audio_stream_type_t streamType,
1802 uint32_t sampleRate,
1803 audio_format_t format,
1804 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001805 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001806 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001807 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001808 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001809 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001810 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001811 status_t *status,
1812 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001813{
Glenn Kasten74935e42013-12-19 08:56:45 -08001814 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001815 sp<Track> track;
1816 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001817 audio_output_flags_t outputFlags = mOutput->flags;
1818
1819 // special case for FAST flag considered OK if fast mixer is present
1820 if (hasFastMixer()) {
1821 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1822 }
1823
1824 // Check if requested flags are compatible with output stream flags
1825 if ((*flags & outputFlags) != *flags) {
1826 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1827 *flags, outputFlags);
1828 *flags = (audio_output_flags_t)(*flags & outputFlags);
1829 }
Eric Laurent81784c32012-11-19 14:55:58 -08001830
Eric Laurent81784c32012-11-19 14:55:58 -08001831 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001832 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001833 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001834 // PCM data
1835 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001836 // TODO: extract as a data library function that checks that a computationally
1837 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001838 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001839 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1840 (channelMask == AUDIO_CHANNEL_OUT_MONO
1841 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001842 // hardware sample rate
1843 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001844 // normal mixer has an associated fast mixer
1845 hasFastMixer() &&
1846 // there are sufficient fast track slots available
1847 (mFastTrackAvailMask != 0)
1848 // FIXME test that MixerThread for this fast track has a capable output HAL
1849 // FIXME add a permission test also?
1850 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001851 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1852 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001853 // read the fast track multiplier property the first time it is needed
1854 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1855 if (ok != 0) {
1856 ALOGE("%s pthread_once failed: %d", __func__, ok);
1857 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001858 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001859 }
Eric Laurent4c415062016-06-17 16:14:16 -07001860
1861 // check compatibility with audio effects.
1862 { // scope for mLock
1863 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001864 for (audio_session_t session : {
1865 AUDIO_SESSION_OUTPUT_STAGE,
1866 AUDIO_SESSION_OUTPUT_MIX,
1867 sessionId,
1868 }) {
1869 sp<EffectChain> chain = getEffectChain_l(session);
1870 if (chain.get() != nullptr) {
1871 audio_output_flags_t old = *flags;
1872 chain->checkOutputFlagCompatibility(flags);
1873 if (old != *flags) {
1874 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1875 (int)session, (int)old, (int)*flags);
1876 }
Eric Laurent4c415062016-06-17 16:14:16 -07001877 }
1878 }
1879 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001880 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001881 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1882 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001883 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001884 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1885 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001886 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001887 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001888 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001889 audio_is_linear_pcm(format),
1890 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001891 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001892 }
1893 }
1894 // For normal PCM streaming tracks, update minimum frame count.
1895 // For compatibility with AudioTrack calculation, buffer depth is forced
1896 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1897 // This is probably too conservative, but legacy application code may depend on it.
1898 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001899 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001900 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001901 // this must match AudioTrack.cpp calculateMinFrameCount().
1902 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001903 uint32_t latencyMs = 0;
1904 lStatus = mOutput->stream->getLatency(&latencyMs);
1905 if (lStatus != OK) {
1906 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1907 goto Exit;
1908 }
Eric Laurent81784c32012-11-19 14:55:58 -08001909 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1910 if (minBufCount < 2) {
1911 minBufCount = 2;
1912 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001913 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1914 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001915 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001916 minBufCount * sourceFramesNeededWithTimestretch(
1917 sampleRate, mNormalFrameCount,
1918 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001919 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001920 frameCount = minFrameCount;
1921 }
Eric Laurent81784c32012-11-19 14:55:58 -08001922 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001923 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001924
Glenn Kastenc3df8382014-03-13 15:05:25 -07001925 switch (mType) {
1926
1927 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001928 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001929 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001930 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1931 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001932 sampleRate, format, channelMask, mOutput, mFormat);
1933 lStatus = BAD_VALUE;
1934 goto Exit;
1935 }
1936 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001937 break;
1938
1939 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001940 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001941 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1942 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001943 sampleRate, format, channelMask, mOutput, mFormat);
1944 lStatus = BAD_VALUE;
1945 goto Exit;
1946 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001947 break;
1948
1949 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001950 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001951 ALOGE("createTrack_l() Bad parameter: format %#x \""
1952 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001953 format, mOutput, mFormat);
1954 lStatus = BAD_VALUE;
1955 goto Exit;
1956 }
Andy Hungcd044842014-08-07 11:04:34 -07001957 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001958 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1959 lStatus = BAD_VALUE;
1960 goto Exit;
1961 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001962 break;
1963
Eric Laurent81784c32012-11-19 14:55:58 -08001964 }
1965
1966 lStatus = initCheck();
1967 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001968 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001969 goto Exit;
1970 }
1971
1972 { // scope for mLock
1973 Mutex::Autolock _l(mLock);
1974
1975 // all tracks in same audio session must share the same routing strategy otherwise
1976 // conflicts will happen when tracks are moved from one output to another by audio policy
1977 // manager
1978 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1979 for (size_t i = 0; i < mTracks.size(); ++i) {
1980 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001981 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001982 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1983 if (sessionId == t->sessionId() && strategy != actual) {
1984 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1985 strategy, actual);
1986 lStatus = BAD_VALUE;
1987 goto Exit;
1988 }
1989 }
1990 }
1991
Glenn Kastend79072e2016-01-06 08:41:20 -08001992 track = new Track(this, client, streamType, sampleRate, format,
1993 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001994 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07001995
Glenn Kasten03003332013-08-06 15:40:54 -07001996 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1997 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001998 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001999 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002000 goto Exit;
2001 }
2002 mTracks.add(track);
2003
2004 sp<EffectChain> chain = getEffectChain_l(sessionId);
2005 if (chain != 0) {
2006 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2007 track->setMainBuffer(chain->inBuffer());
2008 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2009 chain->incTrackCnt();
2010 }
2011
Eric Laurent05067782016-06-01 18:27:28 -07002012 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002013 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2014 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2015 // so ask activity manager to do this on our behalf
2016 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2017 }
2018 }
2019
2020 lStatus = NO_ERROR;
2021
2022Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002023 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002024 return track;
2025}
2026
2027uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2028{
2029 return latency;
2030}
2031
2032uint32_t AudioFlinger::PlaybackThread::latency() const
2033{
2034 Mutex::Autolock _l(mLock);
2035 return latency_l();
2036}
2037uint32_t AudioFlinger::PlaybackThread::latency_l() const
2038{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002039 uint32_t latency;
2040 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2041 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002042 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002043 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002044}
2045
2046void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2047{
2048 Mutex::Autolock _l(mLock);
2049 // Don't apply master volume in SW if our HAL can do it for us.
2050 if (mOutput && mOutput->audioHwDev &&
2051 mOutput->audioHwDev->canSetMasterVolume()) {
2052 mMasterVolume = 1.0;
2053 } else {
2054 mMasterVolume = value;
2055 }
2056}
2057
2058void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2059{
2060 Mutex::Autolock _l(mLock);
2061 // Don't apply master mute in SW if our HAL can do it for us.
2062 if (mOutput && mOutput->audioHwDev &&
2063 mOutput->audioHwDev->canSetMasterMute()) {
2064 mMasterMute = false;
2065 } else {
2066 mMasterMute = muted;
2067 }
2068}
2069
2070void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2071{
2072 Mutex::Autolock _l(mLock);
2073 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002074 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002075}
2076
2077void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2078{
2079 Mutex::Autolock _l(mLock);
2080 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002081 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002082}
2083
2084float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2085{
2086 Mutex::Autolock _l(mLock);
2087 return mStreamTypes[stream].volume;
2088}
2089
2090// addTrack_l() must be called with ThreadBase::mLock held
2091status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2092{
2093 status_t status = ALREADY_EXISTS;
2094
Eric Laurent81784c32012-11-19 14:55:58 -08002095 if (mActiveTracks.indexOf(track) < 0) {
2096 // the track is newly added, make sure it fills up all its
2097 // buffers before playing. This is to ensure the client will
2098 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002099 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002100 TrackBase::track_state state = track->mState;
2101 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002102 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002103 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002104 mLock.lock();
2105 // abort track was stopped/paused while we released the lock
2106 if (state != track->mState) {
2107 if (status == NO_ERROR) {
2108 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002109 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002110 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002111 mLock.lock();
2112 }
2113 return INVALID_OPERATION;
2114 }
2115 // abort if start is rejected by audio policy manager
2116 if (status != NO_ERROR) {
2117 return PERMISSION_DENIED;
2118 }
2119#ifdef ADD_BATTERY_DATA
2120 // to track the speaker usage
2121 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2122#endif
2123 }
2124
Eric Laurent51716182016-02-29 18:00:56 -08002125 // set retry count for buffer fill
2126 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002127 if (track->isStopping_1()) {
2128 track->mRetryCount = kMaxTrackStopRetriesOffload;
2129 } else {
2130 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2131 }
2132 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002133 } else {
2134 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002135 track->mFillingUpStatus =
2136 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002137 }
2138
Eric Laurent81784c32012-11-19 14:55:58 -08002139 track->mResetDone = false;
2140 track->mPresentationCompleteFrames = 0;
2141 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002142 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2143 if (chain != 0) {
2144 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2145 track->sessionId());
2146 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002147 }
2148
Andy Hung2148bf02016-11-28 19:01:02 -08002149 char buffer[256];
2150 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2151 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2152
Eric Laurent81784c32012-11-19 14:55:58 -08002153 status = NO_ERROR;
2154 }
2155
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002156 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002157 return status;
2158}
2159
Eric Laurentbfb1b832013-01-07 09:53:42 -08002160bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002161{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002163 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2165 track->mState = TrackBase::STOPPED;
2166 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002167 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002168 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002170 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002171
2172 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002173}
2174
2175void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2176{
2177 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002178
2179 char buffer[256];
2180 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2181 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2182
Eric Laurent81784c32012-11-19 14:55:58 -08002183 mTracks.remove(track);
2184 deleteTrackName_l(track->name());
2185 // redundant as track is about to be destroyed, for dumpsys only
2186 track->mName = -1;
2187 if (track->isFastTrack()) {
2188 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002189 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002190 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2191 mFastTrackAvailMask |= 1 << index;
2192 // redundant as track is about to be destroyed, for dumpsys only
2193 track->mFastIndex = -1;
2194 }
2195 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2196 if (chain != 0) {
2197 chain->decTrackCnt();
2198 }
2199}
2200
Eric Laurentede6c3b2013-09-19 14:37:46 -07002201void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002202{
2203 // Thread could be blocked waiting for async
2204 // so signal it to handle state changes immediately
2205 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2206 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2207 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002208 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002209}
2210
Eric Laurent81784c32012-11-19 14:55:58 -08002211String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2212{
Eric Laurent81784c32012-11-19 14:55:58 -08002213 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002214 String8 out_s8;
2215 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2216 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002217 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002218 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002219}
2220
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002221void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002222 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2223 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002224
Eric Laurent73e26b62015-04-27 16:55:58 -07002225 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002226
2227 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002228 case AUDIO_OUTPUT_OPENED:
2229 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002230 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002231 desc->mChannelMask = mChannelMask;
2232 desc->mSamplingRate = mSampleRate;
2233 desc->mFormat = mFormat;
2234 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002235 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002236 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002237 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002238 break;
2239
Eric Laurent73e26b62015-04-27 16:55:58 -07002240 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002241 default:
2242 break;
2243 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002244 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002245}
2246
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002247void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002248{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002249 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002250}
2251
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002252void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002253{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002254 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002255}
2256
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002257void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002258{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002259 mCallbackThread->setAsyncError();
2260}
2261
Eric Laurent3b4529e2013-09-05 18:09:19 -07002262void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002263{
2264 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002265 // reject out of sequence requests
2266 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2267 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002268 mWaitWorkCV.signal();
2269 }
2270}
2271
Eric Laurent3b4529e2013-09-05 18:09:19 -07002272void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273{
2274 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002275 // reject out of sequence requests
2276 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2277 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278 mWaitWorkCV.signal();
2279 }
2280}
2281
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002282void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002283{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002284 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002285 mSampleRate = mOutput->getSampleRate();
2286 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002287 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002288 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002289 }
Andy Hung9a592762014-07-21 21:56:01 -07002290 if ((mType == MIXER || mType == DUPLICATING)
2291 && !isValidPcmSinkChannelMask(mChannelMask)) {
2292 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2293 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002294 }
Andy Hunge5412692014-05-16 11:25:07 -07002295 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002296
2297 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002298 status_t result = mOutput->stream->getFormat(&mHALFormat);
2299 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002300 // Get format from the shim, which will be different than the HAL format
2301 // if playing compressed audio over HDMI passthrough.
2302 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002303 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002304 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002305 }
Andy Hung6146c082014-03-18 11:56:15 -07002306 if ((mType == MIXER || mType == DUPLICATING)
2307 && !isValidPcmSinkFormat(mFormat)) {
2308 LOG_FATAL("HAL format %#x not supported for mixed output",
2309 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002310 }
Phil Burk062e67a2015-02-11 13:40:50 -08002311 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002312 result = mOutput->stream->getBufferSize(&mBufferSize);
2313 LOG_ALWAYS_FATAL_IF(result != OK,
2314 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002315 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002316 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002317 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002318 mFrameCount);
2319 }
2320
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002321 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2322 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002323 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002324 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002325 }
2326 }
2327
Eric Laurentd1f69b02014-12-15 14:33:13 -08002328 mHwSupportsPause = false;
2329 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002330 bool supportsPause = false, supportsResume = false;
2331 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2332 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002333 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002334 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002335 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002336 } else if (supportsResume) {
2337 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002338 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002339 }
2340 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002341 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2342 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2343 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002344
Andy Hungfbfc3952015-01-15 13:33:51 -08002345 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2346 // For best precision, we use float instead of the associated output
2347 // device format (typically PCM 16 bit).
2348
2349 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2350 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2351 mBufferSize = mFrameSize * mFrameCount;
2352
2353 // TODO: We currently use the associated output device channel mask and sample rate.
2354 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2355 // (if a valid mask) to avoid premature downmix.
2356 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2357 // instead of the output device sample rate to avoid loss of high frequency information.
2358 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2359 }
2360
Andy Hung09a50072014-02-27 14:30:47 -08002361 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002362 double multiplier = 1.0;
2363 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2364 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002365 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2366 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002367
Eric Laurent81784c32012-11-19 14:55:58 -08002368 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2369 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2370 maxNormalFrameCount = maxNormalFrameCount & ~15;
2371 if (maxNormalFrameCount < minNormalFrameCount) {
2372 maxNormalFrameCount = minNormalFrameCount;
2373 }
2374 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2375 if (multiplier <= 1.0) {
2376 multiplier = 1.0;
2377 } else if (multiplier <= 2.0) {
2378 if (2 * mFrameCount <= maxNormalFrameCount) {
2379 multiplier = 2.0;
2380 } else {
2381 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2382 }
2383 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002384 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002385 }
2386 }
2387 mNormalFrameCount = multiplier * mFrameCount;
2388 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002389 if (mType == MIXER || mType == DUPLICATING) {
2390 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2391 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002392 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002393 mNormalFrameCount);
2394
Andy Hung08fb1742015-05-31 23:22:10 -07002395 // Check if we want to throttle the processing to no more than 2x normal rate
2396 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002397 mThreadThrottleTimeMs = 0;
2398 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002399 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2400
Andy Hung010a1a12014-03-13 13:57:33 -07002401 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2402 // Originally this was int16_t[] array, need to remove legacy implications.
2403 free(mSinkBuffer);
2404 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002405 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2406 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2407 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002408 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002409
Andy Hung69aed5f2014-02-25 17:24:40 -08002410 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2411 // drives the output.
2412 free(mMixerBuffer);
2413 mMixerBuffer = NULL;
2414 if (mMixerBufferEnabled) {
2415 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2416 mMixerBufferSize = mNormalFrameCount * mChannelCount
2417 * audio_bytes_per_sample(mMixerBufferFormat);
2418 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2419 }
Andy Hung98ef9782014-03-04 14:46:50 -08002420 free(mEffectBuffer);
2421 mEffectBuffer = NULL;
2422 if (mEffectBufferEnabled) {
2423 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2424 mEffectBufferSize = mNormalFrameCount * mChannelCount
2425 * audio_bytes_per_sample(mEffectBufferFormat);
2426 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2427 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002428
Eric Laurent81784c32012-11-19 14:55:58 -08002429 // force reconfiguration of effect chains and engines to take new buffer size and audio
2430 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002431 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002432 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2433 // matter.
2434 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2435 Vector< sp<EffectChain> > effectChains = mEffectChains;
2436 for (size_t i = 0; i < effectChains.size(); i ++) {
2437 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2438 }
2439}
2440
2441
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002442status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002443{
2444 if (halFrames == NULL || dspFrames == NULL) {
2445 return BAD_VALUE;
2446 }
2447 Mutex::Autolock _l(mLock);
2448 if (initCheck() != NO_ERROR) {
2449 return INVALID_OPERATION;
2450 }
Andy Hung818e7a32016-02-16 18:08:07 -08002451 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002452 *halFrames = framesWritten;
2453
2454 if (isSuspended()) {
2455 // return an estimation of rendered frames when the output is suspended
2456 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002457 *dspFrames = (uint32_t)
2458 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002459 return NO_ERROR;
2460 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002461 status_t status;
2462 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002463 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002464 *dspFrames = (size_t)frames;
2465 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002466 }
2467}
2468
Eric Laurent4c415062016-06-17 16:14:16 -07002469// hasAudioSession_l() must be called with ThreadBase::mLock held
2470uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002471{
Eric Laurent81784c32012-11-19 14:55:58 -08002472 uint32_t result = 0;
2473 if (getEffectChain_l(sessionId) != 0) {
2474 result = EFFECT_SESSION;
2475 }
2476
2477 for (size_t i = 0; i < mTracks.size(); ++i) {
2478 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002479 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002480 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002481 if (track->isFastTrack()) {
2482 result |= FAST_SESSION;
2483 }
Eric Laurent81784c32012-11-19 14:55:58 -08002484 break;
2485 }
2486 }
2487
2488 return result;
2489}
2490
Glenn Kastend848eb42016-03-08 13:42:11 -08002491uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002492{
2493 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2494 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2495 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2496 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2497 }
2498 for (size_t i = 0; i < mTracks.size(); i++) {
2499 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002500 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002501 return AudioSystem::getStrategyForStream(track->streamType());
2502 }
2503 }
2504 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2505}
2506
2507
Phil Burk062e67a2015-02-11 13:40:50 -08002508AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002509{
2510 Mutex::Autolock _l(mLock);
2511 return mOutput;
2512}
2513
Phil Burk062e67a2015-02-11 13:40:50 -08002514AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002515{
2516 Mutex::Autolock _l(mLock);
2517 AudioStreamOut *output = mOutput;
2518 mOutput = NULL;
2519 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2520 // must push a NULL and wait for ack
2521 mOutputSink.clear();
2522 mPipeSink.clear();
2523 mNormalSink.clear();
2524 return output;
2525}
2526
2527// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002528sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002529{
2530 if (mOutput == NULL) {
2531 return NULL;
2532 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002533 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002534}
2535
2536uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2537{
2538 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2539}
2540
2541status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2542{
2543 if (!isValidSyncEvent(event)) {
2544 return BAD_VALUE;
2545 }
2546
2547 Mutex::Autolock _l(mLock);
2548
2549 for (size_t i = 0; i < mTracks.size(); ++i) {
2550 sp<Track> track = mTracks[i];
2551 if (event->triggerSession() == track->sessionId()) {
2552 (void) track->setSyncEvent(event);
2553 return NO_ERROR;
2554 }
2555 }
2556
2557 return NAME_NOT_FOUND;
2558}
2559
2560bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2561{
2562 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2563}
2564
2565void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2566 const Vector< sp<Track> >& tracksToRemove)
2567{
2568 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002569 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002570 for (size_t i = 0 ; i < count ; i++) {
2571 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002572 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002573 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002574 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002575#ifdef ADD_BATTERY_DATA
2576 // to track the speaker usage
2577 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2578#endif
2579 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002580 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002581 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002582 }
Eric Laurent81784c32012-11-19 14:55:58 -08002583 }
2584 }
2585 }
Eric Laurent81784c32012-11-19 14:55:58 -08002586}
2587
2588void AudioFlinger::PlaybackThread::checkSilentMode_l()
2589{
2590 if (!mMasterMute) {
2591 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002592 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2593 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2594 return;
2595 }
Eric Laurent81784c32012-11-19 14:55:58 -08002596 if (property_get("ro.audio.silent", value, "0") > 0) {
2597 char *endptr;
2598 unsigned long ul = strtoul(value, &endptr, 0);
2599 if (*endptr == '\0' && ul != 0) {
2600 ALOGD("Silence is golden");
2601 // The setprop command will not allow a property to be changed after
2602 // the first time it is set, so we don't have to worry about un-muting.
2603 setMasterMute_l(true);
2604 }
2605 }
2606 }
2607}
2608
2609// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002610ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002611{
Eric Laurent81784c32012-11-19 14:55:58 -08002612 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002613 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002614 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002615
2616 // If an NBAIO sink is present, use it to write the normal mixer's submix
2617 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002618
Andy Hung010a1a12014-03-13 13:57:33 -07002619 const size_t count = mBytesRemaining / mFrameSize;
2620
Simon Wilson2d590962012-11-29 15:18:50 -08002621 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002622 // update the setpoint when AudioFlinger::mScreenState changes
2623 uint32_t screenState = AudioFlinger::mScreenState;
2624 if (screenState != mScreenState) {
2625 mScreenState = screenState;
2626 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2627 if (pipe != NULL) {
2628 pipe->setAvgFrames((mScreenState & 1) ?
2629 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2630 }
2631 }
Andy Hung010a1a12014-03-13 13:57:33 -07002632 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002633 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002634 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002635 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002636 } else {
2637 bytesWritten = framesWritten;
2638 }
2639 // otherwise use the HAL / AudioStreamOut directly
2640 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002642
Eric Laurentbfb1b832013-01-07 09:53:42 -08002643 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002644 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2645 mWriteAckSequence += 2;
2646 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002647 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002648 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002649 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002650 // FIXME We should have an implementation of timestamps for direct output threads.
2651 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002652 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002653
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 if (mUseAsyncWrite &&
2655 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2656 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002657 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002659 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002660 }
Eric Laurent81784c32012-11-19 14:55:58 -08002661 }
2662
Eric Laurent81784c32012-11-19 14:55:58 -08002663 mNumWrites++;
2664 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002665 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 return bytesWritten;
2667}
2668
2669void AudioFlinger::PlaybackThread::threadLoop_drain()
2670{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002671 bool supportsDrain = false;
2672 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2674 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002675 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2676 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002678 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002679 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002680 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002681 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682 }
2683}
2684
2685void AudioFlinger::PlaybackThread::threadLoop_exit()
2686{
Eric Laurent275e8e92014-11-30 15:14:47 -08002687 {
2688 Mutex::Autolock _l(mLock);
2689 for (size_t i = 0; i < mTracks.size(); i++) {
2690 sp<Track> track = mTracks[i];
2691 track->invalidate();
2692 }
Andy Hungdae27702016-10-31 14:01:16 -07002693 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2694 // After we exit there are no more track changes sent to BatteryNotifier
2695 // because that requires an active threadLoop.
2696 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2697 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002698 }
Eric Laurent81784c32012-11-19 14:55:58 -08002699}
2700
2701/*
2702The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002703 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002704 - mActiveSleepTimeUs from activeSleepTimeUs()
2705 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002706 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2707 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002708 - maxPeriod from frame count and sample rate (MIXER only)
2709
2710The parameters that affect these derived values are:
2711 - frame count
2712 - frame size
2713 - sample rate
2714 - device type: A2DP or not
2715 - device latency
2716 - format: PCM or not
2717 - active sleep time
2718 - idle sleep time
2719*/
2720
2721void AudioFlinger::PlaybackThread::cacheParameters_l()
2722{
Andy Hung25c2dac2014-02-27 14:56:00 -08002723 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002724 mActiveSleepTimeUs = activeSleepTimeUs();
2725 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002726
2727 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2728 // truncating audio when going to standby.
2729 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2730 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2731 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2732 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2733 }
2734 }
Eric Laurent81784c32012-11-19 14:55:58 -08002735}
2736
Eric Laurent13084622016-05-17 10:51:49 -07002737bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002738{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002739 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002740 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002741 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002742 size_t size = mTracks.size();
2743 for (size_t i = 0; i < size; i++) {
2744 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002745 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002746 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002747 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002748 }
2749 }
Eric Laurent13084622016-05-17 10:51:49 -07002750 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002751}
2752
Haynes Mathew George05317d22016-05-03 16:34:26 -07002753void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2754{
2755 Mutex::Autolock _l(mLock);
2756 invalidateTracks_l(streamType);
2757}
2758
Eric Laurent81784c32012-11-19 14:55:58 -08002759status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2760{
Glenn Kastend848eb42016-03-08 13:42:11 -08002761 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002762 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2763 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002764 bool ownsBuffer = false;
2765
2766 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002767 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002768 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002769 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002770 if (mType != DIRECT) {
2771 size_t numSamples = mNormalFrameCount * mChannelCount;
2772 buffer = new int16_t[numSamples];
2773 memset(buffer, 0, numSamples * sizeof(int16_t));
2774 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2775 ownsBuffer = true;
2776 }
2777
2778 // Attach all tracks with same session ID to this chain.
2779 for (size_t i = 0; i < mTracks.size(); ++i) {
2780 sp<Track> track = mTracks[i];
2781 if (session == track->sessionId()) {
2782 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2783 buffer);
2784 track->setMainBuffer(buffer);
2785 chain->incTrackCnt();
2786 }
2787 }
2788
2789 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002790 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002791 if (session == track->sessionId()) {
2792 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2793 chain->incActiveTrackCnt();
2794 }
2795 }
2796 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002797 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002798 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002799 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2800 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002801 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002802 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002803 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2804 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002805 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002806 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002807 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002808 // Effect chain for other sessions are inserted at beginning of effect
2809 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002810 // sessions is not important.
2811 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2812 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2813 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002814 size_t size = mEffectChains.size();
2815 size_t i = 0;
2816 for (i = 0; i < size; i++) {
2817 if (mEffectChains[i]->sessionId() < session) {
2818 break;
2819 }
2820 }
2821 mEffectChains.insertAt(chain, i);
2822 checkSuspendOnAddEffectChain_l(chain);
2823
2824 return NO_ERROR;
2825}
2826
2827size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2828{
Glenn Kastend848eb42016-03-08 13:42:11 -08002829 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002830
2831 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2832
2833 for (size_t i = 0; i < mEffectChains.size(); i++) {
2834 if (chain == mEffectChains[i]) {
2835 mEffectChains.removeAt(i);
2836 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002837 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002838 if (session == track->sessionId()) {
2839 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2840 chain.get(), session);
2841 chain->decActiveTrackCnt();
2842 }
2843 }
2844
2845 // detach all tracks with same session ID from this chain
2846 for (size_t i = 0; i < mTracks.size(); ++i) {
2847 sp<Track> track = mTracks[i];
2848 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002849 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002850 chain->decTrackCnt();
2851 }
2852 }
2853 break;
2854 }
2855 }
2856 return mEffectChains.size();
2857}
2858
2859status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002860 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002861{
2862 Mutex::Autolock _l(mLock);
2863 return attachAuxEffect_l(track, EffectId);
2864}
2865
2866status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002867 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002868{
2869 status_t status = NO_ERROR;
2870
2871 if (EffectId == 0) {
2872 track->setAuxBuffer(0, NULL);
2873 } else {
2874 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2875 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2876 if (effect != 0) {
2877 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2878 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2879 } else {
2880 status = INVALID_OPERATION;
2881 }
2882 } else {
2883 status = BAD_VALUE;
2884 }
2885 }
2886 return status;
2887}
2888
2889void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2890{
2891 for (size_t i = 0; i < mTracks.size(); ++i) {
2892 sp<Track> track = mTracks[i];
2893 if (track->auxEffectId() == effectId) {
2894 attachAuxEffect_l(track, 0);
2895 }
2896 }
2897}
2898
2899bool AudioFlinger::PlaybackThread::threadLoop()
2900{
2901 Vector< sp<Track> > tracksToRemove;
2902
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002903 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002904 nsecs_t lastWriteFinished = -1; // time last server write completed
2905 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002906
2907 // MIXER
2908 nsecs_t lastWarning = 0;
2909
2910 // DUPLICATING
2911 // FIXME could this be made local to while loop?
2912 writeFrames = 0;
2913
2914 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002915 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002916
2917 if (mType == MIXER) {
2918 sleepTimeShift = 0;
2919 }
2920
2921 CpuStats cpuStats;
2922 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2923
2924 acquireWakeLock();
2925
Glenn Kasten9e58b552013-01-18 15:09:48 -08002926 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2927 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2928 // and then that string will be logged at the next convenient opportunity.
2929 const char *logString = NULL;
2930
Eric Laurent664539d2013-09-23 18:24:31 -07002931 checkSilentMode_l();
2932
Eric Laurent81784c32012-11-19 14:55:58 -08002933 while (!exitPending())
2934 {
2935 cpuStats.sample(myName);
2936
2937 Vector< sp<EffectChain> > effectChains;
2938
Eric Laurent81784c32012-11-19 14:55:58 -08002939 { // scope for mLock
2940
2941 Mutex::Autolock _l(mLock);
2942
Eric Laurent021cf962014-05-13 10:18:14 -07002943 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002944
Glenn Kasten9e58b552013-01-18 15:09:48 -08002945 if (logString != NULL) {
2946 mNBLogWriter->logTimestamp();
2947 mNBLogWriter->log(logString);
2948 logString = NULL;
2949 }
2950
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002951 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002952 // and associate with the sink frames written out. We need
2953 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002954 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002955 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002956 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002957 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002958 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002959 ExtendedTimestamp timestamp; // use private copy to fetch
2960 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002961
2962 // We keep track of the last valid kernel position in case we are in underrun
2963 // and the normal mixer period is the same as the fast mixer period, or there
2964 // is some error from the HAL.
2965 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2966 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2967 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2968 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2969 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2970
2971 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2972 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2973 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2974 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002975 }
2976
2977 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2978 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002979 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002980 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002981 }
2982
Andy Hung818e7a32016-02-16 18:08:07 -08002983 // copy over kernel info
2984 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07002985 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
2986 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08002987 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2988 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002989 }
2990 // mFramesWritten for non-offloaded tracks are contiguous
2991 // even after standby() is called. This is useful for the track frame
2992 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07002993 bool serverLocationUpdate = false;
2994 if (mFramesWritten != lastFramesWritten) {
2995 serverLocationUpdate = true;
2996 lastFramesWritten = mFramesWritten;
2997 }
2998 // Only update timestamps if there is a meaningful change.
2999 // Either the kernel timestamp must be valid or we have written something.
3000 if (kernelLocationUpdate || serverLocationUpdate) {
3001 if (serverLocationUpdate) {
3002 // use the time before we called the HAL write - it is a bit more accurate
3003 // to when the server last read data than the current time here.
3004 //
3005 // If we haven't written anything, mLastWriteTime will be -1
3006 // and we use systemTime().
3007 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3008 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3009 ? systemTime() : mLastWriteTime;
3010 }
Andy Hungdae27702016-10-31 14:01:16 -07003011
3012 for (const sp<Track> &t : mActiveTracks) {
3013 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003014 t->updateTrackFrameInfo(
3015 t->mAudioTrackServerProxy->framesReleased(),
3016 mFramesWritten,
3017 mTimestamp);
3018 }
Andy Hunge10393e2015-06-12 13:59:33 -07003019 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003020 }
3021
Eric Laurent81784c32012-11-19 14:55:58 -08003022 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023 if (mSignalPending) {
3024 // A signal was raised while we were unlocked
3025 mSignalPending = false;
3026 } else if (waitingAsyncCallback_l()) {
3027 if (exitPending()) {
3028 break;
3029 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003030 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003031 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003032 releaseWakeLock_l();
3033 released = true;
3034 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003035 ALOGV("wait async completion");
3036 mWaitWorkCV.wait(mLock);
3037 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003038 if (released) {
3039 acquireWakeLock_l();
3040 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003041 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3042 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003043
3044 continue;
3045 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003046 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003047 isSuspended()) {
3048 // put audio hardware into standby after short delay
3049 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003050
3051 threadLoop_standby();
3052
3053 mStandby = true;
3054 }
3055
3056 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3057 // we're about to wait, flush the binder command buffer
3058 IPCThreadState::self()->flushCommands();
3059
3060 clearOutputTracks();
3061
3062 if (exitPending()) {
3063 break;
3064 }
3065
3066 releaseWakeLock_l();
3067 // wait until we have something to do...
3068 ALOGV("%s going to sleep", myName.string());
3069 mWaitWorkCV.wait(mLock);
3070 ALOGV("%s waking up", myName.string());
3071 acquireWakeLock_l();
3072
3073 mMixerStatus = MIXER_IDLE;
3074 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3075 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003076 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003077 checkSilentMode_l();
3078
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003079 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3080 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003081 if (mType == MIXER) {
3082 sleepTimeShift = 0;
3083 }
3084
3085 continue;
3086 }
3087 }
Eric Laurent81784c32012-11-19 14:55:58 -08003088 // mMixerStatusIgnoringFastTracks is also updated internally
3089 mMixerStatus = prepareTracks_l(&tracksToRemove);
3090
Andy Hungdae27702016-10-31 14:01:16 -07003091 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003092
Eric Laurent81784c32012-11-19 14:55:58 -08003093 // prevent any changes in effect chain list and in each effect chain
3094 // during mixing and effect process as the audio buffers could be deleted
3095 // or modified if an effect is created or deleted
3096 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003097 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003098
Eric Laurentbfb1b832013-01-07 09:53:42 -08003099 if (mBytesRemaining == 0) {
3100 mCurrentWriteLength = 0;
3101 if (mMixerStatus == MIXER_TRACKS_READY) {
3102 // threadLoop_mix() sets mCurrentWriteLength
3103 threadLoop_mix();
3104 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3105 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003106 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107 // must be written to HAL
3108 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003109 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003110 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003111 }
3112 }
Andy Hung98ef9782014-03-04 14:46:50 -08003113 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003114 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003115 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3116 // or mSinkBuffer (if there are no effects).
3117 //
3118 // This is done pre-effects computation; if effects change to
3119 // support higher precision, this needs to move.
3120 //
3121 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003122 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003123 if (mMixerBufferValid) {
3124 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3125 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3126
Andy Hung2ddee192015-12-18 17:34:44 -08003127 // mono blend occurs for mixer threads only (not direct or offloaded)
3128 // and is handled here if we're going directly to the sink.
3129 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003130 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3131 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003132 }
3133
Andy Hung98ef9782014-03-04 14:46:50 -08003134 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3135 mNormalFrameCount * mChannelCount);
3136 }
3137
Eric Laurentbfb1b832013-01-07 09:53:42 -08003138 mBytesRemaining = mCurrentWriteLength;
3139 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003140 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3141 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3142 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3143 mBytesWritten += mBytesRemaining;
3144 mFramesWritten += framesRemaining;
3145 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003146 mBytesRemaining = 0;
3147 }
Eric Laurent81784c32012-11-19 14:55:58 -08003148
Eric Laurentbfb1b832013-01-07 09:53:42 -08003149 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003150 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003151 for (size_t i = 0; i < effectChains.size(); i ++) {
3152 effectChains[i]->process_l();
3153 }
Eric Laurent81784c32012-11-19 14:55:58 -08003154 }
3155 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003156 // Process effect chains for offloaded thread even if no audio
3157 // was read from audio track: process only updates effect state
3158 // and thus does have to be synchronized with audio writes but may have
3159 // to be called while waiting for async write callback
3160 if (mType == OFFLOAD) {
3161 for (size_t i = 0; i < effectChains.size(); i ++) {
3162 effectChains[i]->process_l();
3163 }
3164 }
Eric Laurent81784c32012-11-19 14:55:58 -08003165
Andy Hung98ef9782014-03-04 14:46:50 -08003166 // Only if the Effects buffer is enabled and there is data in the
3167 // Effects buffer (buffer valid), we need to
3168 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003169 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003170 if (mEffectBufferValid) {
3171 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003172
3173 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003174 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3175 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003176 }
3177
Andy Hung98ef9782014-03-04 14:46:50 -08003178 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3179 mNormalFrameCount * mChannelCount);
3180 }
3181
Eric Laurent81784c32012-11-19 14:55:58 -08003182 // enable changes in effect chain
3183 unlockEffectChains(effectChains);
3184
Eric Laurentbfb1b832013-01-07 09:53:42 -08003185 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003186 // mSleepTimeUs == 0 means we must write to audio hardware
3187 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003188 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003189 // We save lastWriteFinished here, as previousLastWriteFinished,
3190 // for throttling. On thread start, previousLastWriteFinished will be
3191 // set to -1, which properly results in no throttling after the first write.
3192 nsecs_t previousLastWriteFinished = lastWriteFinished;
3193 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003194 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003195 // FIXME rewrite to reduce number of system calls
3196 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003197 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003198 lastWriteFinished = systemTime();
3199 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003200 if (ret < 0) {
3201 mBytesRemaining = 0;
3202 } else {
3203 mBytesWritten += ret;
3204 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003205 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003206 }
3207 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3208 (mMixerStatus == MIXER_DRAIN_ALL)) {
3209 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003210 }
Andy Hung08fb1742015-05-31 23:22:10 -07003211 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003212 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003213 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003214 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003215 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003216 ATRACE_NAME("underrun");
3217 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003218 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003219 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003220 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003221 }
Andy Hung08fb1742015-05-31 23:22:10 -07003222
3223 if (mThreadThrottle
3224 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3225 && ret > 0) { // we wrote something
3226 // Limit MixerThread data processing to no more than twice the
3227 // expected processing rate.
3228 //
3229 // This helps prevent underruns with NuPlayer and other applications
3230 // which may set up buffers that are close to the minimum size, or use
3231 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3232 //
3233 // The throttle smooths out sudden large data drains from the device,
3234 // e.g. when it comes out of standby, which often causes problems with
3235 // (1) mixer threads without a fast mixer (which has its own warm-up)
3236 // (2) minimum buffer sized tracks (even if the track is full,
3237 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003238 //
3239 // Total time spent in last processing cycle equals time spent in
3240 // 1. threadLoop_write, as well as time spent in
3241 // 2. threadLoop_mix (significant for heavy mixing, especially
3242 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003243
Andy Hung69488c42016-05-16 18:43:33 -07003244 // it's OK if deltaMs is an overestimate.
3245 const int32_t deltaMs =
3246 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003247 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3248 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3249 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003250 // notify of throttle start on verbose log
3251 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3252 "mixer(%p) throttle begin:"
3253 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003254 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003255 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003256 // Throttle must be attributed to the previous mixer loop's write time
3257 // to allow back-to-back throttling.
3258 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003259 } else {
3260 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3261 if (diff > 0) {
3262 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003263 // but prevent spamming for bluetooth
3264 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3265 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003266 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3267 }
Andy Hung08fb1742015-05-31 23:22:10 -07003268 }
3269 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003270 }
Eric Laurent81784c32012-11-19 14:55:58 -08003271
Eric Laurentbfb1b832013-01-07 09:53:42 -08003272 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003273 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003274 Mutex::Autolock _l(mLock);
3275 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3276 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003277 }
Glenn Kastene7754022014-10-31 12:11:26 -07003278 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003279 }
Eric Laurent81784c32012-11-19 14:55:58 -08003280 }
3281
3282 // Finally let go of removed track(s), without the lock held
3283 // since we can't guarantee the destructors won't acquire that
3284 // same lock. This will also mutate and push a new fast mixer state.
3285 threadLoop_removeTracks(tracksToRemove);
3286 tracksToRemove.clear();
3287
3288 // FIXME I don't understand the need for this here;
3289 // it was in the original code but maybe the
3290 // assignment in saveOutputTracks() makes this unnecessary?
3291 clearOutputTracks();
3292
3293 // Effect chains will be actually deleted here if they were removed from
3294 // mEffectChains list during mixing or effects processing
3295 effectChains.clear();
3296
3297 // FIXME Note that the above .clear() is no longer necessary since effectChains
3298 // is now local to this block, but will keep it for now (at least until merge done).
3299 }
3300
Eric Laurentbfb1b832013-01-07 09:53:42 -08003301 threadLoop_exit();
3302
Eric Laurentcf817a22014-08-04 20:36:31 -07003303 if (!mStandby) {
3304 threadLoop_standby();
3305 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003306 }
3307
3308 releaseWakeLock();
3309
3310 ALOGV("Thread %p type %d exiting", this, mType);
3311 return false;
3312}
3313
Eric Laurentbfb1b832013-01-07 09:53:42 -08003314// removeTracks_l() must be called with ThreadBase::mLock held
3315void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3316{
3317 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003318 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003319 for (size_t i=0 ; i<count ; i++) {
3320 const sp<Track>& track = tracksToRemove.itemAt(i);
3321 mActiveTracks.remove(track);
3322 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3323 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3324 if (chain != 0) {
3325 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3326 track->sessionId());
3327 chain->decActiveTrackCnt();
3328 }
3329 if (track->isTerminated()) {
3330 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003331 } else { // inactive but not terminated
3332 char buffer[256];
3333 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3334 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003335 }
3336 }
3337 }
3338
3339}
Eric Laurent81784c32012-11-19 14:55:58 -08003340
Eric Laurentaccc1472013-09-20 09:36:34 -07003341status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3342{
3343 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003344 ExtendedTimestamp ets;
3345 status_t status = mNormalSink->getTimestamp(ets);
3346 if (status == NO_ERROR) {
3347 status = ets.getBestTimestamp(&timestamp);
3348 }
3349 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003350 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003351 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003352 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003353 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003354 timestamp.mPosition = (uint32_t)position64;
3355 return NO_ERROR;
3356 }
3357 }
3358 return INVALID_OPERATION;
3359}
Eric Laurent1c333e22014-05-20 10:48:17 -07003360
Eric Laurent054d9d32015-04-24 08:48:48 -07003361status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3362 audio_patch_handle_t *handle)
3363{
Andy Hungf60abce2016-08-26 11:37:54 -07003364 status_t status;
3365 if (property_get_bool("af.patch_park", false /* default_value */)) {
3366 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3367 // or if HAL does not properly lock against access.
3368 AutoPark<FastMixer> park(mFastMixer);
3369 status = PlaybackThread::createAudioPatch_l(patch, handle);
3370 } else {
3371 status = PlaybackThread::createAudioPatch_l(patch, handle);
3372 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003373 return status;
3374}
3375
Eric Laurent1c333e22014-05-20 10:48:17 -07003376status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3377 audio_patch_handle_t *handle)
3378{
3379 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003380
3381 // store new device and send to effects
3382 audio_devices_t type = AUDIO_DEVICE_NONE;
3383 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3384 type |= patch->sinks[i].ext.device.type;
3385 }
3386
3387#ifdef ADD_BATTERY_DATA
3388 // when changing the audio output device, call addBatteryData to notify
3389 // the change
3390 if (mOutDevice != type) {
3391 uint32_t params = 0;
3392 // check whether speaker is on
3393 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3394 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003395 }
3396
Eric Laurent054d9d32015-04-24 08:48:48 -07003397 audio_devices_t deviceWithoutSpeaker
3398 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3399 // check if any other device (except speaker) is on
3400 if (type & deviceWithoutSpeaker) {
3401 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3402 }
3403
3404 if (params != 0) {
3405 addBatteryData(params);
3406 }
3407 }
3408#endif
3409
3410 for (size_t i = 0; i < mEffectChains.size(); i++) {
3411 mEffectChains[i]->setDevice_l(type);
3412 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003413
3414 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3415 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3416 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003417 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003418 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003419
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003420 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003421 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3422 status = hwDevice->createAudioPatch(patch->num_sources,
3423 patch->sources,
3424 patch->num_sinks,
3425 patch->sinks,
3426 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003427 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003428 char *address;
3429 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3430 //FIXME: we only support address on first sink with HAL version < 3.0
3431 address = audio_device_address_to_parameter(
3432 patch->sinks[0].ext.device.type,
3433 patch->sinks[0].ext.device.address);
3434 } else {
3435 address = (char *)calloc(1, 1);
3436 }
3437 AudioParameter param = AudioParameter(String8(address));
3438 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003439 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003440 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003441 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003442 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003443 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003444 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003445 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3446 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003447 return status;
3448}
3449
Eric Laurent054d9d32015-04-24 08:48:48 -07003450status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3451{
Andy Hungf60abce2016-08-26 11:37:54 -07003452 status_t status;
3453 if (property_get_bool("af.patch_park", false /* default_value */)) {
3454 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3455 // or if HAL does not properly lock against access.
3456 AutoPark<FastMixer> park(mFastMixer);
3457 status = PlaybackThread::releaseAudioPatch_l(handle);
3458 } else {
3459 status = PlaybackThread::releaseAudioPatch_l(handle);
3460 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003461 return status;
3462}
3463
Eric Laurent1c333e22014-05-20 10:48:17 -07003464status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3465{
3466 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003467
3468 mOutDevice = AUDIO_DEVICE_NONE;
3469
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003470 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003471 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3472 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003473 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003474 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003475 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003476 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003477 }
3478 return status;
3479}
3480
Eric Laurent83b88082014-06-20 18:31:16 -07003481void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3482{
3483 Mutex::Autolock _l(mLock);
3484 mTracks.add(track);
3485}
3486
3487void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3488{
3489 Mutex::Autolock _l(mLock);
3490 destroyTrack_l(track);
3491}
3492
3493void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3494{
3495 ThreadBase::getAudioPortConfig(config);
3496 config->role = AUDIO_PORT_ROLE_SOURCE;
3497 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3498 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3499}
3500
Eric Laurent81784c32012-11-19 14:55:58 -08003501// ----------------------------------------------------------------------------
3502
3503AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003504 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3505 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003506 // mAudioMixer below
3507 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003508 mFastMixerFutex(0),
3509 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003510 // mOutputSink below
3511 // mPipeSink below
3512 // mNormalSink below
3513{
3514 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003515 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3516 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003517 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3518 mNormalFrameCount);
3519 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3520
Andy Hungfbfc3952015-01-15 13:33:51 -08003521 if (type == DUPLICATING) {
3522 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3523 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3524 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3525 return;
3526 }
Eric Laurent81784c32012-11-19 14:55:58 -08003527 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003528 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003529 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003530 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003531#if !LOG_NDEBUG
3532 ssize_t index =
3533#else
3534 (void)
3535#endif
3536 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003537 ALOG_ASSERT(index == 0);
3538
3539 // initialize fast mixer depending on configuration
3540 bool initFastMixer;
3541 switch (kUseFastMixer) {
3542 case FastMixer_Never:
3543 initFastMixer = false;
3544 break;
3545 case FastMixer_Always:
3546 initFastMixer = true;
3547 break;
3548 case FastMixer_Static:
3549 case FastMixer_Dynamic:
3550 initFastMixer = mFrameCount < mNormalFrameCount;
3551 break;
3552 }
3553 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003554 audio_format_t fastMixerFormat;
3555 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3556 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3557 } else {
3558 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3559 }
3560 if (mFormat != fastMixerFormat) {
3561 // change our Sink format to accept our intermediate precision
3562 mFormat = fastMixerFormat;
3563 free(mSinkBuffer);
3564 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3565 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3566 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3567 }
Eric Laurent81784c32012-11-19 14:55:58 -08003568
3569 // create a MonoPipe to connect our submix to FastMixer
3570 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003571#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003572 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003573#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003574 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003575 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003576 format.mFormat = fastMixerFormat;
3577 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3578
Eric Laurent81784c32012-11-19 14:55:58 -08003579 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3580 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3581 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3582 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3583 const NBAIO_Format offers[1] = {format};
3584 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003585#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003586 ssize_t index =
3587#else
3588 (void)
3589#endif
3590 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003591 ALOG_ASSERT(index == 0);
3592 monoPipe->setAvgFrames((mScreenState & 1) ?
3593 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3594 mPipeSink = monoPipe;
3595
Glenn Kasten46909e72013-02-26 09:20:22 -08003596#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003597 if (mTeeSinkOutputEnabled) {
3598 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003599 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3600 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003601 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003602 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003603 ALOG_ASSERT(index == 0);
3604 mTeeSink = teeSink;
3605 PipeReader *teeSource = new PipeReader(*teeSink);
3606 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003607 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003608 ALOG_ASSERT(index == 0);
3609 mTeeSource = teeSource;
3610 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003611#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003612
3613 // create fast mixer and configure it initially with just one fast track for our submix
3614 mFastMixer = new FastMixer();
3615 FastMixerStateQueue *sq = mFastMixer->sq();
3616#ifdef STATE_QUEUE_DUMP
3617 sq->setObserverDump(&mStateQueueObserverDump);
3618 sq->setMutatorDump(&mStateQueueMutatorDump);
3619#endif
3620 FastMixerState *state = sq->begin();
3621 FastTrack *fastTrack = &state->mFastTracks[0];
3622 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3623 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3624 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003625 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3626 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003627 fastTrack->mGeneration++;
3628 state->mFastTracksGen++;
3629 state->mTrackMask = 1;
3630 // fast mixer will use the HAL output sink
3631 state->mOutputSink = mOutputSink.get();
3632 state->mOutputSinkGen++;
3633 state->mFrameCount = mFrameCount;
3634 state->mCommand = FastMixerState::COLD_IDLE;
3635 // already done in constructor initialization list
3636 //mFastMixerFutex = 0;
3637 state->mColdFutexAddr = &mFastMixerFutex;
3638 state->mColdGen++;
3639 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003640#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003641 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003642#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003643 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3644 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003645 sq->end();
3646 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3647
3648 // start the fast mixer
3649 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3650 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003651 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003652 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003653
3654#ifdef AUDIO_WATCHDOG
3655 // create and start the watchdog
3656 mAudioWatchdog = new AudioWatchdog();
3657 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3658 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3659 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003660 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003661#endif
3662
Eric Laurent81784c32012-11-19 14:55:58 -08003663 }
3664
3665 switch (kUseFastMixer) {
3666 case FastMixer_Never:
3667 case FastMixer_Dynamic:
3668 mNormalSink = mOutputSink;
3669 break;
3670 case FastMixer_Always:
3671 mNormalSink = mPipeSink;
3672 break;
3673 case FastMixer_Static:
3674 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3675 break;
3676 }
3677}
3678
3679AudioFlinger::MixerThread::~MixerThread()
3680{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003681 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003682 FastMixerStateQueue *sq = mFastMixer->sq();
3683 FastMixerState *state = sq->begin();
3684 if (state->mCommand == FastMixerState::COLD_IDLE) {
3685 int32_t old = android_atomic_inc(&mFastMixerFutex);
3686 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003687 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003688 }
3689 }
3690 state->mCommand = FastMixerState::EXIT;
3691 sq->end();
3692 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3693 mFastMixer->join();
3694 // Though the fast mixer thread has exited, it's state queue is still valid.
3695 // We'll use that extract the final state which contains one remaining fast track
3696 // corresponding to our sub-mix.
3697 state = sq->begin();
3698 ALOG_ASSERT(state->mTrackMask == 1);
3699 FastTrack *fastTrack = &state->mFastTracks[0];
3700 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3701 delete fastTrack->mBufferProvider;
3702 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003703 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003704#ifdef AUDIO_WATCHDOG
3705 if (mAudioWatchdog != 0) {
3706 mAudioWatchdog->requestExit();
3707 mAudioWatchdog->requestExitAndWait();
3708 mAudioWatchdog.clear();
3709 }
3710#endif
3711 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003712 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003713 delete mAudioMixer;
3714}
3715
3716
3717uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3718{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003719 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003720 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3721 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3722 }
3723 return latency;
3724}
3725
3726
3727void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3728{
3729 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3730}
3731
Eric Laurentbfb1b832013-01-07 09:53:42 -08003732ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003733{
3734 // FIXME we should only do one push per cycle; confirm this is true
3735 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003736 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003737 FastMixerStateQueue *sq = mFastMixer->sq();
3738 FastMixerState *state = sq->begin();
3739 if (state->mCommand != FastMixerState::MIX_WRITE &&
3740 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3741 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003742
3743 // FIXME workaround for first HAL write being CPU bound on some devices
3744 ATRACE_BEGIN("write");
3745 mOutput->write((char *)mSinkBuffer, 0);
3746 ATRACE_END();
3747
Eric Laurent81784c32012-11-19 14:55:58 -08003748 int32_t old = android_atomic_inc(&mFastMixerFutex);
3749 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003750 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003751 }
3752#ifdef AUDIO_WATCHDOG
3753 if (mAudioWatchdog != 0) {
3754 mAudioWatchdog->resume();
3755 }
3756#endif
3757 }
3758 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003759#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003760 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003761 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003762#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003763 sq->end();
3764 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3765 if (kUseFastMixer == FastMixer_Dynamic) {
3766 mNormalSink = mPipeSink;
3767 }
3768 } else {
3769 sq->end(false /*didModify*/);
3770 }
3771 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003772 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003773}
3774
3775void AudioFlinger::MixerThread::threadLoop_standby()
3776{
3777 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003778 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003779 FastMixerStateQueue *sq = mFastMixer->sq();
3780 FastMixerState *state = sq->begin();
3781 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003782 // Report any frames trapped in the Monopipe
3783 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3784 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3785 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3786 "monoPipeWritten:%lld monoPipeLeft:%lld",
3787 (long long)mFramesWritten, (long long)mSuspendedFrames,
3788 (long long)mPipeSink->framesWritten(), pipeFrames);
3789 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3790
Eric Laurent81784c32012-11-19 14:55:58 -08003791 state->mCommand = FastMixerState::COLD_IDLE;
3792 state->mColdFutexAddr = &mFastMixerFutex;
3793 state->mColdGen++;
3794 mFastMixerFutex = 0;
3795 sq->end();
3796 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3797 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3798 if (kUseFastMixer == FastMixer_Dynamic) {
3799 mNormalSink = mOutputSink;
3800 }
3801#ifdef AUDIO_WATCHDOG
3802 if (mAudioWatchdog != 0) {
3803 mAudioWatchdog->pause();
3804 }
3805#endif
3806 } else {
3807 sq->end(false /*didModify*/);
3808 }
3809 }
3810 PlaybackThread::threadLoop_standby();
3811}
3812
Eric Laurentbfb1b832013-01-07 09:53:42 -08003813bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3814{
3815 return false;
3816}
3817
3818bool AudioFlinger::PlaybackThread::shouldStandby_l()
3819{
3820 return !mStandby;
3821}
3822
3823bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3824{
3825 Mutex::Autolock _l(mLock);
3826 return waitingAsyncCallback_l();
3827}
3828
Eric Laurent81784c32012-11-19 14:55:58 -08003829// shared by MIXER and DIRECT, overridden by DUPLICATING
3830void AudioFlinger::PlaybackThread::threadLoop_standby()
3831{
3832 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003833 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003834 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003835 // discard any pending drain or write ack by incrementing sequence
3836 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3837 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003838 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003839 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3840 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003841 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003842 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003843}
3844
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003845void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3846{
3847 ALOGV("signal playback thread");
3848 broadcast_l();
3849}
3850
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003851void AudioFlinger::PlaybackThread::onAsyncError()
3852{
3853 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3854 invalidateTracks((audio_stream_type_t)i);
3855 }
3856}
3857
Eric Laurent81784c32012-11-19 14:55:58 -08003858void AudioFlinger::MixerThread::threadLoop_mix()
3859{
Eric Laurent81784c32012-11-19 14:55:58 -08003860 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003861 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003862 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003863 // increase sleep time progressively when application underrun condition clears.
3864 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3865 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3866 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003867 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003868 sleepTimeShift--;
3869 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003870 mSleepTimeUs = 0;
3871 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003872 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003873
Eric Laurent81784c32012-11-19 14:55:58 -08003874}
3875
3876void AudioFlinger::MixerThread::threadLoop_sleepTime()
3877{
3878 // If no tracks are ready, sleep once for the duration of an output
3879 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003880 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003881 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003882 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3883 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3884 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003885 }
3886 // reduce sleep time in case of consecutive application underruns to avoid
3887 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3888 // duration we would end up writing less data than needed by the audio HAL if
3889 // the condition persists.
3890 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3891 sleepTimeShift++;
3892 }
3893 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003894 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003895 }
3896 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003897 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3898 // before effects processing or output.
3899 if (mMixerBufferValid) {
3900 memset(mMixerBuffer, 0, mMixerBufferSize);
3901 } else {
3902 memset(mSinkBuffer, 0, mSinkBufferSize);
3903 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003904 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003905 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3906 "anticipated start");
3907 }
3908 // TODO add standby time extension fct of effect tail
3909}
3910
3911// prepareTracks_l() must be called with ThreadBase::mLock held
3912AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3913 Vector< sp<Track> > *tracksToRemove)
3914{
3915
3916 mixer_state mixerStatus = MIXER_IDLE;
3917 // find out which tracks need to be processed
3918 size_t count = mActiveTracks.size();
3919 size_t mixedTracks = 0;
3920 size_t tracksWithEffect = 0;
3921 // counts only _active_ fast tracks
3922 size_t fastTracks = 0;
3923 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3924
3925 float masterVolume = mMasterVolume;
3926 bool masterMute = mMasterMute;
3927
3928 if (masterMute) {
3929 masterVolume = 0;
3930 }
3931 // Delegate master volume control to effect in output mix effect chain if needed
3932 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3933 if (chain != 0) {
3934 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3935 chain->setVolume_l(&v, &v);
3936 masterVolume = (float)((v + (1 << 23)) >> 24);
3937 chain.clear();
3938 }
3939
3940 // prepare a new state to push
3941 FastMixerStateQueue *sq = NULL;
3942 FastMixerState *state = NULL;
3943 bool didModify = false;
3944 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003945 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003946 sq = mFastMixer->sq();
3947 state = sq->begin();
3948 }
3949
Andy Hung69aed5f2014-02-25 17:24:40 -08003950 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003951 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003952
Eric Laurent81784c32012-11-19 14:55:58 -08003953 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07003954 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003955
3956 // this const just means the local variable doesn't change
3957 Track* const track = t.get();
3958
3959 // process fast tracks
3960 if (track->isFastTrack()) {
3961
3962 // It's theoretically possible (though unlikely) for a fast track to be created
3963 // and then removed within the same normal mix cycle. This is not a problem, as
3964 // the track never becomes active so it's fast mixer slot is never touched.
3965 // The converse, of removing an (active) track and then creating a new track
3966 // at the identical fast mixer slot within the same normal mix cycle,
3967 // is impossible because the slot isn't marked available until the end of each cycle.
3968 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003969 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003970 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3971 FastTrack *fastTrack = &state->mFastTracks[j];
3972
3973 // Determine whether the track is currently in underrun condition,
3974 // and whether it had a recent underrun.
3975 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3976 FastTrackUnderruns underruns = ftDump->mUnderruns;
3977 uint32_t recentFull = (underruns.mBitFields.mFull -
3978 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3979 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3980 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3981 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3982 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3983 uint32_t recentUnderruns = recentPartial + recentEmpty;
3984 track->mObservedUnderruns = underruns;
3985 // don't count underruns that occur while stopping or pausing
3986 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003987 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3988 recentUnderruns > 0) {
3989 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3990 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003991 } else {
3992 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003993 }
3994
3995 // This is similar to the state machine for normal tracks,
3996 // with a few modifications for fast tracks.
3997 bool isActive = true;
3998 switch (track->mState) {
3999 case TrackBase::STOPPING_1:
4000 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004001 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004002 track->mState = TrackBase::STOPPING_2;
4003 }
4004 break;
4005 case TrackBase::PAUSING:
4006 // ramp down is not yet implemented
4007 track->setPaused();
4008 break;
4009 case TrackBase::RESUMING:
4010 // ramp up is not yet implemented
4011 track->mState = TrackBase::ACTIVE;
4012 break;
4013 case TrackBase::ACTIVE:
4014 if (recentFull > 0 || recentPartial > 0) {
4015 // track has provided at least some frames recently: reset retry count
4016 track->mRetryCount = kMaxTrackRetries;
4017 }
4018 if (recentUnderruns == 0) {
4019 // no recent underruns: stay active
4020 break;
4021 }
4022 // there has recently been an underrun of some kind
4023 if (track->sharedBuffer() == 0) {
4024 // were any of the recent underruns "empty" (no frames available)?
4025 if (recentEmpty == 0) {
4026 // no, then ignore the partial underruns as they are allowed indefinitely
4027 break;
4028 }
4029 // there has recently been an "empty" underrun: decrement the retry counter
4030 if (--(track->mRetryCount) > 0) {
4031 break;
4032 }
4033 // indicate to client process that the track was disabled because of underrun;
4034 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004035 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004036 // remove from active list, but state remains ACTIVE [confusing but true]
4037 isActive = false;
4038 break;
4039 }
4040 // fall through
4041 case TrackBase::STOPPING_2:
4042 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004043 case TrackBase::STOPPED:
4044 case TrackBase::FLUSHED: // flush() while active
4045 // Check for presentation complete if track is inactive
4046 // We have consumed all the buffers of this track.
4047 // This would be incomplete if we auto-paused on underrun
4048 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004049 uint32_t latency = 0;
4050 status_t result = mOutput->stream->getLatency(&latency);
4051 ALOGE_IF(result != OK,
4052 "Error when retrieving output stream latency: %d", result);
4053 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004054 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004055 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4056 // track stays in active list until presentation is complete
4057 break;
4058 }
4059 }
4060 if (track->isStopping_2()) {
4061 track->mState = TrackBase::STOPPED;
4062 }
4063 if (track->isStopped()) {
4064 // Can't reset directly, as fast mixer is still polling this track
4065 // track->reset();
4066 // So instead mark this track as needing to be reset after push with ack
4067 resetMask |= 1 << i;
4068 }
4069 isActive = false;
4070 break;
4071 case TrackBase::IDLE:
4072 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004073 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004074 }
4075
4076 if (isActive) {
4077 // was it previously inactive?
4078 if (!(state->mTrackMask & (1 << j))) {
4079 ExtendedAudioBufferProvider *eabp = track;
4080 VolumeProvider *vp = track;
4081 fastTrack->mBufferProvider = eabp;
4082 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004083 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004084 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004085 fastTrack->mGeneration++;
4086 state->mTrackMask |= 1 << j;
4087 didModify = true;
4088 // no acknowledgement required for newly active tracks
4089 }
4090 // cache the combined master volume and stream type volume for fast mixer; this
4091 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004092 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004093 ++fastTracks;
4094 } else {
4095 // was it previously active?
4096 if (state->mTrackMask & (1 << j)) {
4097 fastTrack->mBufferProvider = NULL;
4098 fastTrack->mGeneration++;
4099 state->mTrackMask &= ~(1 << j);
4100 didModify = true;
4101 // If any fast tracks were removed, we must wait for acknowledgement
4102 // because we're about to decrement the last sp<> on those tracks.
4103 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4104 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004105 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4106 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4107 j, track->mState, state->mTrackMask, recentUnderruns,
4108 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004109 }
4110 tracksToRemove->add(track);
4111 // Avoids a misleading display in dumpsys
4112 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4113 }
4114 continue;
4115 }
4116
4117 { // local variable scope to avoid goto warning
4118
4119 audio_track_cblk_t* cblk = track->cblk();
4120
4121 // The first time a track is added we wait
4122 // for all its buffers to be filled before processing it
4123 int name = track->name();
4124 // make sure that we have enough frames to mix one full buffer.
4125 // enforce this condition only once to enable draining the buffer in case the client
4126 // app does not call stop() and relies on underrun to stop:
4127 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4128 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004129 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004130 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004131 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004132
4133 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004134 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004135 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4136 // add frames already consumed but not yet released by the resampler
4137 // because mAudioTrackServerProxy->framesReady() will include these frames
4138 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4139
Eric Laurent81784c32012-11-19 14:55:58 -08004140 uint32_t minFrames = 1;
4141 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4142 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004143 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004144 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004145
4146 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004147 if (ATRACE_ENABLED()) {
4148 // I wish we had formatted trace names
4149 char traceName[16];
4150 strcpy(traceName, "nRdy");
4151 int name = track->name();
4152 if (AudioMixer::TRACK0 <= name &&
4153 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4154 name -= AudioMixer::TRACK0;
4155 traceName[4] = (name / 10) + '0';
4156 traceName[5] = (name % 10) + '0';
4157 } else {
4158 traceName[4] = '?';
4159 traceName[5] = '?';
4160 }
4161 traceName[6] = '\0';
4162 ATRACE_INT(traceName, framesReady);
4163 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004164 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004165 !track->isPaused() && !track->isTerminated())
4166 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004167 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004168
4169 mixedTracks++;
4170
Andy Hung69aed5f2014-02-25 17:24:40 -08004171 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4172 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004173 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004174 if (track->mainBuffer() != mSinkBuffer &&
4175 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004176 if (mEffectBufferEnabled) {
4177 mEffectBufferValid = true; // Later can set directly.
4178 }
Eric Laurent81784c32012-11-19 14:55:58 -08004179 chain = getEffectChain_l(track->sessionId());
4180 // Delegate volume control to effect in track effect chain if needed
4181 if (chain != 0) {
4182 tracksWithEffect++;
4183 } else {
4184 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4185 "session %d",
4186 name, track->sessionId());
4187 }
4188 }
4189
4190
4191 int param = AudioMixer::VOLUME;
4192 if (track->mFillingUpStatus == Track::FS_FILLED) {
4193 // no ramp for the first volume setting
4194 track->mFillingUpStatus = Track::FS_ACTIVE;
4195 if (track->mState == TrackBase::RESUMING) {
4196 track->mState = TrackBase::ACTIVE;
4197 param = AudioMixer::RAMP_VOLUME;
4198 }
4199 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004200 // FIXME should not make a decision based on mServer
4201 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004202 // If the track is stopped before the first frame was mixed,
4203 // do not apply ramp
4204 param = AudioMixer::RAMP_VOLUME;
4205 }
4206
4207 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004208 uint32_t vl, vr; // in U8.24 integer format
4209 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004210 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004211 vl = vr = 0;
4212 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004213 if (track->isPausing()) {
4214 track->setPaused();
4215 }
4216 } else {
4217
4218 // read original volumes with volume control
4219 float typeVolume = mStreamTypes[track->streamType()].volume;
4220 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004221 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004222 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004223 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4224 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004225 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004226 if (vlf > GAIN_FLOAT_UNITY) {
4227 ALOGV("Track left volume out of range: %.3g", vlf);
4228 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004229 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004230 if (vrf > GAIN_FLOAT_UNITY) {
4231 ALOGV("Track right volume out of range: %.3g", vrf);
4232 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004233 }
4234 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004235 vlf *= v;
4236 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004237 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004238 // then derive vl and vr as U8.24 versions for the effect chain
4239 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4240 vl = (uint32_t) (scaleto8_24 * vlf);
4241 vr = (uint32_t) (scaleto8_24 * vrf);
4242 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004243 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004244 // send level comes from shared memory and so may be corrupt
4245 if (sendLevel > MAX_GAIN_INT) {
4246 ALOGV("Track send level out of range: %04X", sendLevel);
4247 sendLevel = MAX_GAIN_INT;
4248 }
Andy Hung6be49402014-05-30 10:42:03 -07004249 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4250 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004251 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004252
Eric Laurent81784c32012-11-19 14:55:58 -08004253 // Delegate volume control to effect in track effect chain if needed
4254 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4255 // Do not ramp volume if volume is controlled by effect
4256 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004257 // Update remaining floating point volume levels
4258 vlf = (float)vl / (1 << 24);
4259 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004260 track->mHasVolumeController = true;
4261 } else {
4262 // force no volume ramp when volume controller was just disabled or removed
4263 // from effect chain to avoid volume spike
4264 if (track->mHasVolumeController) {
4265 param = AudioMixer::VOLUME;
4266 }
4267 track->mHasVolumeController = false;
4268 }
4269
Eric Laurent81784c32012-11-19 14:55:58 -08004270 // XXX: these things DON'T need to be done each time
4271 mAudioMixer->setBufferProvider(name, track);
4272 mAudioMixer->enable(name);
4273
Andy Hung6be49402014-05-30 10:42:03 -07004274 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4275 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4276 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004277 mAudioMixer->setParameter(
4278 name,
4279 AudioMixer::TRACK,
4280 AudioMixer::FORMAT, (void *)track->format());
4281 mAudioMixer->setParameter(
4282 name,
4283 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004284 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004285 mAudioMixer->setParameter(
4286 name,
4287 AudioMixer::TRACK,
4288 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004289 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004290 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004291 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004292 if (reqSampleRate == 0) {
4293 reqSampleRate = mSampleRate;
4294 } else if (reqSampleRate > maxSampleRate) {
4295 reqSampleRate = maxSampleRate;
4296 }
Eric Laurent81784c32012-11-19 14:55:58 -08004297 mAudioMixer->setParameter(
4298 name,
4299 AudioMixer::RESAMPLE,
4300 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004301 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004302
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004303 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004304 mAudioMixer->setParameter(
4305 name,
4306 AudioMixer::TIMESTRETCH,
4307 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004308 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004309
Andy Hung69aed5f2014-02-25 17:24:40 -08004310 /*
4311 * Select the appropriate output buffer for the track.
4312 *
Andy Hung98ef9782014-03-04 14:46:50 -08004313 * Tracks with effects go into their own effects chain buffer
4314 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004315 *
4316 * Other tracks can use mMixerBuffer for higher precision
4317 * channel accumulation. If this buffer is enabled
4318 * (mMixerBufferEnabled true), then selected tracks will accumulate
4319 * into it.
4320 *
4321 */
4322 if (mMixerBufferEnabled
4323 && (track->mainBuffer() == mSinkBuffer
4324 || track->mainBuffer() == mMixerBuffer)) {
4325 mAudioMixer->setParameter(
4326 name,
4327 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004328 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004329 mAudioMixer->setParameter(
4330 name,
4331 AudioMixer::TRACK,
4332 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4333 // TODO: override track->mainBuffer()?
4334 mMixerBufferValid = true;
4335 } else {
4336 mAudioMixer->setParameter(
4337 name,
4338 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004339 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004340 mAudioMixer->setParameter(
4341 name,
4342 AudioMixer::TRACK,
4343 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4344 }
Eric Laurent81784c32012-11-19 14:55:58 -08004345 mAudioMixer->setParameter(
4346 name,
4347 AudioMixer::TRACK,
4348 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4349
4350 // reset retry count
4351 track->mRetryCount = kMaxTrackRetries;
4352
4353 // If one track is ready, set the mixer ready if:
4354 // - the mixer was not ready during previous round OR
4355 // - no other track is not ready
4356 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4357 mixerStatus != MIXER_TRACKS_ENABLED) {
4358 mixerStatus = MIXER_TRACKS_READY;
4359 }
4360 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004361 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004362 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4363 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004364 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004365 } else {
4366 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004367 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004368
Eric Laurent81784c32012-11-19 14:55:58 -08004369 // clear effect chain input buffer if an active track underruns to avoid sending
4370 // previous audio buffer again to effects
4371 chain = getEffectChain_l(track->sessionId());
4372 if (chain != 0) {
4373 chain->clearInputBuffer();
4374 }
4375
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004376 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004377 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4378 track->isStopped() || track->isPaused()) {
4379 // We have consumed all the buffers of this track.
4380 // Remove it from the list of active tracks.
4381 // TODO: use actual buffer filling status instead of latency when available from
4382 // audio HAL
4383 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004384 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004385 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4386 if (track->isStopped()) {
4387 track->reset();
4388 }
4389 tracksToRemove->add(track);
4390 }
4391 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004392 // No buffers for this track. Give it a few chances to
4393 // fill a buffer, then remove it from active list.
4394 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004395 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004396 tracksToRemove->add(track);
4397 // indicate to client process that the track was disabled because of underrun;
4398 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004399 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004400 // If one track is not ready, mark the mixer also not ready if:
4401 // - the mixer was ready during previous round OR
4402 // - no other track is ready
4403 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4404 mixerStatus != MIXER_TRACKS_READY) {
4405 mixerStatus = MIXER_TRACKS_ENABLED;
4406 }
4407 }
4408 mAudioMixer->disable(name);
4409 }
4410
4411 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004412
4413 }
4414
4415 // Push the new FastMixer state if necessary
4416 bool pauseAudioWatchdog = false;
4417 if (didModify) {
4418 state->mFastTracksGen++;
4419 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4420 if (kUseFastMixer == FastMixer_Dynamic &&
4421 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4422 state->mCommand = FastMixerState::COLD_IDLE;
4423 state->mColdFutexAddr = &mFastMixerFutex;
4424 state->mColdGen++;
4425 mFastMixerFutex = 0;
4426 if (kUseFastMixer == FastMixer_Dynamic) {
4427 mNormalSink = mOutputSink;
4428 }
4429 // If we go into cold idle, need to wait for acknowledgement
4430 // so that fast mixer stops doing I/O.
4431 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4432 pauseAudioWatchdog = true;
4433 }
Eric Laurent81784c32012-11-19 14:55:58 -08004434 }
4435 if (sq != NULL) {
4436 sq->end(didModify);
4437 sq->push(block);
4438 }
4439#ifdef AUDIO_WATCHDOG
4440 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4441 mAudioWatchdog->pause();
4442 }
4443#endif
4444
4445 // Now perform the deferred reset on fast tracks that have stopped
4446 while (resetMask != 0) {
4447 size_t i = __builtin_ctz(resetMask);
4448 ALOG_ASSERT(i < count);
4449 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004450 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004451 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4452 track->reset();
4453 }
4454
4455 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004456 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004457
Eric Laurent97d547d2014-09-02 14:45:53 -07004458 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4459 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004460 }
4461
4462 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004463 // as long as there are effects we should clear the effects buffer, to avoid
4464 // passing a non-clean buffer to the effect chain
4465 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004466 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004467 // sink or mix buffer must be cleared if all tracks are connected to an
4468 // effect chain as in this case the mixer will not write to the sink or mix buffer
4469 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004470 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4471 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004472 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004473 if (mMixerBufferValid) {
4474 memset(mMixerBuffer, 0, mMixerBufferSize);
4475 // TODO: In testing, mSinkBuffer below need not be cleared because
4476 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4477 // after mixing.
4478 //
4479 // To enforce this guarantee:
4480 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4481 // (mixedTracks == 0 && fastTracks > 0))
4482 // must imply MIXER_TRACKS_READY.
4483 // Later, we may clear buffers regardless, and skip much of this logic.
4484 }
Andy Hung98ef9782014-03-04 14:46:50 -08004485 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004486 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004487 }
4488
4489 // if any fast tracks, then status is ready
4490 mMixerStatusIgnoringFastTracks = mixerStatus;
4491 if (fastTracks > 0) {
4492 mixerStatus = MIXER_TRACKS_READY;
4493 }
4494 return mixerStatus;
4495}
4496
Eric Laurentad7dd962016-09-22 12:38:37 -07004497// trackCountForUid_l() must be called with ThreadBase::mLock held
4498uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4499{
4500 uint32_t trackCount = 0;
4501 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004502 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004503 trackCount++;
4504 }
4505 }
4506 return trackCount;
4507}
4508
Eric Laurent81784c32012-11-19 14:55:58 -08004509// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004510int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004511 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004512{
Eric Laurentad7dd962016-09-22 12:38:37 -07004513 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4514 return -1;
4515 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004516 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004517}
4518
4519// deleteTrackName_l() must be called with ThreadBase::mLock held
4520void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4521{
4522 ALOGV("remove track (%d) and delete from mixer", name);
4523 mAudioMixer->deleteTrackName(name);
4524}
4525
Eric Laurent10351942014-05-08 18:49:52 -07004526// checkForNewParameter_l() must be called with ThreadBase::mLock held
4527bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4528 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004529{
Eric Laurent81784c32012-11-19 14:55:58 -08004530 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004531 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004532
Eric Laurent10351942014-05-08 18:49:52 -07004533 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004534
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004535 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004536
Eric Laurent10351942014-05-08 18:49:52 -07004537 AudioParameter param = AudioParameter(keyValuePair);
4538 int value;
4539 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4540 reconfig = true;
4541 }
4542 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004543 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004544 status = BAD_VALUE;
4545 } else {
4546 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004547 reconfig = true;
4548 }
Eric Laurent10351942014-05-08 18:49:52 -07004549 }
4550 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004551 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004552 status = BAD_VALUE;
4553 } else {
4554 // no need to save value, since it's constant
4555 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004556 }
Eric Laurent10351942014-05-08 18:49:52 -07004557 }
4558 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4559 // do not accept frame count changes if tracks are open as the track buffer
4560 // size depends on frame count and correct behavior would not be guaranteed
4561 // if frame count is changed after track creation
4562 if (!mTracks.isEmpty()) {
4563 status = INVALID_OPERATION;
4564 } else {
4565 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004566 }
Eric Laurent10351942014-05-08 18:49:52 -07004567 }
4568 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004569#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004570 // when changing the audio output device, call addBatteryData to notify
4571 // the change
4572 if (mOutDevice != value) {
4573 uint32_t params = 0;
4574 // check whether speaker is on
4575 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4576 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004577 }
Eric Laurent10351942014-05-08 18:49:52 -07004578
4579 audio_devices_t deviceWithoutSpeaker
4580 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4581 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004582 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004583 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4584 }
4585
4586 if (params != 0) {
4587 addBatteryData(params);
4588 }
4589 }
Eric Laurent81784c32012-11-19 14:55:58 -08004590#endif
4591
Eric Laurent10351942014-05-08 18:49:52 -07004592 // forward device change to effects that have requested to be
4593 // aware of attached audio device.
4594 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004595 a2dpDeviceChanged =
4596 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004597 mOutDevice = value;
4598 for (size_t i = 0; i < mEffectChains.size(); i++) {
4599 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004600 }
4601 }
Eric Laurent10351942014-05-08 18:49:52 -07004602 }
Eric Laurent81784c32012-11-19 14:55:58 -08004603
Eric Laurent10351942014-05-08 18:49:52 -07004604 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004605 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004606 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004607 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004608 mStandby = true;
4609 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004610 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004611 }
Eric Laurent10351942014-05-08 18:49:52 -07004612 if (status == NO_ERROR && reconfig) {
4613 readOutputParameters_l();
4614 delete mAudioMixer;
4615 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4616 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004617 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004618 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004619 if (name < 0) {
4620 break;
4621 }
4622 mTracks[i]->mName = name;
4623 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004624 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004625 }
Eric Laurent81784c32012-11-19 14:55:58 -08004626 }
4627
Eric Laurent42537be2016-01-08 17:16:42 -08004628 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004629}
4630
4631
4632void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4633{
Eric Laurent81784c32012-11-19 14:55:58 -08004634 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004635 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004636 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004637 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004638
4639 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004640 // while we are dumping it. It may be inconsistent, but it won't mutate!
4641 // This is a large object so we place it on the heap.
4642 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4643 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4644 copy->dump(fd);
4645 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004646
4647#ifdef STATE_QUEUE_DUMP
4648 // Similar for state queue
4649 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4650 observerCopy.dump(fd);
4651 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4652 mutatorCopy.dump(fd);
4653#endif
4654
Glenn Kasten46909e72013-02-26 09:20:22 -08004655#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004656 // Write the tee output to a .wav file
4657 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004658#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004659
4660#ifdef AUDIO_WATCHDOG
4661 if (mAudioWatchdog != 0) {
4662 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4663 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4664 wdCopy.dump(fd);
4665 }
4666#endif
4667}
4668
4669uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4670{
4671 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4672}
4673
4674uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4675{
4676 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4677}
4678
4679void AudioFlinger::MixerThread::cacheParameters_l()
4680{
4681 PlaybackThread::cacheParameters_l();
4682
4683 // FIXME: Relaxed timing because of a certain device that can't meet latency
4684 // Should be reduced to 2x after the vendor fixes the driver issue
4685 // increase threshold again due to low power audio mode. The way this warning
4686 // threshold is calculated and its usefulness should be reconsidered anyway.
4687 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4688}
4689
4690// ----------------------------------------------------------------------------
4691
4692AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004693 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4694 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004695 // mLeftVolFloat, mRightVolFloat
4696{
4697}
4698
Eric Laurentbfb1b832013-01-07 09:53:42 -08004699AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4700 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004701 ThreadBase::type_t type, bool systemReady)
4702 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004703 // mLeftVolFloat, mRightVolFloat
4704{
4705}
4706
Eric Laurent81784c32012-11-19 14:55:58 -08004707AudioFlinger::DirectOutputThread::~DirectOutputThread()
4708{
4709}
4710
Eric Laurent5850c4c2016-11-10 13:04:31 -08004711void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004712{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004713 float left, right;
4714
4715 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4716 left = right = 0;
4717 } else {
4718 float typeVolume = mStreamTypes[track->streamType()].volume;
4719 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004720 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004721 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4722 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4723 if (left > GAIN_FLOAT_UNITY) {
4724 left = GAIN_FLOAT_UNITY;
4725 }
4726 left *= v;
4727 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4728 if (right > GAIN_FLOAT_UNITY) {
4729 right = GAIN_FLOAT_UNITY;
4730 }
4731 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004732 }
4733
4734 if (lastTrack) {
4735 if (left != mLeftVolFloat || right != mRightVolFloat) {
4736 mLeftVolFloat = left;
4737 mRightVolFloat = right;
4738
4739 // Convert volumes from float to 8.24
4740 uint32_t vl = (uint32_t)(left * (1 << 24));
4741 uint32_t vr = (uint32_t)(right * (1 << 24));
4742
4743 // Delegate volume control to effect in track effect chain if needed
4744 // only one effect chain can be present on DirectOutputThread, so if
4745 // there is one, the track is connected to it
4746 if (!mEffectChains.isEmpty()) {
4747 mEffectChains[0]->setVolume_l(&vl, &vr);
4748 left = (float)vl / (1 << 24);
4749 right = (float)vr / (1 << 24);
4750 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004751 status_t result = mOutput->stream->setVolume(left, right);
4752 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004753 }
4754 }
4755}
4756
Phil Burk43b4dcc2015-06-09 16:53:44 -07004757void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4758{
4759 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004760 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004761
Eric Laurent0f0631e2015-07-06 18:01:25 -07004762 if (previousTrack != 0 && latestTrack != 0) {
4763 if (mType == DIRECT) {
4764 if (previousTrack.get() != latestTrack.get()) {
4765 mFlushPending = true;
4766 }
4767 } else /* mType == OFFLOAD */ {
4768 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4769 mFlushPending = true;
4770 }
4771 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004772 }
4773 PlaybackThread::onAddNewTrack_l();
4774}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004775
Eric Laurent81784c32012-11-19 14:55:58 -08004776AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4777 Vector< sp<Track> > *tracksToRemove
4778)
4779{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004780 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004781 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004782 bool doHwPause = false;
4783 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004784
4785 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004786 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004787 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004788 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004789 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004790 continue;
4791 }
4792
Eric Laurent5850c4c2016-11-10 13:04:31 -08004793 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004794#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004795 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004796#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004797 // Only consider last track started for volume and mixer state control.
4798 // In theory an older track could underrun and restart after the new one starts
4799 // but as we only care about the transition phase between two tracks on a
4800 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004801 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004802 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004803
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004804 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004805 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004806 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004807 doHwPause = true;
4808 mHwPaused = true;
4809 }
4810 tracksToRemove->add(track);
4811 } else if (track->isFlushPending()) {
4812 track->flushAck();
4813 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004814 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004815 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004816 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004817 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004818 if (last) {
4819 mLeftVolFloat = mRightVolFloat = -1.0;
4820 if (mHwPaused) {
4821 doHwResume = true;
4822 mHwPaused = false;
4823 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004824 }
4825 }
4826
Eric Laurent81784c32012-11-19 14:55:58 -08004827 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004828 // for all its buffers to be filled before processing it.
4829 // Allow draining the buffer in case the client
4830 // app does not call stop() and relies on underrun to stop:
4831 // hence the test on (track->mRetryCount > 1).
4832 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004833 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004834 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004835 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004836 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004837 minFrames = mNormalFrameCount;
4838 } else {
4839 minFrames = 1;
4840 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004841
Eric Laurentab5cdba2014-06-09 17:22:27 -07004842 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4843 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004844 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004845 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004846
4847 if (track->mFillingUpStatus == Track::FS_FILLED) {
4848 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004849 if (last) {
4850 // make sure processVolume_l() will apply new volume even if 0
4851 mLeftVolFloat = mRightVolFloat = -1.0;
4852 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004853 if (!mHwSupportsPause) {
4854 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004855 }
4856 }
4857
4858 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004859 processVolume_l(track, last);
4860 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004861 sp<Track> previousTrack = mPreviousTrack.promote();
4862 if (previousTrack != 0) {
4863 if (track != previousTrack.get()) {
4864 // Flush any data still being written from last track
4865 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004866 // Invalidate previous track to force a seek when resuming.
4867 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004868 }
4869 }
4870 mPreviousTrack = track;
4871
Eric Laurentd595b7c2013-04-03 17:27:56 -07004872 // reset retry count
4873 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004874 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004875 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004876 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004877 doHwResume = true;
4878 mHwPaused = false;
4879 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004880 }
Eric Laurent81784c32012-11-19 14:55:58 -08004881 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004882 // clear effect chain input buffer if the last active track started underruns
4883 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004884 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004885 mEffectChains[0]->clearInputBuffer();
4886 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004887 if (track->isStopping_1()) {
4888 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004889 if (last && mHwPaused) {
4890 doHwResume = true;
4891 mHwPaused = false;
4892 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004893 }
4894 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4895 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004896 // We have consumed all the buffers of this track.
4897 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004898 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004899 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004900 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4901 } else {
4902 audioHALFrames = 0;
4903 }
4904
Andy Hung818e7a32016-02-16 18:08:07 -08004905 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004906 if (mStandby || !last ||
4907 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004908 if (track->isStopping_2()) {
4909 track->mState = TrackBase::STOPPED;
4910 }
Eric Laurent81784c32012-11-19 14:55:58 -08004911 if (track->isStopped()) {
4912 track->reset();
4913 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004914 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004915 }
4916 } else {
4917 // No buffers for this track. Give it a few chances to
4918 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004919 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004920 if (--(track->mRetryCount) <= 0) {
4921 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004922 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004923 // indicate to client process that the track was disabled because of underrun;
4924 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004925 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004926 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004927 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4928 "minFrames = %u, mFormat = %#x",
4929 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004930 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004931 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004932 doHwPause = true;
4933 mHwPaused = true;
4934 }
Eric Laurent81784c32012-11-19 14:55:58 -08004935 }
4936 }
4937 }
4938 }
4939
Eric Laurentd1f69b02014-12-15 14:33:13 -08004940 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004941 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004942 for (size_t i = 0; i < mTracks.size(); i++) {
4943 if (mTracks[i]->isFlushPending()) {
4944 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004945 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004946 }
4947 }
4948 }
4949
4950 // make sure the pause/flush/resume sequence is executed in the right order.
4951 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4952 // before flush and then resume HW. This can happen in case of pause/flush/resume
4953 // if resume is received before pause is executed.
4954 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004955 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004956 status_t result = mOutput->stream->pause();
4957 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004958 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004959 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004960 flushHw_l();
4961 }
4962 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004963 status_t result = mOutput->stream->resume();
4964 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004965 }
Eric Laurent81784c32012-11-19 14:55:58 -08004966 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004967 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004968
4969 return mixerStatus;
4970}
4971
4972void AudioFlinger::DirectOutputThread::threadLoop_mix()
4973{
Eric Laurent81784c32012-11-19 14:55:58 -08004974 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004975 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004976 // output audio to hardware
4977 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004978 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004979 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004980 status_t status = mActiveTrack->getNextBuffer(&buffer);
4981 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004982 // no need to pad with 0 for compressed audio
4983 if (audio_has_proportional_frames(mFormat)) {
4984 memset(curBuf, 0, frameCount * mFrameSize);
4985 }
Eric Laurent81784c32012-11-19 14:55:58 -08004986 break;
4987 }
4988 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4989 frameCount -= buffer.frameCount;
4990 curBuf += buffer.frameCount * mFrameSize;
4991 mActiveTrack->releaseBuffer(&buffer);
4992 }
Andy Hung2098f272014-02-27 14:00:06 -08004993 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004994 mSleepTimeUs = 0;
4995 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004996 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004997}
4998
4999void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5000{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005001 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005002 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005003 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005004 return;
5005 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005006 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005007 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005008 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005009 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005010 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005011 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005012 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005013 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005014 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005015 }
5016}
5017
Eric Laurentd1f69b02014-12-15 14:33:13 -08005018void AudioFlinger::DirectOutputThread::threadLoop_exit()
5019{
5020 {
5021 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005022 for (size_t i = 0; i < mTracks.size(); i++) {
5023 if (mTracks[i]->isFlushPending()) {
5024 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005025 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005026 }
5027 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005028 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005029 flushHw_l();
5030 }
5031 }
5032 PlaybackThread::threadLoop_exit();
5033}
5034
5035// must be called with thread mutex locked
5036bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5037{
5038 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005039 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005040
vivek mehta9cd7ad12016-03-17 00:18:29 -07005041 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5042 return !mStandby;
5043 }
5044
Eric Laurentd1f69b02014-12-15 14:33:13 -08005045 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5046 // after a timeout and we will enter standby then.
5047 if (mTracks.size() > 0) {
5048 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005049 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5050 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005051 }
5052
Eric Laurent5cff4032015-05-26 13:49:58 -07005053 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005054}
5055
Eric Laurent81784c32012-11-19 14:55:58 -08005056// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005057int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005058 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005059{
Eric Laurentad7dd962016-09-22 12:38:37 -07005060 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5061 return -1;
5062 }
Eric Laurent81784c32012-11-19 14:55:58 -08005063 return 0;
5064}
5065
5066// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005067void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005068{
5069}
5070
Eric Laurent10351942014-05-08 18:49:52 -07005071// checkForNewParameter_l() must be called with ThreadBase::mLock held
5072bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5073 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005074{
5075 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005076 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005077
Eric Laurent10351942014-05-08 18:49:52 -07005078 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005079
Eric Laurent10351942014-05-08 18:49:52 -07005080 AudioParameter param = AudioParameter(keyValuePair);
5081 int value;
5082 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5083 // forward device change to effects that have requested to be
5084 // aware of attached audio device.
5085 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005086 a2dpDeviceChanged =
5087 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005088 mOutDevice = value;
5089 for (size_t i = 0; i < mEffectChains.size(); i++) {
5090 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005091 }
5092 }
Eric Laurent81784c32012-11-19 14:55:58 -08005093 }
Eric Laurent10351942014-05-08 18:49:52 -07005094 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5095 // do not accept frame count changes if tracks are open as the track buffer
5096 // size depends on frame count and correct behavior would not be garantied
5097 // if frame count is changed after track creation
5098 if (!mTracks.isEmpty()) {
5099 status = INVALID_OPERATION;
5100 } else {
5101 reconfig = true;
5102 }
5103 }
5104 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005105 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005106 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005107 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005108 mStandby = true;
5109 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005110 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005111 }
5112 if (status == NO_ERROR && reconfig) {
5113 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005114 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005115 }
5116 }
5117
Eric Laurent42537be2016-01-08 17:16:42 -08005118 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005119}
5120
5121uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5122{
5123 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005124 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005125 time = PlaybackThread::activeSleepTimeUs();
5126 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005127 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005128 }
5129 return time;
5130}
5131
5132uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5133{
5134 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005135 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005136 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5137 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005138 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005139 }
5140 return time;
5141}
5142
5143uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5144{
5145 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005146 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005147 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5148 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005149 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005150 }
5151 return time;
5152}
5153
5154void AudioFlinger::DirectOutputThread::cacheParameters_l()
5155{
5156 PlaybackThread::cacheParameters_l();
5157
5158 // use shorter standby delay as on normal output to release
5159 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005160 // no delay on outputs with HW A/V sync
5161 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005162 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005163 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005164 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005165 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005166 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005167 }
Eric Laurent81784c32012-11-19 14:55:58 -08005168}
5169
Eric Laurente659ef42014-09-29 13:06:46 -07005170void AudioFlinger::DirectOutputThread::flushHw_l()
5171{
Phil Burk062e67a2015-02-11 13:40:50 -08005172 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005173 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005174 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005175}
5176
Eric Laurent81784c32012-11-19 14:55:58 -08005177// ----------------------------------------------------------------------------
5178
Eric Laurentbfb1b832013-01-07 09:53:42 -08005179AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005180 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005181 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005182 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005183 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005184 mDrainSequence(0),
5185 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005186{
5187}
5188
5189AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5190{
5191}
5192
5193void AudioFlinger::AsyncCallbackThread::onFirstRef()
5194{
5195 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5196}
5197
5198bool AudioFlinger::AsyncCallbackThread::threadLoop()
5199{
5200 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005201 uint32_t writeAckSequence;
5202 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005203 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005204
5205 {
5206 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005207 while (!((mWriteAckSequence & 1) ||
5208 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005209 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005210 exitPending())) {
5211 mWaitWorkCV.wait(mLock);
5212 }
5213
Eric Laurentbfb1b832013-01-07 09:53:42 -08005214 if (exitPending()) {
5215 break;
5216 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005217 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5218 mWriteAckSequence, mDrainSequence);
5219 writeAckSequence = mWriteAckSequence;
5220 mWriteAckSequence &= ~1;
5221 drainSequence = mDrainSequence;
5222 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005223 asyncError = mAsyncError;
5224 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005225 }
5226 {
Eric Laurent4de95592013-09-26 15:28:21 -07005227 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5228 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005229 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005230 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005231 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005232 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005233 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005234 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005235 if (asyncError) {
5236 playbackThread->onAsyncError();
5237 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005238 }
5239 }
5240 }
5241 return false;
5242}
5243
5244void AudioFlinger::AsyncCallbackThread::exit()
5245{
5246 ALOGV("AsyncCallbackThread::exit");
5247 Mutex::Autolock _l(mLock);
5248 requestExit();
5249 mWaitWorkCV.broadcast();
5250}
5251
Eric Laurent3b4529e2013-09-05 18:09:19 -07005252void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005253{
5254 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005255 // bit 0 is cleared
5256 mWriteAckSequence = sequence << 1;
5257}
5258
5259void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5260{
5261 Mutex::Autolock _l(mLock);
5262 // ignore unexpected callbacks
5263 if (mWriteAckSequence & 2) {
5264 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005265 mWaitWorkCV.signal();
5266 }
5267}
5268
Eric Laurent3b4529e2013-09-05 18:09:19 -07005269void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005270{
5271 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005272 // bit 0 is cleared
5273 mDrainSequence = sequence << 1;
5274}
5275
5276void AudioFlinger::AsyncCallbackThread::resetDraining()
5277{
5278 Mutex::Autolock _l(mLock);
5279 // ignore unexpected callbacks
5280 if (mDrainSequence & 2) {
5281 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005282 mWaitWorkCV.signal();
5283 }
5284}
5285
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005286void AudioFlinger::AsyncCallbackThread::setAsyncError()
5287{
5288 Mutex::Autolock _l(mLock);
5289 mAsyncError = true;
5290 mWaitWorkCV.signal();
5291}
5292
Eric Laurentbfb1b832013-01-07 09:53:42 -08005293
5294// ----------------------------------------------------------------------------
5295AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005296 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5297 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005298 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5299 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005300{
Eric Laurentfd477972013-10-25 18:10:40 -07005301 //FIXME: mStandby should be set to true by ThreadBase constructor
5302 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005303 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304}
5305
Eric Laurentbfb1b832013-01-07 09:53:42 -08005306void AudioFlinger::OffloadThread::threadLoop_exit()
5307{
5308 if (mFlushPending || mHwPaused) {
5309 // If a flush is pending or track was paused, just discard buffered data
5310 flushHw_l();
5311 } else {
5312 mMixerStatus = MIXER_DRAIN_ALL;
5313 threadLoop_drain();
5314 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005315 if (mUseAsyncWrite) {
5316 ALOG_ASSERT(mCallbackThread != 0);
5317 mCallbackThread->exit();
5318 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005319 PlaybackThread::threadLoop_exit();
5320}
5321
5322AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5323 Vector< sp<Track> > *tracksToRemove
5324)
5325{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005326 size_t count = mActiveTracks.size();
5327
5328 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005329 bool doHwPause = false;
5330 bool doHwResume = false;
5331
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005332 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005333
Eric Laurentbfb1b832013-01-07 09:53:42 -08005334 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005335 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005336 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005337#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005338 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005339#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005340 // Only consider last track started for volume and mixer state control.
5341 // In theory an older track could underrun and restart after the new one starts
5342 // but as we only care about the transition phase between two tracks on a
5343 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005344 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005345 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005346
Haynes Mathew George7844f672014-01-15 12:32:55 -08005347 if (track->isInvalid()) {
5348 ALOGW("An invalidated track shouldn't be in active list");
5349 tracksToRemove->add(track);
5350 continue;
5351 }
5352
5353 if (track->mState == TrackBase::IDLE) {
5354 ALOGW("An idle track shouldn't be in active list");
5355 continue;
5356 }
5357
Eric Laurentbfb1b832013-01-07 09:53:42 -08005358 if (track->isPausing()) {
5359 track->setPaused();
5360 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005361 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005362 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005363 mHwPaused = true;
5364 }
5365 // If we were part way through writing the mixbuffer to
5366 // the HAL we must save this until we resume
5367 // BUG - this will be wrong if a different track is made active,
5368 // in that case we want to discard the pending data in the
5369 // mixbuffer and tell the client to present it again when the
5370 // track is resumed
5371 mPausedWriteLength = mCurrentWriteLength;
5372 mPausedBytesRemaining = mBytesRemaining;
5373 mBytesRemaining = 0; // stop writing
5374 }
5375 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005376 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005377 if (track->isStopping_1()) {
5378 track->mRetryCount = kMaxTrackStopRetriesOffload;
5379 } else {
5380 track->mRetryCount = kMaxTrackRetriesOffload;
5381 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005382 track->flushAck();
5383 if (last) {
5384 mFlushPending = true;
5385 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005386 } else if (track->isResumePending()){
5387 track->resumeAck();
5388 if (last) {
5389 if (mPausedBytesRemaining) {
5390 // Need to continue write that was interrupted
5391 mCurrentWriteLength = mPausedWriteLength;
5392 mBytesRemaining = mPausedBytesRemaining;
5393 mPausedBytesRemaining = 0;
5394 }
5395 if (mHwPaused) {
5396 doHwResume = true;
5397 mHwPaused = false;
5398 // threadLoop_mix() will handle the case that we need to
5399 // resume an interrupted write
5400 }
5401 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005402 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005403
Eric Laurent3df841a2016-07-15 15:15:40 -07005404 mLeftVolFloat = mRightVolFloat = -1.0;
5405
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005406 // Do not handle new data in this iteration even if track->framesReady()
5407 mixerStatus = MIXER_TRACKS_ENABLED;
5408 }
5409 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005410 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005411 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005412 if (track->mFillingUpStatus == Track::FS_FILLED) {
5413 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005414 if (last) {
5415 // make sure processVolume_l() will apply new volume even if 0
5416 mLeftVolFloat = mRightVolFloat = -1.0;
5417 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005418 }
5419
5420 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005421 sp<Track> previousTrack = mPreviousTrack.promote();
5422 if (previousTrack != 0) {
5423 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005424 // Flush any data still being written from last track
5425 mBytesRemaining = 0;
5426 if (mPausedBytesRemaining) {
5427 // Last track was paused so we also need to flush saved
5428 // mixbuffer state and invalidate track so that it will
5429 // re-submit that unwritten data when it is next resumed
5430 mPausedBytesRemaining = 0;
5431 // Invalidate is a bit drastic - would be more efficient
5432 // to have a flag to tell client that some of the
5433 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005434 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005435 }
5436 // flush data already sent to the DSP if changing audio session as audio
5437 // comes from a different source. Also invalidate previous track to force a
5438 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005439 if (previousTrack->sessionId() != track->sessionId()) {
5440 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005441 }
5442 }
5443 }
5444 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005445 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005446 if (track->isStopping_1()) {
5447 track->mRetryCount = kMaxTrackStopRetriesOffload;
5448 } else {
5449 track->mRetryCount = kMaxTrackRetriesOffload;
5450 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005451 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005452 mixerStatus = MIXER_TRACKS_READY;
5453 }
5454 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005455 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005456 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005457 if (--(track->mRetryCount) <= 0) {
5458 // Hardware buffer can hold a large amount of audio so we must
5459 // wait for all current track's data to drain before we say
5460 // that the track is stopped.
5461 if (mBytesRemaining == 0) {
5462 // Only start draining when all data in mixbuffer
5463 // has been written
5464 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5465 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5466 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5467 if (last && !mStandby) {
5468 // do not modify drain sequence if we are already draining. This happens
5469 // when resuming from pause after drain.
5470 if ((mDrainSequence & 1) == 0) {
5471 mSleepTimeUs = 0;
5472 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5473 mixerStatus = MIXER_DRAIN_TRACK;
5474 mDrainSequence += 2;
5475 }
5476 if (mHwPaused) {
5477 // It is possible to move from PAUSED to STOPPING_1 without
5478 // a resume so we must ensure hardware is running
5479 doHwResume = true;
5480 mHwPaused = false;
5481 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 }
5483 }
Eric Laurente93cc032016-05-05 10:15:10 -07005484 } else if (last) {
5485 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5486 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005487 }
5488 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005489 // Drain has completed or we are in standby, signal presentation complete
5490 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005491 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005492 uint32_t latency = 0;
5493 status_t result = mOutput->stream->getLatency(&latency);
5494 ALOGE_IF(result != OK,
5495 "Error when retrieving output stream latency: %d", result);
5496 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005497 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005498 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005499 track->presentationComplete(framesWritten, audioHALFrames);
5500 track->reset();
5501 tracksToRemove->add(track);
5502 }
5503 } else {
5504 // No buffers for this track. Give it a few chances to
5505 // fill a buffer, then remove it from active list.
5506 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005507 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005508 uint64_t position = 0;
5509 struct timespec unused;
5510 // The running check restarts the retry counter at least once.
5511 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5512 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5513 running = true;
5514 mOffloadUnderrunPosition = position;
5515 }
5516 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005517 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5518 (long long)position, (long long)mOffloadUnderrunPosition);
5519 }
5520 if (running) { // still running, give us more time.
5521 track->mRetryCount = kMaxTrackRetriesOffload;
5522 } else {
5523 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5524 track->name());
5525 tracksToRemove->add(track);
5526 // indicate to client process that the track was disabled because of underrun;
5527 // it will then automatically call start() when data is available
5528 track->disable();
5529 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005530 } else if (last){
5531 mixerStatus = MIXER_TRACKS_ENABLED;
5532 }
5533 }
5534 }
5535 // compute volume for this track
5536 processVolume_l(track, last);
5537 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005538
Eric Laurentea0fade2013-10-04 16:23:48 -07005539 // make sure the pause/flush/resume sequence is executed in the right order.
5540 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5541 // before flush and then resume HW. This can happen in case of pause/flush/resume
5542 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005543 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005544 status_t result = mOutput->stream->pause();
5545 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005546 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005547 if (mFlushPending) {
5548 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005549 }
Eric Laurentfd477972013-10-25 18:10:40 -07005550 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005551 status_t result = mOutput->stream->resume();
5552 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005553 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005554
Eric Laurentbfb1b832013-01-07 09:53:42 -08005555 // remove all the tracks that need to be...
5556 removeTracks_l(*tracksToRemove);
5557
5558 return mixerStatus;
5559}
5560
Eric Laurentbfb1b832013-01-07 09:53:42 -08005561// must be called with thread mutex locked
5562bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5563{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005564 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5565 mWriteAckSequence, mDrainSequence);
5566 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005567 return true;
5568 }
5569 return false;
5570}
5571
Eric Laurentbfb1b832013-01-07 09:53:42 -08005572bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5573{
5574 Mutex::Autolock _l(mLock);
5575 return waitingAsyncCallback_l();
5576}
5577
5578void AudioFlinger::OffloadThread::flushHw_l()
5579{
Eric Laurente659ef42014-09-29 13:06:46 -07005580 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581 // Flush anything still waiting in the mixbuffer
5582 mCurrentWriteLength = 0;
5583 mBytesRemaining = 0;
5584 mPausedWriteLength = 0;
5585 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005586 // reset bytes written count to reflect that DSP buffers are empty after flush.
5587 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005588 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005589
Eric Laurentbfb1b832013-01-07 09:53:42 -08005590 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005591 // discard any pending drain or write ack by incrementing sequence
5592 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5593 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005594 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005595 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5596 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005597 }
5598}
5599
Haynes Mathew George05317d22016-05-03 16:34:26 -07005600void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5601{
5602 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005603 if (PlaybackThread::invalidateTracks_l(streamType)) {
5604 mFlushPending = true;
5605 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005606}
5607
Eric Laurentbfb1b832013-01-07 09:53:42 -08005608// ----------------------------------------------------------------------------
5609
Eric Laurent81784c32012-11-19 14:55:58 -08005610AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005611 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005612 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005613 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005614 mWaitTimeMs(UINT_MAX)
5615{
5616 addOutputTrack(mainThread);
5617}
5618
5619AudioFlinger::DuplicatingThread::~DuplicatingThread()
5620{
5621 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5622 mOutputTracks[i]->destroy();
5623 }
5624}
5625
5626void AudioFlinger::DuplicatingThread::threadLoop_mix()
5627{
5628 // mix buffers...
5629 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005630 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005631 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005632 if (mMixerBufferValid) {
5633 memset(mMixerBuffer, 0, mMixerBufferSize);
5634 } else {
5635 memset(mSinkBuffer, 0, mSinkBufferSize);
5636 }
Eric Laurent81784c32012-11-19 14:55:58 -08005637 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005638 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005639 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005640 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005641 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005642}
5643
5644void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5645{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005646 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005647 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005648 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005649 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005650 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005651 }
5652 } else if (mBytesWritten != 0) {
5653 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5654 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005655 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005656 } else {
5657 // flush remaining overflow buffers in output tracks
5658 writeFrames = 0;
5659 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005660 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005661 }
5662}
5663
Eric Laurentbfb1b832013-01-07 09:53:42 -08005664ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005665{
5666 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005667 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005668 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005669 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005670 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005671}
5672
5673void AudioFlinger::DuplicatingThread::threadLoop_standby()
5674{
5675 // DuplicatingThread implements standby by stopping all tracks
5676 for (size_t i = 0; i < outputTracks.size(); i++) {
5677 outputTracks[i]->stop();
5678 }
5679}
5680
5681void AudioFlinger::DuplicatingThread::saveOutputTracks()
5682{
5683 outputTracks = mOutputTracks;
5684}
5685
5686void AudioFlinger::DuplicatingThread::clearOutputTracks()
5687{
5688 outputTracks.clear();
5689}
5690
5691void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5692{
5693 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005694 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5695 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5696 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5697 const size_t frameCount =
5698 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5699 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5700 // from different OutputTracks and their associated MixerThreads (e.g. one may
5701 // nearly empty and the other may be dropping data).
5702
5703 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005704 this,
5705 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005706 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005707 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005708 frameCount,
5709 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005710 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5711 if (status != NO_ERROR) {
5712 ALOGE("addOutputTrack() initCheck failed %d", status);
5713 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005714 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005715 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5716 mOutputTracks.add(outputTrack);
5717 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5718 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005719}
5720
5721void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5722{
5723 Mutex::Autolock _l(mLock);
5724 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5725 if (mOutputTracks[i]->thread() == thread) {
5726 mOutputTracks[i]->destroy();
5727 mOutputTracks.removeAt(i);
5728 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005729 if (thread->getOutput() == mOutput) {
5730 mOutput = NULL;
5731 }
Eric Laurent81784c32012-11-19 14:55:58 -08005732 return;
5733 }
5734 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005735 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005736}
5737
5738// caller must hold mLock
5739void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5740{
5741 mWaitTimeMs = UINT_MAX;
5742 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5743 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5744 if (strong != 0) {
5745 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5746 if (waitTimeMs < mWaitTimeMs) {
5747 mWaitTimeMs = waitTimeMs;
5748 }
5749 }
5750 }
5751}
5752
5753
5754bool AudioFlinger::DuplicatingThread::outputsReady(
5755 const SortedVector< sp<OutputTrack> > &outputTracks)
5756{
5757 for (size_t i = 0; i < outputTracks.size(); i++) {
5758 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5759 if (thread == 0) {
5760 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5761 outputTracks[i].get());
5762 return false;
5763 }
5764 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5765 // see note at standby() declaration
5766 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5767 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5768 thread.get());
5769 return false;
5770 }
5771 }
5772 return true;
5773}
5774
5775uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5776{
5777 return (mWaitTimeMs * 1000) / 2;
5778}
5779
5780void AudioFlinger::DuplicatingThread::cacheParameters_l()
5781{
5782 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5783 updateWaitTime_l();
5784
5785 MixerThread::cacheParameters_l();
5786}
5787
5788// ----------------------------------------------------------------------------
5789// Record
5790// ----------------------------------------------------------------------------
5791
5792AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5793 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005794 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005795 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005796 audio_devices_t inDevice,
5797 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005798#ifdef TEE_SINK
5799 , const sp<NBAIO_Sink>& teeSink
5800#endif
5801 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005802 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005803 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005804 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005805 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005806#ifdef TEE_SINK
5807 , mTeeSink(teeSink)
5808#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005809 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5810 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005811 // mFastCapture below
5812 , mFastCaptureFutex(0)
5813 // mInputSource
5814 // mPipeSink
5815 // mPipeSource
5816 , mPipeFramesP2(0)
5817 // mPipeMemory
5818 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005819 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005820{
Glenn Kastend7dca052015-03-05 16:05:54 -08005821 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5822 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005823
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005824 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005825
5826 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005827 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005828 size_t numCounterOffers = 0;
5829 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005830#if !LOG_NDEBUG
5831 ssize_t index =
5832#else
5833 (void)
5834#endif
5835 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005836 ALOG_ASSERT(index == 0);
5837
5838 // initialize fast capture depending on configuration
5839 bool initFastCapture;
5840 switch (kUseFastCapture) {
5841 case FastCapture_Never:
5842 initFastCapture = false;
5843 break;
5844 case FastCapture_Always:
5845 initFastCapture = true;
5846 break;
5847 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005848 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005849 break;
5850 // case FastCapture_Dynamic:
5851 }
5852
5853 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005854 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005855 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005856 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5857 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005858 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5859 void *pipeBuffer;
5860 const sp<MemoryDealer> roHeap(readOnlyHeap());
5861 sp<IMemory> pipeMemory;
5862 if ((roHeap == 0) ||
5863 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5864 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5865 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5866 goto failed;
5867 }
5868 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5869 memset(pipeBuffer, 0, pipeSize);
5870 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5871 const NBAIO_Format offers[1] = {format};
5872 size_t numCounterOffers = 0;
5873 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5874 ALOG_ASSERT(index == 0);
5875 mPipeSink = pipe;
5876 PipeReader *pipeReader = new PipeReader(*pipe);
5877 numCounterOffers = 0;
5878 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5879 ALOG_ASSERT(index == 0);
5880 mPipeSource = pipeReader;
5881 mPipeFramesP2 = pipeFramesP2;
5882 mPipeMemory = pipeMemory;
5883
5884 // create fast capture
5885 mFastCapture = new FastCapture();
5886 FastCaptureStateQueue *sq = mFastCapture->sq();
5887#ifdef STATE_QUEUE_DUMP
5888 // FIXME
5889#endif
5890 FastCaptureState *state = sq->begin();
5891 state->mCblk = NULL;
5892 state->mInputSource = mInputSource.get();
5893 state->mInputSourceGen++;
5894 state->mPipeSink = pipe;
5895 state->mPipeSinkGen++;
5896 state->mFrameCount = mFrameCount;
5897 state->mCommand = FastCaptureState::COLD_IDLE;
5898 // already done in constructor initialization list
5899 //mFastCaptureFutex = 0;
5900 state->mColdFutexAddr = &mFastCaptureFutex;
5901 state->mColdGen++;
5902 state->mDumpState = &mFastCaptureDumpState;
5903#ifdef TEE_SINK
5904 // FIXME
5905#endif
5906 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5907 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5908 sq->end();
5909 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5910
5911 // start the fast capture
5912 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5913 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005914 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005915 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005916#ifdef AUDIO_WATCHDOG
5917 // FIXME
5918#endif
5919
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005920 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005921 }
5922failed: ;
5923
5924 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005925}
5926
Eric Laurent81784c32012-11-19 14:55:58 -08005927AudioFlinger::RecordThread::~RecordThread()
5928{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005929 if (mFastCapture != 0) {
5930 FastCaptureStateQueue *sq = mFastCapture->sq();
5931 FastCaptureState *state = sq->begin();
5932 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5933 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5934 if (old == -1) {
5935 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5936 }
5937 }
5938 state->mCommand = FastCaptureState::EXIT;
5939 sq->end();
5940 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5941 mFastCapture->join();
5942 mFastCapture.clear();
5943 }
5944 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005945 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005946 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005947}
5948
5949void AudioFlinger::RecordThread::onFirstRef()
5950{
Glenn Kastend7dca052015-03-05 16:05:54 -08005951 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005952}
5953
Eric Laurent81784c32012-11-19 14:55:58 -08005954bool AudioFlinger::RecordThread::threadLoop()
5955{
Eric Laurent81784c32012-11-19 14:55:58 -08005956 nsecs_t lastWarning = 0;
5957
5958 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005959
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005960reacquire_wakelock:
5961 sp<RecordTrack> activeTrack;
5962 {
5963 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07005964 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005965 }
5966
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005967 // used to request a deferred sleep, to be executed later while mutex is unlocked
5968 uint32_t sleepUs = 0;
5969
5970 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005971 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005972 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005973
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005974 // activeTracks accumulates a copy of a subset of mActiveTracks
5975 Vector< sp<RecordTrack> > activeTracks;
5976
Glenn Kasten735f45f2014-08-18 15:51:59 -07005977 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005978 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005979
Glenn Kasten735f45f2014-08-18 15:51:59 -07005980 // reference to a fast track which is about to be removed
5981 sp<RecordTrack> fastTrackToRemove;
5982
Eric Laurent81784c32012-11-19 14:55:58 -08005983 { // scope for mLock
5984 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005985
Eric Laurent021cf962014-05-13 10:18:14 -07005986 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005987
Eric Laurent000a4192014-01-29 15:17:32 -08005988 // check exitPending here because checkForNewParameters_l() and
5989 // checkForNewParameters_l() can temporarily release mLock
5990 if (exitPending()) {
5991 break;
5992 }
5993
Eric Laurent5c25d562016-07-13 17:17:45 -07005994 // sleep with mutex unlocked
5995 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07005996 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07005997 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
5998 ATRACE_END();
5999 sleepUs = 0;
6000 continue;
6001 }
6002
Glenn Kasten2b806402013-11-20 16:37:38 -08006003 // if no active track(s), then standby and release wakelock
6004 size_t size = mActiveTracks.size();
6005 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006006 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006007 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006008 releaseWakeLock_l();
6009 ALOGV("RecordThread: loop stopping");
6010 // go to sleep
6011 mWaitWorkCV.wait(mLock);
6012 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006013 goto reacquire_wakelock;
6014 }
6015
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006016 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006017 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006018 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006019
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006020 activeTrack = mActiveTracks[i];
6021 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006022 if (activeTrack->isFastTrack()) {
6023 ALOG_ASSERT(fastTrackToRemove == 0);
6024 fastTrackToRemove = activeTrack;
6025 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006026 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006027 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006028 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006029 continue;
6030 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006031
6032 TrackBase::track_state activeTrackState = activeTrack->mState;
6033 switch (activeTrackState) {
6034
6035 case TrackBase::PAUSING:
6036 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006037 doBroadcast = true;
6038 size--;
6039 continue;
6040
6041 case TrackBase::STARTING_1:
6042 sleepUs = 10000;
6043 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006044 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006045 continue;
6046
6047 case TrackBase::STARTING_2:
6048 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006049 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006050 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006051 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006052 break;
6053
6054 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006055 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006056 break;
6057
6058 case TrackBase::IDLE:
6059 i++;
6060 continue;
6061
6062 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006063 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006064 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006065
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006066 activeTracks.add(activeTrack);
6067 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006068
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006069 if (activeTrack->isFastTrack()) {
6070 ALOG_ASSERT(!mFastTrackAvail);
6071 ALOG_ASSERT(fastTrack == 0);
6072 fastTrack = activeTrack;
6073 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006074 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006075
Andy Hungdae27702016-10-31 14:01:16 -07006076 mActiveTracks.updatePowerState(this);
6077
Eric Laurent5c25d562016-07-13 17:17:45 -07006078 if (allStopped) {
6079 standbyIfNotAlreadyInStandby();
6080 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006081 if (doBroadcast) {
6082 mStartStopCond.broadcast();
6083 }
6084
6085 // sleep if there are no active tracks to process
6086 if (activeTracks.size() == 0) {
6087 if (sleepUs == 0) {
6088 sleepUs = kRecordThreadSleepUs;
6089 }
6090 continue;
6091 }
6092 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006093
Eric Laurent81784c32012-11-19 14:55:58 -08006094 lockEffectChains_l(effectChains);
6095 }
6096
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006097 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006098
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006099 size_t size = effectChains.size();
6100 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006101 // thread mutex is not locked, but effect chain is locked
6102 effectChains[i]->process_l();
6103 }
6104
Glenn Kasten735f45f2014-08-18 15:51:59 -07006105 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006106 if (mFastCapture != 0) {
6107 FastCaptureStateQueue *sq = mFastCapture->sq();
6108 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006109 bool didModify = false;
6110 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006111 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6112 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6113 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6114 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6115 if (old == -1) {
6116 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6117 }
6118 }
6119 state->mCommand = FastCaptureState::READ_WRITE;
6120#if 0 // FIXME
6121 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006122 FastThreadDumpState::kSamplingNforLowRamDevice :
6123 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006124#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006125 didModify = true;
6126 }
6127 audio_track_cblk_t *cblkOld = state->mCblk;
6128 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6129 if (cblkNew != cblkOld) {
6130 state->mCblk = cblkNew;
6131 // block until acked if removing a fast track
6132 if (cblkOld != NULL) {
6133 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6134 }
6135 didModify = true;
6136 }
6137 sq->end(didModify);
6138 if (didModify) {
6139 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006140#if 0
6141 if (kUseFastCapture == FastCapture_Dynamic) {
6142 mNormalSource = mPipeSource;
6143 }
6144#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006145 }
6146 }
6147
Glenn Kasten735f45f2014-08-18 15:51:59 -07006148 // now run the fast track destructor with thread mutex unlocked
6149 fastTrackToRemove.clear();
6150
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006151 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6152 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6153 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6154 // If destination is non-contiguous, first read past the nominal end of buffer, then
6155 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006156
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006157 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006158 ssize_t framesRead;
6159
6160 // If an NBAIO source is present, use it to read the normal capture's data
6161 if (mPipeSource != 0) {
6162 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006163 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006164 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006165 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006166 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6167 // buffer size or at least for 20ms.
6168 size_t sleepFrames = max(
6169 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6170 if (framesRead <= (ssize_t) sleepFrames) {
6171 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6172 }
6173 if (framesRead < 0) {
6174 status_t status = (status_t) framesRead;
6175 switch (status) {
6176 case OVERRUN:
6177 ALOGW("overrun on read from pipe");
6178 framesRead = 0;
6179 break;
6180 case NEGOTIATE:
6181 ALOGE("re-negotiation is needed");
6182 framesRead = -1; // Will cause an attempt to recover.
6183 break;
6184 default:
6185 ALOGE("unknown error %d on read from pipe", status);
6186 break;
6187 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006188 }
6189 // otherwise use the HAL / AudioStreamIn directly
6190 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006191 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006192 size_t bytesRead;
6193 status_t result = mInput->stream->read(
6194 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006195 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006196 if (result < 0) {
6197 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006198 } else {
6199 framesRead = bytesRead / mFrameSize;
6200 }
6201 }
6202
Andy Hung3f0c9022016-01-15 17:49:46 -08006203 // Update server timestamp with server stats
6204 // systemTime() is optional if the hardware supports timestamps.
6205 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6206 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6207
6208 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006209 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006210 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006211 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006212 if (ret == NO_ERROR) {
6213 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6214 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6215 // Note: In general record buffers should tend to be empty in
6216 // a properly running pipeline.
6217 //
6218 // Also, it is not advantageous to call get_presentation_position during the read
6219 // as the read obtains a lock, preventing the timestamp call from executing.
6220 }
6221 }
6222 // Use this to track timestamp information
6223 // ALOGD("%s", mTimestamp.toString().c_str());
6224
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006225 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006226 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006227 // Force input into standby so that it tries to recover at next read attempt
6228 inputStandBy();
6229 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006230 }
6231 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006232 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006233 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006234 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006235
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006236 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006237 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006238 }
6239 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006240 {
6241 size_t part1 = mRsmpInFramesP2 - rear;
6242 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006243 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006244 (framesRead - part1) * mFrameSize);
6245 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006246 }
6247 rear = mRsmpInRear += framesRead;
6248
6249 size = activeTracks.size();
6250 // loop over each active track
6251 for (size_t i = 0; i < size; i++) {
6252 activeTrack = activeTracks[i];
6253
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006254 // skip fast tracks, as those are handled directly by FastCapture
6255 if (activeTrack->isFastTrack()) {
6256 continue;
6257 }
6258
Andy Hung73c02e42015-03-29 01:13:58 -07006259 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006260 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6261
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006262 enum {
6263 OVERRUN_UNKNOWN,
6264 OVERRUN_TRUE,
6265 OVERRUN_FALSE
6266 } overrun = OVERRUN_UNKNOWN;
6267
6268 // loop over getNextBuffer to handle circular sink
6269 for (;;) {
6270
6271 activeTrack->mSink.frameCount = ~0;
6272 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6273 size_t framesOut = activeTrack->mSink.frameCount;
6274 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6275
Andy Hung73c02e42015-03-29 01:13:58 -07006276 // check available frames and handle overrun conditions
6277 // if the record track isn't draining fast enough.
6278 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006279 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006280 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6281 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006282 overrun = OVERRUN_TRUE;
6283 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006284 if (framesOut == 0 || framesIn == 0) {
6285 break;
6286 }
6287
Andy Hung6770c6f2015-04-07 13:43:36 -07006288 // Don't allow framesOut to be larger than what is possible with resampling
6289 // from framesIn.
6290 // This isn't strictly necessary but helps limit buffer resizing in
6291 // RecordBufferConverter. TODO: remove when no longer needed.
6292 framesOut = min(framesOut,
6293 destinationFramesPossible(
6294 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006295 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6296 framesOut = activeTrack->mRecordBufferConverter->convert(
6297 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006298
6299 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6300 overrun = OVERRUN_FALSE;
6301 }
6302
6303 if (activeTrack->mFramesToDrop == 0) {
6304 if (framesOut > 0) {
6305 activeTrack->mSink.frameCount = framesOut;
6306 activeTrack->releaseBuffer(&activeTrack->mSink);
6307 }
6308 } else {
6309 // FIXME could do a partial drop of framesOut
6310 if (activeTrack->mFramesToDrop > 0) {
6311 activeTrack->mFramesToDrop -= framesOut;
6312 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006313 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006314 }
6315 } else {
6316 activeTrack->mFramesToDrop += framesOut;
6317 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6318 activeTrack->mSyncStartEvent->isCancelled()) {
6319 ALOGW("Synced record %s, session %d, trigger session %d",
6320 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6321 activeTrack->sessionId(),
6322 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006323 activeTrack->mSyncStartEvent->triggerSession() :
6324 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006325 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006326 }
6327 }
6328 }
6329
6330 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006331 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006332 }
6333 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334
6335 switch (overrun) {
6336 case OVERRUN_TRUE:
6337 // client isn't retrieving buffers fast enough
6338 if (!activeTrack->setOverflow()) {
6339 nsecs_t now = systemTime();
6340 // FIXME should lastWarning per track?
6341 if ((now - lastWarning) > kWarningThrottleNs) {
6342 ALOGW("RecordThread: buffer overflow");
6343 lastWarning = now;
6344 }
6345 }
6346 break;
6347 case OVERRUN_FALSE:
6348 activeTrack->clearOverflow();
6349 break;
6350 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006351 break;
6352 }
6353
Andy Hung3f0c9022016-01-15 17:49:46 -08006354 // update frame information and push timestamp out
6355 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006356 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006357 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6358 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006359 }
6360
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006361unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006362 // enable changes in effect chain
6363 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006364 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006365 }
6366
Glenn Kasten93e471f2013-08-19 08:40:07 -07006367 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006368
6369 {
6370 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006371 for (size_t i = 0; i < mTracks.size(); i++) {
6372 sp<RecordTrack> track = mTracks[i];
6373 track->invalidate();
6374 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006375 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006376 mStartStopCond.broadcast();
6377 }
6378
6379 releaseWakeLock();
6380
6381 ALOGV("RecordThread %p exiting", this);
6382 return false;
6383}
6384
Glenn Kasten93e471f2013-08-19 08:40:07 -07006385void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006386{
6387 if (!mStandby) {
6388 inputStandBy();
6389 mStandby = true;
6390 }
6391}
6392
6393void AudioFlinger::RecordThread::inputStandBy()
6394{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006395 // Idle the fast capture if it's currently running
6396 if (mFastCapture != 0) {
6397 FastCaptureStateQueue *sq = mFastCapture->sq();
6398 FastCaptureState *state = sq->begin();
6399 if (!(state->mCommand & FastCaptureState::IDLE)) {
6400 state->mCommand = FastCaptureState::COLD_IDLE;
6401 state->mColdFutexAddr = &mFastCaptureFutex;
6402 state->mColdGen++;
6403 mFastCaptureFutex = 0;
6404 sq->end();
6405 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6406 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6407#if 0
6408 if (kUseFastCapture == FastCapture_Dynamic) {
6409 // FIXME
6410 }
6411#endif
6412#ifdef AUDIO_WATCHDOG
6413 // FIXME
6414#endif
6415 } else {
6416 sq->end(false /*didModify*/);
6417 }
6418 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006419 status_t result = mInput->stream->standby();
6420 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006421
6422 // If going into standby, flush the pipe source.
6423 if (mPipeSource.get() != nullptr) {
6424 const ssize_t flushed = mPipeSource->flush();
6425 if (flushed > 0) {
6426 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6427 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6428 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6429 }
6430 }
Eric Laurent81784c32012-11-19 14:55:58 -08006431}
6432
Glenn Kasten05997e22014-03-13 15:08:33 -07006433// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006434sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006435 const sp<AudioFlinger::Client>& client,
6436 uint32_t sampleRate,
6437 audio_format_t format,
6438 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006439 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006440 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006441 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006442 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006443 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006444 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006445 status_t *status,
6446 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006447{
Glenn Kasten74935e42013-12-19 08:56:45 -08006448 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006449 sp<RecordTrack> track;
6450 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006451 audio_input_flags_t inputFlags = mInput->flags;
6452
6453 // special case for FAST flag considered OK if fast capture is present
6454 if (hasFastCapture()) {
6455 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6456 }
6457
6458 // Check if requested flags are compatible with output stream flags
6459 if ((*flags & inputFlags) != *flags) {
6460 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6461 " input flags (%08x)",
6462 *flags, inputFlags);
6463 *flags = (audio_input_flags_t)(*flags & inputFlags);
6464 }
Eric Laurent81784c32012-11-19 14:55:58 -08006465
Glenn Kasten90e58b12013-07-31 16:16:02 -07006466 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006467 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006468 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006469 // we formerly checked for a callback handler (non-0 tid),
6470 // but that is no longer required for TRANSFER_OBTAIN mode
6471 //
Glenn Kasten74105912014-07-03 12:28:53 -07006472 // frame count is not specified, or is exactly the pipe depth
6473 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006474 // PCM data
6475 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006476 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006477 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006478 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006479 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006480 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006481 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006482 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006483 hasFastCapture() &&
6484 // there are sufficient fast track slots available
6485 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006486 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006487 // check compatibility with audio effects.
6488 Mutex::Autolock _l(mLock);
6489 // Do not accept FAST flag if the session has software effects
6490 sp<EffectChain> chain = getEffectChain_l(sessionId);
6491 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006492 audio_input_flags_t old = *flags;
6493 chain->checkInputFlagCompatibility(flags);
6494 if (old != *flags) {
6495 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6496 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006497 }
6498 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006499 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006500 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6501 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006502 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006503 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006504 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006505 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006506 frameCount, mFrameCount, mPipeFramesP2,
6507 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6508 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006509 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006510 }
6511 }
6512
6513 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006514 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006515 // fast track: frame count is exactly the pipe depth
6516 frameCount = mPipeFramesP2;
6517 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6518 *notificationFrames = mFrameCount;
6519 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006520 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6521 // or 20 ms if there is a fast capture
6522 // TODO This could be a roundupRatio inline, and const
6523 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6524 * sampleRate + mSampleRate - 1) / mSampleRate;
6525 // minimum number of notification periods is at least kMinNotifications,
6526 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6527 static const size_t kMinNotifications = 3;
6528 static const uint32_t kMinMs = 30;
6529 // TODO This could be a roundupRatio inline
6530 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6531 // TODO This could be a roundupRatio inline
6532 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6533 maxNotificationFrames;
6534 const size_t minFrameCount = maxNotificationFrames *
6535 max(kMinNotifications, minNotificationsByMs);
6536 frameCount = max(frameCount, minFrameCount);
6537 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6538 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006539 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006540 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006541 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006542
Glenn Kasten15e57982013-09-24 11:52:37 -07006543 lStatus = initCheck();
6544 if (lStatus != NO_ERROR) {
6545 ALOGE("createRecordTrack_l() audio driver not initialized");
6546 goto Exit;
6547 }
Eric Laurent81784c32012-11-19 14:55:58 -08006548
6549 { // scope for mLock
6550 Mutex::Autolock _l(mLock);
6551
6552 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006553 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006554 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006555
Glenn Kasten03003332013-08-06 15:40:54 -07006556 lStatus = track->initCheck();
6557 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006558 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006559 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006560 goto Exit;
6561 }
6562 mTracks.add(track);
6563
6564 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6565 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6566 mAudioFlinger->btNrecIsOff();
6567 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6568 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006569
Eric Laurent05067782016-06-01 18:27:28 -07006570 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006571 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6572 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6573 // so ask activity manager to do this on our behalf
6574 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6575 }
Eric Laurent81784c32012-11-19 14:55:58 -08006576 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006577
Eric Laurent81784c32012-11-19 14:55:58 -08006578 lStatus = NO_ERROR;
6579
6580Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006581 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006582 return track;
6583}
6584
6585status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6586 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006587 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006588{
6589 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6590 sp<ThreadBase> strongMe = this;
6591 status_t status = NO_ERROR;
6592
6593 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006594 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006595 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006596 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006597 triggerSession,
6598 recordTrack->sessionId(),
6599 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006600 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006601 // Sync event can be cancelled by the trigger session if the track is not in a
6602 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006603 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006604 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006605 } else {
6606 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006607 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006608 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006609 }
6610 }
6611
6612 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006613 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006614 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006615 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6616 if (recordTrack->mState == TrackBase::PAUSING) {
6617 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006618 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006619 } else {
6620 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006621 }
6622 return status;
6623 }
6624
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006625 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6626 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6627 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006628 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006629 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006630 status_t status = NO_ERROR;
6631 if (recordTrack->isExternalTrack()) {
6632 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006633 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006634 mLock.lock();
6635 // FIXME should verify that recordTrack is still in mActiveTracks
6636 if (status != NO_ERROR) {
6637 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006638 recordTrack->clearSyncStartEvent();
6639 ALOGV("RecordThread::start error %d", status);
6640 return status;
6641 }
Eric Laurent81784c32012-11-19 14:55:58 -08006642 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006643 // Catch up with current buffer indices if thread is already running.
6644 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6645 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6646 // see previously buffered data before it called start(), but with greater risk of overrun.
6647
Andy Hung73c02e42015-03-29 01:13:58 -07006648 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006649 // clear any converter state as new data will be discontinuous
6650 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006651 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006652 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006653 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006654 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006655 ALOGV("Record failed to start");
6656 status = BAD_VALUE;
6657 goto startError;
6658 }
Eric Laurent81784c32012-11-19 14:55:58 -08006659 return status;
6660 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006661
Eric Laurent81784c32012-11-19 14:55:58 -08006662startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006663 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006664 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006665 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006666 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006667 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006668 return status;
6669}
6670
Eric Laurent81784c32012-11-19 14:55:58 -08006671void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6672{
6673 sp<SyncEvent> strongEvent = event.promote();
6674
6675 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006676 sp<RefBase> ptr = strongEvent->cookie().promote();
6677 if (ptr != 0) {
6678 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6679 recordTrack->handleSyncStartEvent(strongEvent);
6680 }
Eric Laurent81784c32012-11-19 14:55:58 -08006681 }
6682}
6683
Glenn Kastena8356f62013-07-25 14:37:52 -07006684bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006685 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006686 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006687 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006688 return false;
6689 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006690 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006691 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006692 // signal thread to stop
6693 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006694 // do not wait for mStartStopCond if exiting
6695 if (exitPending()) {
6696 return true;
6697 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006698 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006699 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006700 // if we have been restarted, recordTrack is in mActiveTracks here
6701 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006702 ALOGV("Record stopped OK");
6703 return true;
6704 }
6705 return false;
6706}
6707
Glenn Kasten0f11b512014-01-31 16:18:54 -08006708bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006709{
6710 return false;
6711}
6712
Glenn Kasten0f11b512014-01-31 16:18:54 -08006713status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006714{
6715#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6716 if (!isValidSyncEvent(event)) {
6717 return BAD_VALUE;
6718 }
6719
Glenn Kastend848eb42016-03-08 13:42:11 -08006720 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006721 status_t ret = NAME_NOT_FOUND;
6722
6723 Mutex::Autolock _l(mLock);
6724
6725 for (size_t i = 0; i < mTracks.size(); i++) {
6726 sp<RecordTrack> track = mTracks[i];
6727 if (eventSession == track->sessionId()) {
6728 (void) track->setSyncEvent(event);
6729 ret = NO_ERROR;
6730 }
6731 }
6732 return ret;
6733#else
6734 return BAD_VALUE;
6735#endif
6736}
6737
6738// destroyTrack_l() must be called with ThreadBase::mLock held
6739void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6740{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006741 track->terminate();
6742 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006743 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006744 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006745 removeTrack_l(track);
6746 }
6747}
6748
6749void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6750{
6751 mTracks.remove(track);
6752 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006753 if (track->isFastTrack()) {
6754 ALOG_ASSERT(!mFastTrackAvail);
6755 mFastTrackAvail = true;
6756 }
Eric Laurent81784c32012-11-19 14:55:58 -08006757}
6758
6759void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6760{
6761 dumpInternals(fd, args);
6762 dumpTracks(fd, args);
6763 dumpEffectChains(fd, args);
6764}
6765
6766void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6767{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006768 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006769
Glenn Kasten44182c22015-03-05 17:12:23 -08006770 dumpBase(fd, args);
6771
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006772 AudioStreamIn *input = mInput;
6773 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6774 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6775 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006776 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006777 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006778 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006779 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006780 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006781
Glenn Kasten2f90c512015-12-02 11:40:09 -08006782 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6783 // while we are dumping it. It may be inconsistent, but it won't mutate!
6784 // This is a large object so we place it on the heap.
6785 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6786 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6787 copy->dump(fd);
6788 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006789}
6790
Glenn Kasten0f11b512014-01-31 16:18:54 -08006791void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006792{
6793 const size_t SIZE = 256;
6794 char buffer[SIZE];
6795 String8 result;
6796
Marco Nelissenb2208842014-02-07 14:00:50 -08006797 size_t numtracks = mTracks.size();
6798 size_t numactive = mActiveTracks.size();
6799 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006800 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006801 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006802 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006803 RecordTrack::appendDumpHeader(result);
6804 for (size_t i = 0; i < numtracks ; ++i) {
6805 sp<RecordTrack> track = mTracks[i];
6806 if (track != 0) {
6807 bool active = mActiveTracks.indexOf(track) >= 0;
6808 if (active) {
6809 numactiveseen++;
6810 }
6811 track->dump(buffer, SIZE, active);
6812 result.append(buffer);
6813 }
Eric Laurent81784c32012-11-19 14:55:58 -08006814 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006815 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006816 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006817 }
6818
Marco Nelissenb2208842014-02-07 14:00:50 -08006819 if (numactiveseen != numactive) {
6820 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6821 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006822 result.append(buffer);
6823 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006824 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006825 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006826 if (mTracks.indexOf(track) < 0) {
6827 track->dump(buffer, SIZE, true);
6828 result.append(buffer);
6829 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006830 }
Eric Laurent81784c32012-11-19 14:55:58 -08006831
6832 }
6833 write(fd, result.string(), result.size());
6834}
6835
Andy Hung73c02e42015-03-29 01:13:58 -07006836
6837void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6838{
6839 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6840 RecordThread *recordThread = (RecordThread *) threadBase.get();
6841 mRsmpInFront = recordThread->mRsmpInRear;
6842 mRsmpInUnrel = 0;
6843}
6844
6845void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6846 size_t *framesAvailable, bool *hasOverrun)
6847{
6848 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6849 RecordThread *recordThread = (RecordThread *) threadBase.get();
6850 const int32_t rear = recordThread->mRsmpInRear;
6851 const int32_t front = mRsmpInFront;
6852 const ssize_t filled = rear - front;
6853
6854 size_t framesIn;
6855 bool overrun = false;
6856 if (filled < 0) {
6857 // should not happen, but treat like a massive overrun and re-sync
6858 framesIn = 0;
6859 mRsmpInFront = rear;
6860 overrun = true;
6861 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6862 framesIn = (size_t) filled;
6863 } else {
6864 // client is not keeping up with server, but give it latest data
6865 framesIn = recordThread->mRsmpInFrames;
6866 mRsmpInFront = /* front = */ rear - framesIn;
6867 overrun = true;
6868 }
6869 if (framesAvailable != NULL) {
6870 *framesAvailable = framesIn;
6871 }
6872 if (hasOverrun != NULL) {
6873 *hasOverrun = overrun;
6874 }
6875}
6876
Eric Laurent81784c32012-11-19 14:55:58 -08006877// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006878status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006879 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006880{
Andy Hung73c02e42015-03-29 01:13:58 -07006881 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006882 if (threadBase == 0) {
6883 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006884 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006885 return NOT_ENOUGH_DATA;
6886 }
6887 RecordThread *recordThread = (RecordThread *) threadBase.get();
6888 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006889 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006890 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006891 // FIXME should not be P2 (don't want to increase latency)
6892 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006893 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006894 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006895 front &= recordThread->mRsmpInFramesP2 - 1;
6896 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006897 if (part1 > (size_t) filled) {
6898 part1 = filled;
6899 }
6900 size_t ask = buffer->frameCount;
6901 ALOG_ASSERT(ask > 0);
6902 if (part1 > ask) {
6903 part1 = ask;
6904 }
6905 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006906 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006907 buffer->raw = NULL;
6908 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006909 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006910 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006911 }
6912
Andy Hung57446612015-04-19 23:56:46 -07006913 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006914 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006915 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006916 return NO_ERROR;
6917}
6918
6919// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006920void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6921 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006922{
Glenn Kasten85948432013-08-19 12:09:05 -07006923 size_t stepCount = buffer->frameCount;
6924 if (stepCount == 0) {
6925 return;
6926 }
Andy Hung73c02e42015-03-29 01:13:58 -07006927 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6928 mRsmpInUnrel -= stepCount;
6929 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006930 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006931 buffer->frameCount = 0;
6932}
6933
Andy Hung97a893e2015-03-29 01:03:07 -07006934AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6935 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6936 uint32_t srcSampleRate,
6937 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6938 uint32_t dstSampleRate) :
6939 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6940 // mSrcFormat
6941 // mSrcSampleRate
6942 // mDstChannelMask
6943 // mDstFormat
6944 // mDstSampleRate
6945 // mSrcChannelCount
6946 // mDstChannelCount
6947 // mDstFrameSize
6948 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006949 mResampler(NULL),
6950 mIsLegacyDownmix(false),
6951 mIsLegacyUpmix(false),
6952 mRequiresFloat(false),
6953 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006954{
6955 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6956 dstChannelMask, dstFormat, dstSampleRate);
6957}
6958
6959AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6960 free(mBuf);
6961 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006962 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006963}
6964
6965size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6966 AudioBufferProvider *provider, size_t frames)
6967{
Andy Hungd330ee42015-04-20 13:23:41 -07006968 if (mInputConverterProvider != NULL) {
6969 mInputConverterProvider->setBufferProvider(provider);
6970 provider = mInputConverterProvider;
6971 }
6972
6973 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006974 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6975 mSrcSampleRate, mSrcFormat, mDstFormat);
6976
6977 AudioBufferProvider::Buffer buffer;
6978 for (size_t i = frames; i > 0; ) {
6979 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006980 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006981 if (status != OK || buffer.frameCount == 0) {
6982 frames -= i; // cannot fill request.
6983 break;
6984 }
Andy Hungd330ee42015-04-20 13:23:41 -07006985 // format convert to destination buffer
6986 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006987
6988 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6989 i -= buffer.frameCount;
6990 provider->releaseBuffer(&buffer);
6991 }
6992 } else {
6993 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6994 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6995
Andy Hungd330ee42015-04-20 13:23:41 -07006996 // reallocate buffer if needed
6997 if (mBufFrameSize != 0 && mBufFrames < frames) {
6998 free(mBuf);
6999 mBufFrames = frames;
7000 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7001 }
Andy Hung97a893e2015-03-29 01:03:07 -07007002 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007003 memset(mBuf, 0, frames * mBufFrameSize);
7004 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7005 // format convert to destination buffer
7006 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007007 }
7008 return frames;
7009}
7010
7011status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7012 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7013 uint32_t srcSampleRate,
7014 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7015 uint32_t dstSampleRate)
7016{
7017 // quick evaluation if there is any change.
7018 if (mSrcFormat == srcFormat
7019 && mSrcChannelMask == srcChannelMask
7020 && mSrcSampleRate == srcSampleRate
7021 && mDstFormat == dstFormat
7022 && mDstChannelMask == dstChannelMask
7023 && mDstSampleRate == dstSampleRate) {
7024 return NO_ERROR;
7025 }
7026
Andy Hungdb4c0312015-05-06 08:46:52 -07007027 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7028 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7029 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007030 const bool valid =
7031 audio_is_input_channel(srcChannelMask)
7032 && audio_is_input_channel(dstChannelMask)
7033 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7034 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7035 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7036 ; // no upsampling checks for now
7037 if (!valid) {
7038 return BAD_VALUE;
7039 }
7040
7041 mSrcFormat = srcFormat;
7042 mSrcChannelMask = srcChannelMask;
7043 mSrcSampleRate = srcSampleRate;
7044 mDstFormat = dstFormat;
7045 mDstChannelMask = dstChannelMask;
7046 mDstSampleRate = dstSampleRate;
7047
7048 // compute derived parameters
7049 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7050 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7051 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7052
Andy Hungd330ee42015-04-20 13:23:41 -07007053 // do we need to resample?
7054 delete mResampler;
7055 mResampler = NULL;
7056 if (mSrcSampleRate != mDstSampleRate) {
7057 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7058 mSrcChannelCount, mDstSampleRate);
7059 mResampler->setSampleRate(mSrcSampleRate);
7060 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7061 }
7062
7063 // are we running legacy channel conversion modes?
7064 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7065 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7066 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7067 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7068 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7069 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7070
7071 // do we need to process in float?
7072 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7073
7074 // do we need a staging buffer to convert for destination (we can still optimize this)?
7075 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7076 if (mResampler != NULL) {
7077 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7078 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007079 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007080 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7081 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007082 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7083 } else {
7084 mBufFrameSize = 0;
7085 }
7086 mBufFrames = 0; // force the buffer to be resized.
7087
Andy Hungd330ee42015-04-20 13:23:41 -07007088 // do we need an input converter buffer provider to give us float?
7089 delete mInputConverterProvider;
7090 mInputConverterProvider = NULL;
7091 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7092 mInputConverterProvider = new ReformatBufferProvider(
7093 audio_channel_count_from_in_mask(mSrcChannelMask),
7094 mSrcFormat,
7095 AUDIO_FORMAT_PCM_FLOAT,
7096 256 /* provider buffer frame count */);
7097 }
7098
7099 // do we need a remixer to do channel mask conversion
7100 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7101 (void) memcpy_by_index_array_initialization_from_channel_mask(
7102 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007103 }
7104 return NO_ERROR;
7105}
7106
Andy Hungd330ee42015-04-20 13:23:41 -07007107void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7108 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007109{
Andy Hungd330ee42015-04-20 13:23:41 -07007110 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007111 if (mBufFrameSize != 0 && mBufFrames < frames) {
7112 free(mBuf);
7113 mBufFrames = frames;
7114 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7115 }
Andy Hungd330ee42015-04-20 13:23:41 -07007116 // do we need to do legacy upmix and downmix?
7117 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007118 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007119 if (mIsLegacyUpmix) {
7120 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7121 (const float *)src, frames);
7122 } else /*mIsLegacyDownmix */ {
7123 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7124 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007125 }
Andy Hungd330ee42015-04-20 13:23:41 -07007126 if (mBuf != NULL) {
7127 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7128 frames * mDstChannelCount);
7129 }
7130 return;
7131 }
7132 // do we need to do channel mask conversion?
7133 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007134 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007135 memcpy_by_index_array(dstBuf, mDstChannelCount,
7136 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7137 if (dstBuf == dst) {
7138 return; // format is the same
7139 }
7140 }
7141 // convert to destination buffer
7142 const void *convertBuf = mBuf != NULL ? mBuf : src;
7143 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7144 frames * mDstChannelCount);
7145}
7146
7147void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7148 void *dst, /*not-a-const*/ void *src, size_t frames)
7149{
7150 // src buffer format is ALWAYS float when entering this routine
7151 if (mIsLegacyUpmix) {
7152 ; // mono to stereo already handled by resampler
7153 } else if (mIsLegacyDownmix
7154 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7155 // the resampler outputs stereo for mono input channel (a feature?)
7156 // must convert to mono
7157 downmix_to_mono_float_from_stereo_float((float *)src,
7158 (const float *)src, frames);
7159 } else if (mSrcChannelMask != mDstChannelMask) {
7160 // convert to mono channel again for channel mask conversion (could be skipped
7161 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007162 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007163 downmix_to_mono_float_from_stereo_float((float *)src,
7164 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007165 }
Andy Hungd330ee42015-04-20 13:23:41 -07007166 // convert to destination format (in place, OK as float is larger than other types)
7167 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7168 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7169 frames * mSrcChannelCount);
7170 }
7171 // channel convert and save to dst
7172 memcpy_by_index_array(dst, mDstChannelCount,
7173 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7174 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007175 }
Andy Hungd330ee42015-04-20 13:23:41 -07007176 // convert to destination format and save to dst
7177 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7178 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007179}
7180
Eric Laurent10351942014-05-08 18:49:52 -07007181bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7182 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007183{
7184 bool reconfig = false;
7185
Eric Laurent10351942014-05-08 18:49:52 -07007186 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007187
Eric Laurent10351942014-05-08 18:49:52 -07007188 audio_format_t reqFormat = mFormat;
7189 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007190 // 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 -07007191 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7192
7193 AudioParameter param = AudioParameter(keyValuePair);
7194 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007195
7196 // scope for AutoPark extends to end of method
7197 AutoPark<FastCapture> park(mFastCapture);
7198
Eric Laurent10351942014-05-08 18:49:52 -07007199 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7200 // channel count change can be requested. Do we mandate the first client defines the
7201 // HAL sampling rate and channel count or do we allow changes on the fly?
7202 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7203 samplingRate = value;
7204 reconfig = true;
7205 }
7206 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007207 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007208 status = BAD_VALUE;
7209 } else {
7210 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007211 reconfig = true;
7212 }
Eric Laurent10351942014-05-08 18:49:52 -07007213 }
7214 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7215 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007216 if (!audio_is_input_channel(mask) ||
7217 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007218 status = BAD_VALUE;
7219 } else {
7220 channelMask = mask;
7221 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007222 }
Eric Laurent10351942014-05-08 18:49:52 -07007223 }
7224 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7225 // do not accept frame count changes if tracks are open as the track buffer
7226 // size depends on frame count and correct behavior would not be guaranteed
7227 // if frame count is changed after track creation
7228 if (mActiveTracks.size() > 0) {
7229 status = INVALID_OPERATION;
7230 } else {
7231 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007232 }
Eric Laurent10351942014-05-08 18:49:52 -07007233 }
7234 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7235 // forward device change to effects that have requested to be
7236 // aware of attached audio device.
7237 for (size_t i = 0; i < mEffectChains.size(); i++) {
7238 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007239 }
Eric Laurent81784c32012-11-19 14:55:58 -08007240
Eric Laurent10351942014-05-08 18:49:52 -07007241 // store input device and output device but do not forward output device to audio HAL.
7242 // Note that status is ignored by the caller for output device
7243 // (see AudioFlinger::setParameters()
7244 if (audio_is_output_devices(value)) {
7245 mOutDevice = value;
7246 status = BAD_VALUE;
7247 } else {
7248 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007249 if (value != AUDIO_DEVICE_NONE) {
7250 mPrevInDevice = value;
7251 }
Eric Laurent10351942014-05-08 18:49:52 -07007252 // disable AEC and NS if the device is a BT SCO headset supporting those
7253 // pre processings
7254 if (mTracks.size() > 0) {
7255 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7256 mAudioFlinger->btNrecIsOff();
7257 for (size_t i = 0; i < mTracks.size(); i++) {
7258 sp<RecordTrack> track = mTracks[i];
7259 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7260 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007261 }
7262 }
7263 }
Eric Laurent10351942014-05-08 18:49:52 -07007264 }
7265 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7266 mAudioSource != (audio_source_t)value) {
7267 // forward device change to effects that have requested to be
7268 // aware of attached audio device.
7269 for (size_t i = 0; i < mEffectChains.size(); i++) {
7270 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007271 }
Eric Laurent10351942014-05-08 18:49:52 -07007272 mAudioSource = (audio_source_t)value;
7273 }
Glenn Kastene198c362013-08-13 09:13:36 -07007274
Eric Laurent10351942014-05-08 18:49:52 -07007275 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007276 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007277 if (status == INVALID_OPERATION) {
7278 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007279 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007280 }
7281 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007282 if (status == BAD_VALUE) {
7283 uint32_t sRate;
7284 audio_channel_mask_t channelMask;
7285 audio_format_t format;
7286 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7287 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7288 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7289 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7290 status = NO_ERROR;
7291 }
Eric Laurent81784c32012-11-19 14:55:58 -08007292 }
Eric Laurent10351942014-05-08 18:49:52 -07007293 if (status == NO_ERROR) {
7294 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007295 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007296 }
7297 }
Eric Laurent81784c32012-11-19 14:55:58 -08007298 }
Eric Laurent10351942014-05-08 18:49:52 -07007299
Eric Laurent81784c32012-11-19 14:55:58 -08007300 return reconfig;
7301}
7302
7303String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7304{
Eric Laurent81784c32012-11-19 14:55:58 -08007305 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007306 if (initCheck() == NO_ERROR) {
7307 String8 out_s8;
7308 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7309 return out_s8;
7310 }
Eric Laurent81784c32012-11-19 14:55:58 -08007311 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007312 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007313}
7314
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007315void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007316 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7317
7318 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007319
7320 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007321 case AUDIO_INPUT_OPENED:
7322 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007323 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007324 desc->mChannelMask = mChannelMask;
7325 desc->mSamplingRate = mSampleRate;
7326 desc->mFormat = mFormat;
7327 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007328 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007329 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007330 break;
7331
Eric Laurent73e26b62015-04-27 16:55:58 -07007332 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007333 default:
7334 break;
7335 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007336 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007337}
7338
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007339void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007340{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007341 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7342 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007343 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007344 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007345 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007346 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7347 result = mInput->stream->getFrameSize(&mFrameSize);
7348 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7349 result = mInput->stream->getBufferSize(&mBufferSize);
7350 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007351 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007352 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007353 // 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 -07007354 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007355 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007356 // A larger value should allow more old data to be read after a track calls start(),
7357 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007358 //
7359 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007360 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007361 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007362 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007363 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007364
7365 // TODO optimize audio capture buffer sizes ...
7366 // Here we calculate the size of the sliding buffer used as a source
7367 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7368 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7369 // be better to have it derived from the pipe depth in the long term.
7370 // The current value is higher than necessary. However it should not add to latency.
7371
Glenn Kasten85948432013-08-19 12:09:05 -07007372 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007373 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7374 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7375 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007376
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007377 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7378 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007379}
7380
Glenn Kasten5f972c02014-01-13 09:59:31 -08007381uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007382{
7383 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007384 uint32_t result;
7385 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7386 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007387 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007388 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007389}
7390
Eric Laurent4c415062016-06-17 16:14:16 -07007391// hasAudioSession_l() must be called with ThreadBase::mLock held
7392uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007393{
Eric Laurent81784c32012-11-19 14:55:58 -08007394 uint32_t result = 0;
7395 if (getEffectChain_l(sessionId) != 0) {
7396 result = EFFECT_SESSION;
7397 }
7398
7399 for (size_t i = 0; i < mTracks.size(); ++i) {
7400 if (sessionId == mTracks[i]->sessionId()) {
7401 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007402 if (mTracks[i]->isFastTrack()) {
7403 result |= FAST_SESSION;
7404 }
Eric Laurent81784c32012-11-19 14:55:58 -08007405 break;
7406 }
7407 }
7408
7409 return result;
7410}
7411
Glenn Kastend848eb42016-03-08 13:42:11 -08007412KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007413{
Glenn Kastend848eb42016-03-08 13:42:11 -08007414 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007415 Mutex::Autolock _l(mLock);
7416 for (size_t j = 0; j < mTracks.size(); ++j) {
7417 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007418 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007419 if (ids.indexOfKey(sessionId) < 0) {
7420 ids.add(sessionId, true);
7421 }
7422 }
7423 return ids;
7424}
7425
7426AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7427{
7428 Mutex::Autolock _l(mLock);
7429 AudioStreamIn *input = mInput;
7430 mInput = NULL;
7431 return input;
7432}
7433
7434// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007435sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007436{
7437 if (mInput == NULL) {
7438 return NULL;
7439 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007440 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007441}
7442
7443status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7444{
7445 // only one chain per input thread
7446 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007447 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007448 return INVALID_OPERATION;
7449 }
7450 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007451 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007452 chain->setInBuffer(NULL);
7453 chain->setOutBuffer(NULL);
7454
7455 checkSuspendOnAddEffectChain_l(chain);
7456
Eric Laurent1b928682014-10-02 19:41:47 -07007457 // make sure enabled pre processing effects state is communicated to the HAL as we
7458 // just moved them to a new input stream.
7459 chain->syncHalEffectsState();
7460
Eric Laurent81784c32012-11-19 14:55:58 -08007461 mEffectChains.add(chain);
7462
7463 return NO_ERROR;
7464}
7465
7466size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7467{
7468 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7469 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007470 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007471 chain.get(), mEffectChains.size(), this);
7472 if (mEffectChains.size() == 1) {
7473 mEffectChains.removeAt(0);
7474 }
7475 return 0;
7476}
7477
Eric Laurent1c333e22014-05-20 10:48:17 -07007478status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7479 audio_patch_handle_t *handle)
7480{
7481 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007482
7483 // store new device and send to effects
7484 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007485 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007486 for (size_t i = 0; i < mEffectChains.size(); i++) {
7487 mEffectChains[i]->setDevice_l(mInDevice);
7488 }
7489
7490 // disable AEC and NS if the device is a BT SCO headset supporting those
7491 // pre processings
7492 if (mTracks.size() > 0) {
7493 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7494 mAudioFlinger->btNrecIsOff();
7495 for (size_t i = 0; i < mTracks.size(); i++) {
7496 sp<RecordTrack> track = mTracks[i];
7497 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7498 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7499 }
7500 }
7501
7502 // store new source and send to effects
7503 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7504 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007505 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007506 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007507 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007508 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007509
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007510 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007511 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7512 status = hwDevice->createAudioPatch(patch->num_sources,
7513 patch->sources,
7514 patch->num_sinks,
7515 patch->sinks,
7516 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007517 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007518 char *address;
7519 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7520 address = audio_device_address_to_parameter(
7521 patch->sources[0].ext.device.type,
7522 patch->sources[0].ext.device.address);
7523 } else {
7524 address = (char *)calloc(1, 1);
7525 }
7526 AudioParameter param = AudioParameter(String8(address));
7527 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007528 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007529 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007530 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007531 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007532 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007533 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007534 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007535
Eric Laurente8726fe2015-06-26 09:39:24 -07007536 if (mInDevice != mPrevInDevice) {
7537 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7538 mPrevInDevice = mInDevice;
7539 }
Eric Laurent296fb132015-05-01 11:38:42 -07007540
Eric Laurent1c333e22014-05-20 10:48:17 -07007541 return status;
7542}
7543
7544status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7545{
7546 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007547
7548 mInDevice = AUDIO_DEVICE_NONE;
7549
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007550 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007551 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7552 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007553 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007554 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007555 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007556 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007557 }
7558 return status;
7559}
7560
Eric Laurent83b88082014-06-20 18:31:16 -07007561void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7562{
7563 Mutex::Autolock _l(mLock);
7564 mTracks.add(record);
7565}
7566
7567void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7568{
7569 Mutex::Autolock _l(mLock);
7570 destroyTrack_l(record);
7571}
7572
7573void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7574{
7575 ThreadBase::getAudioPortConfig(config);
7576 config->role = AUDIO_PORT_ROLE_SINK;
7577 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7578 config->ext.mix.usecase.source = mAudioSource;
7579}
Eric Laurent1c333e22014-05-20 10:48:17 -07007580
Glenn Kasten63238ef2015-03-02 15:50:29 -08007581} // namespace android