blob: d45cf21cd090f22d4426850e86afd0c7a12a7611 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070032#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080034#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080035
36#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070037#include <private/android_filesystem_config.h>
Andy Hung2ddee192015-12-18 17:34:44 -080038#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080039#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070042#include <system/audio_effects/effect_ns.h>
43#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045
46// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070047#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080048#include <media/nbaio/AudioStreamOutSink.h>
49#include <media/nbaio/MonoPipe.h>
50#include <media/nbaio/MonoPipeReader.h>
51#include <media/nbaio/Pipe.h>
52#include <media/nbaio/PipeReader.h>
53#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080054#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080055
56#include <powermanager/PowerManager.h>
57
Eric Laurent81784c32012-11-19 14:55:58 -080058#include "AudioFlinger.h"
59#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070060#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070064#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080065
Eric Laurent81784c32012-11-19 14:55:58 -080066#ifdef ADD_BATTERY_DATA
67#include <media/IMediaPlayerService.h>
68#include <media/IMediaDeathNotifier.h>
69#endif
70
Eric Laurent81784c32012-11-19 14:55:58 -080071#ifdef DEBUG_CPU_USAGE
72#include <cpustats/CentralTendencyStatistics.h>
73#include <cpustats/ThreadCpuUsage.h>
74#endif
75
Glenn Kastenc05b8d72016-03-24 09:48:17 -070076#include "AutoPark.h"
77
Eric Laurent81784c32012-11-19 14:55:58 -080078// ----------------------------------------------------------------------------
79
80// Note: the following macro is used for extremely verbose logging message. In
81// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
82// 0; but one side effect of this is to turn all LOGV's as well. Some messages
83// are so verbose that we want to suppress them even when we have ALOG_ASSERT
84// turned on. Do not uncomment the #def below unless you really know what you
85// are doing and want to see all of the extremely verbose messages.
86//#define VERY_VERY_VERBOSE_LOGGING
87#ifdef VERY_VERY_VERBOSE_LOGGING
88#define ALOGVV ALOGV
89#else
90#define ALOGVV(a...) do { } while(0)
91#endif
92
Andy Hung6770c6f2015-04-07 13:43:36 -070093// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070094#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070095template <typename T>
96static inline T min(const T& a, const T& b)
97{
98 return a < b ? a : b;
99}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700100
Andy Hungd330ee42015-04-20 13:23:41 -0700101#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700102#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700103#endif
104
Eric Laurent81784c32012-11-19 14:55:58 -0800105namespace android {
106
107// retry counts for buffer fill timeout
108// 50 * ~20msecs = 1 second
109static const int8_t kMaxTrackRetries = 50;
110static const int8_t kMaxTrackStartupRetries = 50;
111// allow less retry attempts on direct output thread.
112// direct outputs can be a scarce resource in audio hardware and should
113// be released as quickly as possible.
114static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700115
Eric Laurent51716182016-02-29 18:00:56 -0800116
Eric Laurent81784c32012-11-19 14:55:58 -0800117
118// don't warn about blocked writes or record buffer overflows more often than this
119static const nsecs_t kWarningThrottleNs = seconds(5);
120
121// RecordThread loop sleep time upon application overrun or audio HAL read error
122static const int kRecordThreadSleepUs = 5000;
123
Eric Laurent10351942014-05-08 18:49:52 -0700124// maximum time to wait in sendConfigEvent_l() for a status to be received
125static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800126
127// minimum sleep time for the mixer thread loop when tracks are active but in underrun
128static const uint32_t kMinThreadSleepTimeUs = 5000;
129// maximum divider applied to the active sleep time in the mixer thread loop
130static const uint32_t kMaxThreadSleepTimeShift = 2;
131
Andy Hung09a50072014-02-27 14:30:47 -0800132// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700133// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800134static const uint32_t kMinNormalSinkBufferSizeMs = 20;
135// maximum normal sink buffer size
136static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800137
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700138// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
139// FIXME This should be based on experimentally observed scheduling jitter
140static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
141
Eric Laurent972a1732013-09-04 09:42:59 -0700142// Offloaded output thread standby delay: allows track transition without going to standby
143static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
144
Eric Laurent51716182016-02-29 18:00:56 -0800145// Direct output thread minimum sleep time in idle or active(underrun) state
146static const nsecs_t kDirectMinSleepTimeUs = 10000;
147
Glenn Kasten1b291842016-07-18 14:55:21 -0700148// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
149// balance between power consumption and latency, and allows threads to be scheduled reliably
150// by the CFS scheduler.
151// FIXME Express other hardcoded references to 20ms with references to this constant and move
152// it appropriately.
153#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800154
Eric Laurent81784c32012-11-19 14:55:58 -0800155// Whether to use fast mixer
156static const enum {
157 FastMixer_Never, // never initialize or use: for debugging only
158 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
159 // normal mixer multiplier is 1
160 FastMixer_Static, // initialize if needed, then use all the time if initialized,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
163 // multiplier is calculated based on min & max normal mixer buffer size
164 // FIXME for FastMixer_Dynamic:
165 // Supporting this option will require fixing HALs that can't handle large writes.
166 // For example, one HAL implementation returns an error from a large write,
167 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
168 // We could either fix the HAL implementations, or provide a wrapper that breaks
169 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
170} kUseFastMixer = FastMixer_Static;
171
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700172// Whether to use fast capture
173static const enum {
174 FastCapture_Never, // never initialize or use: for debugging only
175 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
176 FastCapture_Static, // initialize if needed, then use all the time if initialized
177} kUseFastCapture = FastCapture_Static;
178
Eric Laurent81784c32012-11-19 14:55:58 -0800179// Priorities for requestPriority
180static const int kPriorityAudioApp = 2;
181static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700182static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800183
Glenn Kastenea38ee72016-04-18 11:08:01 -0700184// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
185// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
186// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700187
188// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800189static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800190
Glenn Kasten03490092014-05-27 12:30:54 -0700191// The minimum and maximum allowed values
192static const int kFastTrackMultiplierMin = 1;
193static const int kFastTrackMultiplierMax = 2;
194
195// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
196static int sFastTrackMultiplier = kFastTrackMultiplier;
197
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700198// See Thread::readOnlyHeap().
199// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
200// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
201// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700202static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700203
Eric Laurent81784c32012-11-19 14:55:58 -0800204// ----------------------------------------------------------------------------
205
Glenn Kasten03490092014-05-27 12:30:54 -0700206static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
207
208static void sFastTrackMultiplierInit()
209{
210 char value[PROPERTY_VALUE_MAX];
211 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
212 char *endptr;
213 unsigned long ul = strtoul(value, &endptr, 0);
214 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
215 sFastTrackMultiplier = (int) ul;
216 }
217 }
218}
219
220// ----------------------------------------------------------------------------
221
Eric Laurent81784c32012-11-19 14:55:58 -0800222#ifdef ADD_BATTERY_DATA
223// To collect the amplifier usage
224static void addBatteryData(uint32_t params) {
225 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
226 if (service == NULL) {
227 // it already logged
228 return;
229 }
230
231 service->addBatteryData(params);
232}
233#endif
234
Andy Hung3f0c9022016-01-15 17:49:46 -0800235// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
236struct {
237 // call when you acquire a partial wakelock
238 void acquire(const sp<IBinder> &wakeLockToken) {
239 pthread_mutex_lock(&mLock);
240 if (wakeLockToken.get() == nullptr) {
241 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
242 } else {
243 if (mCount == 0) {
244 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
245 }
246 ++mCount;
247 }
248 pthread_mutex_unlock(&mLock);
249 }
250
251 // call when you release a partial wakelock.
252 void release(const sp<IBinder> &wakeLockToken) {
253 if (wakeLockToken.get() == nullptr) {
254 return;
255 }
256 pthread_mutex_lock(&mLock);
257 if (--mCount < 0) {
258 ALOGE("negative wakelock count");
259 mCount = 0;
260 }
261 pthread_mutex_unlock(&mLock);
262 }
263
264 // retrieves the boottime timebase offset from monotonic.
265 int64_t getBoottimeOffset() {
266 pthread_mutex_lock(&mLock);
267 int64_t boottimeOffset = mBoottimeOffset;
268 pthread_mutex_unlock(&mLock);
269 return boottimeOffset;
270 }
271
272 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
273 // and the selected timebase.
274 // Currently only TIMEBASE_BOOTTIME is allowed.
275 //
276 // This only needs to be called upon acquiring the first partial wakelock
277 // after all other partial wakelocks are released.
278 //
279 // We do an empirical measurement of the offset rather than parsing
280 // /proc/timer_list since the latter is not a formal kernel ABI.
281 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
282 int clockbase;
283 switch (timebase) {
284 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
285 clockbase = SYSTEM_TIME_BOOTTIME;
286 break;
287 default:
288 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
289 break;
290 }
291 // try three times to get the clock offset, choose the one
292 // with the minimum gap in measurements.
293 const int tries = 3;
294 nsecs_t bestGap, measured;
295 for (int i = 0; i < tries; ++i) {
296 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t tbase = systemTime(clockbase);
298 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
299 const nsecs_t gap = tmono2 - tmono;
300 if (i == 0 || gap < bestGap) {
301 bestGap = gap;
302 measured = tbase - ((tmono + tmono2) >> 1);
303 }
304 }
305
306 // to avoid micro-adjusting, we don't change the timebase
307 // unless it is significantly different.
308 //
309 // Assumption: It probably takes more than toleranceNs to
310 // suspend and resume the device.
311 static int64_t toleranceNs = 10000; // 10 us
312 if (llabs(*offset - measured) > toleranceNs) {
313 ALOGV("Adjusting timebase offset old: %lld new: %lld",
314 (long long)*offset, (long long)measured);
315 *offset = measured;
316 }
317 }
318
319 pthread_mutex_t mLock;
320 int32_t mCount;
321 int64_t mBoottimeOffset;
322} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800323
324// ----------------------------------------------------------------------------
325// CPU Stats
326// ----------------------------------------------------------------------------
327
328class CpuStats {
329public:
330 CpuStats();
331 void sample(const String8 &title);
332#ifdef DEBUG_CPU_USAGE
333private:
334 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
335 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
336
337 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
338
339 int mCpuNum; // thread's current CPU number
340 int mCpukHz; // frequency of thread's current CPU in kHz
341#endif
342};
343
344CpuStats::CpuStats()
345#ifdef DEBUG_CPU_USAGE
346 : mCpuNum(-1), mCpukHz(-1)
347#endif
348{
349}
350
Glenn Kasten0f11b512014-01-31 16:18:54 -0800351void CpuStats::sample(const String8 &title
352#ifndef DEBUG_CPU_USAGE
353 __unused
354#endif
355 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800356#ifdef DEBUG_CPU_USAGE
357 // get current thread's delta CPU time in wall clock ns
358 double wcNs;
359 bool valid = mCpuUsage.sampleAndEnable(wcNs);
360
361 // record sample for wall clock statistics
362 if (valid) {
363 mWcStats.sample(wcNs);
364 }
365
366 // get the current CPU number
367 int cpuNum = sched_getcpu();
368
369 // get the current CPU frequency in kHz
370 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
371
372 // check if either CPU number or frequency changed
373 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
374 mCpuNum = cpuNum;
375 mCpukHz = cpukHz;
376 // ignore sample for purposes of cycles
377 valid = false;
378 }
379
380 // if no change in CPU number or frequency, then record sample for cycle statistics
381 if (valid && mCpukHz > 0) {
382 double cycles = wcNs * cpukHz * 0.000001;
383 mHzStats.sample(cycles);
384 }
385
386 unsigned n = mWcStats.n();
387 // mCpuUsage.elapsed() is expensive, so don't call it every loop
388 if ((n & 127) == 1) {
389 long long elapsed = mCpuUsage.elapsed();
390 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
391 double perLoop = elapsed / (double) n;
392 double perLoop100 = perLoop * 0.01;
393 double perLoop1k = perLoop * 0.001;
394 double mean = mWcStats.mean();
395 double stddev = mWcStats.stddev();
396 double minimum = mWcStats.minimum();
397 double maximum = mWcStats.maximum();
398 double meanCycles = mHzStats.mean();
399 double stddevCycles = mHzStats.stddev();
400 double minCycles = mHzStats.minimum();
401 double maxCycles = mHzStats.maximum();
402 mCpuUsage.resetElapsed();
403 mWcStats.reset();
404 mHzStats.reset();
405 ALOGD("CPU usage for %s over past %.1f secs\n"
406 " (%u mixer loops at %.1f mean ms per loop):\n"
407 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
408 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
409 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
410 title.string(),
411 elapsed * .000000001, n, perLoop * .000001,
412 mean * .001,
413 stddev * .001,
414 minimum * .001,
415 maximum * .001,
416 mean / perLoop100,
417 stddev / perLoop100,
418 minimum / perLoop100,
419 maximum / perLoop100,
420 meanCycles / perLoop1k,
421 stddevCycles / perLoop1k,
422 minCycles / perLoop1k,
423 maxCycles / perLoop1k);
424
425 }
426 }
427#endif
428};
429
430// ----------------------------------------------------------------------------
431// ThreadBase
432// ----------------------------------------------------------------------------
433
Glenn Kasten97b7b752014-09-28 13:04:24 -0700434// static
435const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
436{
437 switch (type) {
438 case MIXER:
439 return "MIXER";
440 case DIRECT:
441 return "DIRECT";
442 case DUPLICATING:
443 return "DUPLICATING";
444 case RECORD:
445 return "RECORD";
446 case OFFLOAD:
447 return "OFFLOAD";
448 default:
449 return "unknown";
450 }
451}
452
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700453std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 }
461 return result;
462}
463
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 std::string result;
467 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475 return result;
476}
477
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800478const char *sourceToString(audio_source_t source)
479{
480 switch (source) {
481 case AUDIO_SOURCE_DEFAULT: return "default";
482 case AUDIO_SOURCE_MIC: return "mic";
483 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
484 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
485 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
486 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
487 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
488 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
489 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800490 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800491 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
492 case AUDIO_SOURCE_HOTWORD: return "hotword";
493 default: return "unknown";
494 }
495}
496
Eric Laurent81784c32012-11-19 14:55:58 -0800497AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700498 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800499 : Thread(false /*canCallJava*/),
500 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700501 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700502 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800503 // are set by PlaybackThread::readOutputParameters_l() or
504 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700505 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800506 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700507 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
508 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800509 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700510 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent9cab7462016-11-10 13:05:20 -0800511 mSystemReady(systemReady),
512 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800513{
Eric Laurent296fb132015-05-01 11:38:42 -0700514 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
517AudioFlinger::ThreadBase::~ThreadBase()
518{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 mConfigEvents.clear();
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522 // do not lock the mutex in destructor
523 releaseWakeLock_l();
524 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800525 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800526 binder->unlinkToDeath(mDeathRecipient);
527 }
528}
529
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700530status_t AudioFlinger::ThreadBase::readyToRun()
531{
532 status_t status = initCheck();
533 if (status == NO_ERROR) {
534 ALOGI("AudioFlinger's thread %p ready to run", this);
535 } else {
536 ALOGE("No working audio driver found.");
537 }
538 return status;
539}
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541void AudioFlinger::ThreadBase::exit()
542{
543 ALOGV("ThreadBase::exit");
544 // do any cleanup required for exit to succeed
545 preExit();
546 {
547 // This lock prevents the following race in thread (uniprocessor for illustration):
548 // if (!exitPending()) {
549 // // context switch from here to exit()
550 // // exit() calls requestExit(), what exitPending() observes
551 // // exit() calls signal(), which is dropped since no waiters
552 // // context switch back from exit() to here
553 // mWaitWorkCV.wait(...);
554 // // now thread is hung
555 // }
556 AutoMutex lock(mLock);
557 requestExit();
558 mWaitWorkCV.broadcast();
559 }
560 // When Thread::requestExitAndWait is made virtual and this method is renamed to
561 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
562 requestExitAndWait();
563}
564
565status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
566{
Eric Laurent81784c32012-11-19 14:55:58 -0800567 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
568 Mutex::Autolock _l(mLock);
569
Eric Laurent10351942014-05-08 18:49:52 -0700570 return sendSetParameterConfigEvent_l(keyValuePairs);
571}
572
573// sendConfigEvent_l() must be called with ThreadBase::mLock held
574// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
575status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
576{
577 status_t status = NO_ERROR;
578
Eric Laurent72e3f392015-05-20 14:43:50 -0700579 if (event->mRequiresSystemReady && !mSystemReady) {
580 event->mWaitStatus = false;
581 mPendingConfigEvents.add(event);
582 return status;
583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700585 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800586 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700587 mLock.unlock();
588 {
589 Mutex::Autolock _l(event->mLock);
590 while (event->mWaitStatus) {
591 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
592 event->mStatus = TIMED_OUT;
593 event->mWaitStatus = false;
594 }
595 }
596 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800597 }
Eric Laurent10351942014-05-08 18:49:52 -0700598 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800599 return status;
600}
601
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700602void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
604 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
608// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700612 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800613}
614
Eric Laurent72e3f392015-05-20 14:43:50 -0700615void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
616{
617 Mutex::Autolock _l(mLock);
618 sendPrioConfigEvent_l(pid, tid, prio);
619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
622void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
623{
Eric Laurent10351942014-05-08 18:49:52 -0700624 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
625 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800626}
627
Eric Laurent10351942014-05-08 18:49:52 -0700628// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
629status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800630{
Andy Hung2ddee192015-12-18 17:34:44 -0800631 sp<ConfigEvent> configEvent;
632 AudioParameter param(keyValuePair);
633 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700634 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800635 setMasterMono_l(value != 0);
636 if (param.size() == 1) {
637 return NO_ERROR; // should be a solo parameter - we don't pass down
638 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700639 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800640 configEvent = new SetParameterConfigEvent(param.toString());
641 } else {
642 configEvent = new SetParameterConfigEvent(keyValuePair);
643 }
Eric Laurent10351942014-05-08 18:49:52 -0700644 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700645}
646
Eric Laurent1c333e22014-05-20 10:48:17 -0700647status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
648 const struct audio_patch *patch,
649 audio_patch_handle_t *handle)
650{
651 Mutex::Autolock _l(mLock);
652 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
653 status_t status = sendConfigEvent_l(configEvent);
654 if (status == NO_ERROR) {
655 CreateAudioPatchConfigEventData *data =
656 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
657 *handle = data->mHandle;
658 }
659 return status;
660}
661
662status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
663 const audio_patch_handle_t handle)
664{
665 Mutex::Autolock _l(mLock);
666 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
667 return sendConfigEvent_l(configEvent);
668}
669
670
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700671// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700672void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700673{
Eric Laurent10351942014-05-08 18:49:52 -0700674 bool configChanged = false;
675
Eric Laurent81784c32012-11-19 14:55:58 -0800676 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700677 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700678 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800679 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700680 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700681 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700682 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
683 // FIXME Need to understand why this has to be done asynchronously
684 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700685 true /*asynchronous*/);
686 if (err != 0) {
687 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700688 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700689 }
690 } break;
691 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700692 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700693 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700694 } break;
695 case CFG_EVENT_SET_PARAMETER: {
696 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
697 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
698 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700699 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700700 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700701 case CFG_EVENT_CREATE_AUDIO_PATCH: {
702 CreateAudioPatchConfigEventData *data =
703 (CreateAudioPatchConfigEventData *)event->mData.get();
704 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
705 } break;
706 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
707 ReleaseAudioPatchConfigEventData *data =
708 (ReleaseAudioPatchConfigEventData *)event->mData.get();
709 event->mStatus = releaseAudioPatch_l(data->mHandle);
710 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700711 default:
Eric Laurent10351942014-05-08 18:49:52 -0700712 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700713 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800714 }
Eric Laurent10351942014-05-08 18:49:52 -0700715 {
716 Mutex::Autolock _l(event->mLock);
717 if (event->mWaitStatus) {
718 event->mWaitStatus = false;
719 event->mCond.signal();
720 }
721 }
722 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
723 }
724
725 if (configChanged) {
726 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800727 }
Eric Laurent81784c32012-11-19 14:55:58 -0800728}
729
Marco Nelissenb2208842014-02-07 14:00:50 -0800730String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
731 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700732 const audio_channel_representation_t representation =
733 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700734
735 switch (representation) {
736 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
737 if (output) {
738 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
739 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
740 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
741 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
742 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
743 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
744 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
745 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
746 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
747 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
748 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
749 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
750 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
751 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
753 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
754 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
755 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
756 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
757 } else {
758 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
759 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
760 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
761 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
762 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
763 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
764 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
765 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
766 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
767 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
768 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
769 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
770 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
771 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
772 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
773 }
774 const int len = s.length();
775 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700776 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700777 s.unlockBuffer(len - 2); // remove trailing ", "
778 }
779 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800780 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700781 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
782 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
783 return s;
784 default:
785 s.appendFormat("unknown mask, representation:%d bits:%#x",
786 representation, audio_channel_mask_get_bits(mask));
787 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800788 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800789}
790
Glenn Kasten0f11b512014-01-31 16:18:54 -0800791void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800792{
793 const size_t SIZE = 256;
794 char buffer[SIZE];
795 String8 result;
796
797 bool locked = AudioFlinger::dumpTryLock(mLock);
798 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700799 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800800 }
801
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800802 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700803 dprintf(fd, " I/O handle: %d\n", mId);
804 dprintf(fd, " TID: %d\n", getTid());
805 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700806 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700807 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700808 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700809 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700810 dprintf(fd, " Channel count: %u\n", mChannelCount);
811 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800812 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700813 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700814 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700815 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800816 size_t numConfig = mConfigEvents.size();
817 if (numConfig) {
818 for (size_t i = 0; i < numConfig; i++) {
819 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700820 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800821 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700822 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800823 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700824 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800825 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700826 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
827 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800828 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800829
830 if (locked) {
831 mLock.unlock();
832 }
833}
834
835void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
836{
837 const size_t SIZE = 256;
838 char buffer[SIZE];
839 String8 result;
840
Marco Nelissenb2208842014-02-07 14:00:50 -0800841 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000842 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800843 write(fd, buffer, strlen(buffer));
844
Marco Nelissenb2208842014-02-07 14:00:50 -0800845 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800846 sp<EffectChain> chain = mEffectChains[i];
847 if (chain != 0) {
848 chain->dump(fd, args);
849 }
850 }
851}
852
Eric Laurent9cab7462016-11-10 13:05:20 -0800853void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800854{
855 Mutex::Autolock _l(mLock);
Eric Laurent9cab7462016-11-10 13:05:20 -0800856 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800857}
858
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100859String16 AudioFlinger::ThreadBase::getWakeLockTag()
860{
861 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800862 case MIXER:
863 return String16("AudioMix");
864 case DIRECT:
865 return String16("AudioDirectOut");
866 case DUPLICATING:
867 return String16("AudioDup");
868 case RECORD:
869 return String16("AudioIn");
870 case OFFLOAD:
871 return String16("AudioOffload");
872 default:
873 ALOG_ASSERT(false);
874 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100875 }
876}
877
Eric Laurent9cab7462016-11-10 13:05:20 -0800878void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800879{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800880 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800881 if (mPowerManager != 0) {
882 sp<IBinder> binder = new BBinder();
Eric Laurent9cab7462016-11-10 13:05:20 -0800883 status_t status;
884 if (uid >= 0) {
885 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
886 binder,
887 getWakeLockTag(),
888 String16("audioserver"),
889 uid,
890 true /* FIXME force oneway contrary to .aidl */);
891 } else {
892 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700893 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100894 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700895 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700896 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent9cab7462016-11-10 13:05:20 -0800897 }
Eric Laurent81784c32012-11-19 14:55:58 -0800898 if (status == NO_ERROR) {
899 mWakeLockToken = binder;
900 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800901 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800902 }
Wei Jia3f273d12015-11-24 09:06:49 -0800903
Eric Laurent9cab7462016-11-10 13:05:20 -0800904 if (!mNotifiedBatteryStart) {
905 // TODO: call this function for each track when it becomes active.
906 BatteryNotifier::getInstance().noteStartAudio(AID_AUDIOSERVER);
907 mNotifiedBatteryStart = true;
908 }
Andy Hung3f0c9022016-01-15 17:49:46 -0800909 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800910 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
911 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800912}
913
914void AudioFlinger::ThreadBase::releaseWakeLock()
915{
916 Mutex::Autolock _l(mLock);
917 releaseWakeLock_l();
918}
919
920void AudioFlinger::ThreadBase::releaseWakeLock_l()
921{
Andy Hung3f0c9022016-01-15 17:49:46 -0800922 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800923 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800924 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800925 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700926 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
927 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 }
929 mWakeLockToken.clear();
930 }
Eric Laurent9cab7462016-11-10 13:05:20 -0800931
932 if (mNotifiedBatteryStart) {
933 // TODO: call this function for each track when it becomes inactive.
934 BatteryNotifier::getInstance().noteStopAudio(AID_AUDIOSERVER);
935 mNotifiedBatteryStart = false;
936 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800937}
938
939void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700940 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800941 // use checkService() to avoid blocking if power service is not up yet
942 sp<IBinder> binder =
943 defaultServiceManager()->checkService(String16("power"));
944 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800945 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800946 } else {
947 mPowerManager = interface_cast<IPowerManager>(binder);
948 binder->linkToDeath(mDeathRecipient);
949 }
950 }
951}
952
Eric Laurent9cab7462016-11-10 13:05:20 -0800953void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800954 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -0800955 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
956 if (mSystemReady) {
957 ALOGE("no wake lock to update, but system ready!");
958 } else {
959 ALOGW("no wake lock to update, system not ready yet");
960 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800961 return;
962 }
963 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800964 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
965 status_t status = mPowerManager->updateWakeLockUids(
966 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
967 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800968 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800969 }
970}
971
Eric Laurent81784c32012-11-19 14:55:58 -0800972void AudioFlinger::ThreadBase::clearPowerManager()
973{
974 Mutex::Autolock _l(mLock);
975 releaseWakeLock_l();
976 mPowerManager.clear();
977}
978
Glenn Kasten0f11b512014-01-31 16:18:54 -0800979void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800980{
981 sp<ThreadBase> thread = mThread.promote();
982 if (thread != 0) {
983 thread->clearPowerManager();
984 }
985 ALOGW("power manager service died !!!");
986}
987
988void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800989 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800990{
991 Mutex::Autolock _l(mLock);
992 setEffectSuspended_l(type, suspend, sessionId);
993}
994
995void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800996 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800997{
998 sp<EffectChain> chain = getEffectChain_l(sessionId);
999 if (chain != 0) {
1000 if (type != NULL) {
1001 chain->setEffectSuspended_l(type, suspend);
1002 } else {
1003 chain->setEffectSuspendedAll_l(suspend);
1004 }
1005 }
1006
1007 updateSuspendedSessions_l(type, suspend, sessionId);
1008}
1009
1010void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1011{
1012 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1013 if (index < 0) {
1014 return;
1015 }
1016
1017 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1018 mSuspendedSessions.valueAt(index);
1019
1020 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001021 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001022 for (int j = 0; j < desc->mRefCount; j++) {
1023 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1024 chain->setEffectSuspendedAll_l(true);
1025 } else {
1026 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1027 desc->mType.timeLow);
1028 chain->setEffectSuspended_l(&desc->mType, true);
1029 }
1030 }
1031 }
1032}
1033
1034void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1035 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001036 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001037{
1038 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1039
1040 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1041
1042 if (suspend) {
1043 if (index >= 0) {
1044 sessionEffects = mSuspendedSessions.valueAt(index);
1045 } else {
1046 mSuspendedSessions.add(sessionId, sessionEffects);
1047 }
1048 } else {
1049 if (index < 0) {
1050 return;
1051 }
1052 sessionEffects = mSuspendedSessions.valueAt(index);
1053 }
1054
1055
1056 int key = EffectChain::kKeyForSuspendAll;
1057 if (type != NULL) {
1058 key = type->timeLow;
1059 }
1060 index = sessionEffects.indexOfKey(key);
1061
1062 sp<SuspendedSessionDesc> desc;
1063 if (suspend) {
1064 if (index >= 0) {
1065 desc = sessionEffects.valueAt(index);
1066 } else {
1067 desc = new SuspendedSessionDesc();
1068 if (type != NULL) {
1069 desc->mType = *type;
1070 }
1071 sessionEffects.add(key, desc);
1072 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1073 }
1074 desc->mRefCount++;
1075 } else {
1076 if (index < 0) {
1077 return;
1078 }
1079 desc = sessionEffects.valueAt(index);
1080 if (--desc->mRefCount == 0) {
1081 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1082 sessionEffects.removeItemsAt(index);
1083 if (sessionEffects.isEmpty()) {
1084 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1085 sessionId);
1086 mSuspendedSessions.removeItem(sessionId);
1087 }
1088 }
1089 }
1090 if (!sessionEffects.isEmpty()) {
1091 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1092 }
1093}
1094
1095void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1096 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001097 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001098{
1099 Mutex::Autolock _l(mLock);
1100 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1101}
1102
1103void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1104 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001105 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001106{
1107 if (mType != RECORD) {
1108 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1109 // another session. This gives the priority to well behaved effect control panels
1110 // and applications not using global effects.
1111 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1112 // global effects
1113 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1114 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1115 }
1116 }
1117
1118 sp<EffectChain> chain = getEffectChain_l(sessionId);
1119 if (chain != 0) {
1120 chain->checkSuspendOnEffectEnabled(effect, enabled);
1121 }
1122}
1123
Eric Laurent4c415062016-06-17 16:14:16 -07001124// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1125status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1126 const effect_descriptor_t *desc, audio_session_t sessionId)
1127{
1128 // No global effect sessions on record threads
1129 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1130 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1131 desc->name, mThreadName);
1132 return BAD_VALUE;
1133 }
1134 // only pre processing effects on record thread
1135 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1136 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1137 desc->name, mThreadName);
1138 return BAD_VALUE;
1139 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001140
1141 // always allow effects without processing load or latency
1142 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1143 return NO_ERROR;
1144 }
1145
Eric Laurent4c415062016-06-17 16:14:16 -07001146 audio_input_flags_t flags = mInput->flags;
1147 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1148 if (flags & AUDIO_INPUT_FLAG_RAW) {
1149 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1150 desc->name, mThreadName);
1151 return BAD_VALUE;
1152 }
1153 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1154 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1155 desc->name, mThreadName);
1156 return BAD_VALUE;
1157 }
1158 }
1159 return NO_ERROR;
1160}
1161
1162// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1163status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1164 const effect_descriptor_t *desc, audio_session_t sessionId)
1165{
1166 // no preprocessing on playback threads
1167 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1168 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1169 " thread %s", desc->name, mThreadName);
1170 return BAD_VALUE;
1171 }
1172
1173 switch (mType) {
1174 case MIXER: {
1175 // Reject any effect on mixer multichannel sinks.
1176 // TODO: fix both format and multichannel issues with effects.
1177 if (mChannelCount != FCC_2) {
1178 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1179 " thread %s", desc->name, mChannelCount, mThreadName);
1180 return BAD_VALUE;
1181 }
1182 audio_output_flags_t flags = mOutput->flags;
1183 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1184 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1185 // global effects are applied only to non fast tracks if they are SW
1186 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1187 break;
1188 }
1189 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1190 // only post processing on output stage session
1191 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1192 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1193 " on output stage session", desc->name);
1194 return BAD_VALUE;
1195 }
1196 } else {
1197 // no restriction on effects applied on non fast tracks
1198 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1199 break;
1200 }
1201 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001202
1203 // always allow effects without processing load or latency
1204 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1205 break;
1206 }
Eric Laurent4c415062016-06-17 16:14:16 -07001207 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1208 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1209 desc->name);
1210 return BAD_VALUE;
1211 }
1212 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1213 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1214 " in fast mode", desc->name);
1215 return BAD_VALUE;
1216 }
1217 }
1218 } break;
1219 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001220 // nothing actionable on offload threads, if the effect:
1221 // - is offloadable: the effect can be created
1222 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1223 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001224 break;
1225 case DIRECT:
1226 // Reject any effect on Direct output threads for now, since the format of
1227 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1228 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1229 desc->name, mThreadName);
1230 return BAD_VALUE;
1231 case DUPLICATING:
1232 // Reject any effect on mixer multichannel sinks.
1233 // TODO: fix both format and multichannel issues with effects.
1234 if (mChannelCount != FCC_2) {
1235 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1236 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1237 return BAD_VALUE;
1238 }
1239 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1240 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1241 " thread %s", desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1245 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1246 " DUPLICATING thread %s", desc->name, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1250 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1251 " DUPLICATING thread %s", desc->name, mThreadName);
1252 return BAD_VALUE;
1253 }
1254 break;
1255 default:
1256 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1257 }
1258
1259 return NO_ERROR;
1260}
1261
Eric Laurent81784c32012-11-19 14:55:58 -08001262// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1263sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1264 const sp<AudioFlinger::Client>& client,
1265 const sp<IEffectClient>& effectClient,
1266 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001267 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001268 effect_descriptor_t *desc,
1269 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001270 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001271{
1272 sp<EffectModule> effect;
1273 sp<EffectHandle> handle;
1274 status_t lStatus;
1275 sp<EffectChain> chain;
1276 bool chainCreated = false;
1277 bool effectCreated = false;
1278 bool effectRegistered = false;
1279
1280 lStatus = initCheck();
1281 if (lStatus != NO_ERROR) {
1282 ALOGW("createEffect_l() Audio driver not initialized.");
1283 goto Exit;
1284 }
1285
Eric Laurent81784c32012-11-19 14:55:58 -08001286 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1287
1288 { // scope for mLock
1289 Mutex::Autolock _l(mLock);
1290
Eric Laurent4c415062016-06-17 16:14:16 -07001291 lStatus = checkEffectCompatibility_l(desc, sessionId);
1292 if (lStatus != NO_ERROR) {
1293 goto Exit;
1294 }
1295
Eric Laurent81784c32012-11-19 14:55:58 -08001296 // check for existing effect chain with the requested audio session
1297 chain = getEffectChain_l(sessionId);
1298 if (chain == 0) {
1299 // create a new chain for this session
1300 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1301 chain = new EffectChain(this, sessionId);
1302 addEffectChain_l(chain);
1303 chain->setStrategy(getStrategyForSession_l(sessionId));
1304 chainCreated = true;
1305 } else {
1306 effect = chain->getEffectFromDesc_l(desc);
1307 }
1308
1309 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1310
1311 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001312 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001313 // Check CPU and memory usage
1314 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1315 if (lStatus != NO_ERROR) {
1316 goto Exit;
1317 }
1318 effectRegistered = true;
1319 // create a new effect module if none present in the chain
1320 effect = new EffectModule(this, chain, desc, id, sessionId);
1321 lStatus = effect->status();
1322 if (lStatus != NO_ERROR) {
1323 goto Exit;
1324 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001325 effect->setOffloaded(mType == OFFLOAD, mId);
1326
Eric Laurent81784c32012-11-19 14:55:58 -08001327 lStatus = chain->addEffect_l(effect);
1328 if (lStatus != NO_ERROR) {
1329 goto Exit;
1330 }
1331 effectCreated = true;
1332
1333 effect->setDevice(mOutDevice);
1334 effect->setDevice(mInDevice);
1335 effect->setMode(mAudioFlinger->getMode());
1336 effect->setAudioSource(mAudioSource);
1337 }
1338 // create effect handle and connect it to effect module
1339 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001340 lStatus = handle->initCheck();
1341 if (lStatus == OK) {
1342 lStatus = effect->addHandle(handle.get());
1343 }
Eric Laurent81784c32012-11-19 14:55:58 -08001344 if (enabled != NULL) {
1345 *enabled = (int)effect->isEnabled();
1346 }
1347 }
1348
1349Exit:
1350 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1351 Mutex::Autolock _l(mLock);
1352 if (effectCreated) {
1353 chain->removeEffect_l(effect);
1354 }
1355 if (effectRegistered) {
1356 AudioSystem::unregisterEffect(effect->id());
1357 }
1358 if (chainCreated) {
1359 removeEffectChain_l(chain);
1360 }
1361 handle.clear();
1362 }
1363
Glenn Kasten9156ef32013-08-06 15:39:08 -07001364 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001365 return handle;
1366}
1367
Glenn Kastend848eb42016-03-08 13:42:11 -08001368sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1369 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001370{
1371 Mutex::Autolock _l(mLock);
1372 return getEffect_l(sessionId, effectId);
1373}
1374
Glenn Kastend848eb42016-03-08 13:42:11 -08001375sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1376 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001377{
1378 sp<EffectChain> chain = getEffectChain_l(sessionId);
1379 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1380}
1381
1382// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1383// PlaybackThread::mLock held
1384status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1385{
1386 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001387 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001388 sp<EffectChain> chain = getEffectChain_l(sessionId);
1389 bool chainCreated = false;
1390
Eric Laurent5baf2af2013-09-12 17:37:00 -07001391 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1392 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1393 this, effect->desc().name, effect->desc().flags);
1394
Eric Laurent81784c32012-11-19 14:55:58 -08001395 if (chain == 0) {
1396 // create a new chain for this session
1397 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1398 chain = new EffectChain(this, sessionId);
1399 addEffectChain_l(chain);
1400 chain->setStrategy(getStrategyForSession_l(sessionId));
1401 chainCreated = true;
1402 }
1403 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1404
1405 if (chain->getEffectFromId_l(effect->id()) != 0) {
1406 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1407 this, effect->desc().name, chain.get());
1408 return BAD_VALUE;
1409 }
1410
Eric Laurent5baf2af2013-09-12 17:37:00 -07001411 effect->setOffloaded(mType == OFFLOAD, mId);
1412
Eric Laurent81784c32012-11-19 14:55:58 -08001413 status_t status = chain->addEffect_l(effect);
1414 if (status != NO_ERROR) {
1415 if (chainCreated) {
1416 removeEffectChain_l(chain);
1417 }
1418 return status;
1419 }
1420
1421 effect->setDevice(mOutDevice);
1422 effect->setDevice(mInDevice);
1423 effect->setMode(mAudioFlinger->getMode());
1424 effect->setAudioSource(mAudioSource);
1425 return NO_ERROR;
1426}
1427
1428void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1429
1430 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1431 effect_descriptor_t desc = effect->desc();
1432 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1433 detachAuxEffect_l(effect->id());
1434 }
1435
1436 sp<EffectChain> chain = effect->chain().promote();
1437 if (chain != 0) {
1438 // remove effect chain if removing last effect
1439 if (chain->removeEffect_l(effect) == 0) {
1440 removeEffectChain_l(chain);
1441 }
1442 } else {
1443 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1444 }
1445}
1446
1447void AudioFlinger::ThreadBase::lockEffectChains_l(
1448 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1449{
1450 effectChains = mEffectChains;
1451 for (size_t i = 0; i < mEffectChains.size(); i++) {
1452 mEffectChains[i]->lock();
1453 }
1454}
1455
1456void AudioFlinger::ThreadBase::unlockEffectChains(
1457 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1458{
1459 for (size_t i = 0; i < effectChains.size(); i++) {
1460 effectChains[i]->unlock();
1461 }
1462}
1463
Glenn Kastend848eb42016-03-08 13:42:11 -08001464sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001465{
1466 Mutex::Autolock _l(mLock);
1467 return getEffectChain_l(sessionId);
1468}
1469
Glenn Kastend848eb42016-03-08 13:42:11 -08001470sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1471 const
Eric Laurent81784c32012-11-19 14:55:58 -08001472{
1473 size_t size = mEffectChains.size();
1474 for (size_t i = 0; i < size; i++) {
1475 if (mEffectChains[i]->sessionId() == sessionId) {
1476 return mEffectChains[i];
1477 }
1478 }
1479 return 0;
1480}
1481
1482void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1483{
1484 Mutex::Autolock _l(mLock);
1485 size_t size = mEffectChains.size();
1486 for (size_t i = 0; i < size; i++) {
1487 mEffectChains[i]->setMode_l(mode);
1488 }
1489}
1490
Eric Laurent83b88082014-06-20 18:31:16 -07001491void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1492{
1493 config->type = AUDIO_PORT_TYPE_MIX;
1494 config->ext.mix.handle = mId;
1495 config->sample_rate = mSampleRate;
1496 config->format = mFormat;
1497 config->channel_mask = mChannelMask;
1498 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1499 AUDIO_PORT_CONFIG_FORMAT;
1500}
1501
Eric Laurent72e3f392015-05-20 14:43:50 -07001502void AudioFlinger::ThreadBase::systemReady()
1503{
1504 Mutex::Autolock _l(mLock);
1505 if (mSystemReady) {
1506 return;
1507 }
1508 mSystemReady = true;
1509
1510 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1511 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1512 }
1513 mPendingConfigEvents.clear();
1514}
1515
Eric Laurent83b88082014-06-20 18:31:16 -07001516
Eric Laurent81784c32012-11-19 14:55:58 -08001517// ----------------------------------------------------------------------------
1518// Playback
1519// ----------------------------------------------------------------------------
1520
1521AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1522 AudioStreamOut* output,
1523 audio_io_handle_t id,
1524 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001525 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001526 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001527 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001528 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001529 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001530 mMixerBuffer(NULL),
1531 mMixerBufferSize(0),
1532 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1533 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001534 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001535 mEffectBuffer(NULL),
1536 mEffectBufferSize(0),
1537 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1538 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001539 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001540 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001541 mSuspendedFrames(0),
Eric Laurent9cab7462016-11-10 13:05:20 -08001542 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001543 // mStreamTypes[] initialized in constructor body
1544 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001545 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001546 mMixerStatus(MIXER_IDLE),
1547 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001548 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001549 mBytesRemaining(0),
1550 mCurrentWriteLength(0),
1551 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001552 mWriteAckSequence(0),
1553 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001554 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001555 mScreenState(AudioFlinger::mScreenState),
1556 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001557 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001558 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001559{
Glenn Kastend7dca052015-03-05 16:05:54 -08001560 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1561 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001562
1563 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1564 // it would be safer to explicitly pass initial masterVolume/masterMute as
1565 // parameter.
1566 //
1567 // If the HAL we are using has support for master volume or master mute,
1568 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1569 // and the mute set to false).
1570 mMasterVolume = audioFlinger->masterVolume_l();
1571 mMasterMute = audioFlinger->masterMute_l();
1572 if (mOutput && mOutput->audioHwDev) {
1573 if (mOutput->audioHwDev->canSetMasterVolume()) {
1574 mMasterVolume = 1.0;
1575 }
1576
1577 if (mOutput->audioHwDev->canSetMasterMute()) {
1578 mMasterMute = false;
1579 }
1580 }
1581
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001582 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001583
Eric Laurent223fd5c2014-11-11 13:43:36 -08001584 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001585 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001586 stream = (audio_stream_type_t) (stream + 1)) {
1587 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1588 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1589 }
Eric Laurent81784c32012-11-19 14:55:58 -08001590}
1591
1592AudioFlinger::PlaybackThread::~PlaybackThread()
1593{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001594 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001595 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001596 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001597 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001598}
1599
1600void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1601{
1602 dumpInternals(fd, args);
1603 dumpTracks(fd, args);
1604 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001605 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001606}
1607
Glenn Kasten0f11b512014-01-31 16:18:54 -08001608void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001609{
1610 const size_t SIZE = 256;
1611 char buffer[SIZE];
1612 String8 result;
1613
Marco Nelissenb2208842014-02-07 14:00:50 -08001614 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001615 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1616 const stream_type_t *st = &mStreamTypes[i];
1617 if (i > 0) {
1618 result.appendFormat(", ");
1619 }
1620 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1621 if (st->mute) {
1622 result.append("M");
1623 }
1624 }
1625 result.append("\n");
1626 write(fd, result.string(), result.length());
1627 result.clear();
1628
Eric Laurent81784c32012-11-19 14:55:58 -08001629 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1630 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001631 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001632 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001633
1634 size_t numtracks = mTracks.size();
1635 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001636 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001637 size_t numactiveseen = 0;
1638 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001639 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001640 Track::appendDumpHeader(result);
1641 for (size_t i = 0; i < numtracks; ++i) {
1642 sp<Track> track = mTracks[i];
1643 if (track != 0) {
1644 bool active = mActiveTracks.indexOf(track) >= 0;
1645 if (active) {
1646 numactiveseen++;
1647 }
1648 track->dump(buffer, SIZE, active);
1649 result.append(buffer);
1650 }
1651 }
1652 } else {
1653 result.append("\n");
1654 }
1655 if (numactiveseen != numactive) {
1656 // some tracks in the active list were not in the tracks list
1657 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1658 " not in the track list\n");
1659 result.append(buffer);
1660 Track::appendDumpHeader(result);
1661 for (size_t i = 0; i < numactive; ++i) {
Eric Laurent9cab7462016-11-10 13:05:20 -08001662 sp<Track> track = mActiveTracks[i].promote();
1663 if (track != 0 && mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001664 track->dump(buffer, SIZE, true);
1665 result.append(buffer);
1666 }
1667 }
1668 }
1669
1670 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001671}
1672
1673void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1674{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001675 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001676
1677 dumpBase(fd, args);
1678
Elliott Hughes87cebad2014-05-22 10:14:43 -07001679 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001680 dprintf(fd, " Last write occurred (msecs): %llu\n",
1681 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001682 dprintf(fd, " Total writes: %d\n", mNumWrites);
1683 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1684 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1685 dprintf(fd, " Suspend count: %d\n", mSuspended);
1686 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1687 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1688 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1689 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001690 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001691 AudioStreamOut *output = mOutput;
1692 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001693 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1694 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001695 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1696 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1697 if (mPipeSink.get() != nullptr) {
1698 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1699 }
1700 if (output != nullptr) {
1701 dprintf(fd, " Hal stream dump:\n");
1702 (void)output->stream->dump(fd);
1703 }
Eric Laurent81784c32012-11-19 14:55:58 -08001704}
1705
1706// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001707
1708void AudioFlinger::PlaybackThread::onFirstRef()
1709{
Glenn Kastend7dca052015-03-05 16:05:54 -08001710 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001711}
1712
1713// ThreadBase virtuals
1714void AudioFlinger::PlaybackThread::preExit()
1715{
1716 ALOGV(" preExit()");
1717 // FIXME this is using hard-coded strings but in the future, this functionality will be
1718 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001719 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1720 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001721}
1722
1723// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1724sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1725 const sp<AudioFlinger::Client>& client,
1726 audio_stream_type_t streamType,
1727 uint32_t sampleRate,
1728 audio_format_t format,
1729 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001730 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001731 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001732 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001733 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001734 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001735 uid_t uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001736 status_t *status)
1737{
Glenn Kasten74935e42013-12-19 08:56:45 -08001738 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001739 sp<Track> track;
1740 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001741 audio_output_flags_t outputFlags = mOutput->flags;
1742
1743 // special case for FAST flag considered OK if fast mixer is present
1744 if (hasFastMixer()) {
1745 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1746 }
1747
1748 // Check if requested flags are compatible with output stream flags
1749 if ((*flags & outputFlags) != *flags) {
1750 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1751 *flags, outputFlags);
1752 *flags = (audio_output_flags_t)(*flags & outputFlags);
1753 }
Eric Laurent81784c32012-11-19 14:55:58 -08001754
Eric Laurent81784c32012-11-19 14:55:58 -08001755 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001756 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001757 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001758 // PCM data
1759 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001760 // TODO: extract as a data library function that checks that a computationally
1761 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001762 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001763 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1764 (channelMask == AUDIO_CHANNEL_OUT_MONO
1765 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001766 // hardware sample rate
1767 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001768 // normal mixer has an associated fast mixer
1769 hasFastMixer() &&
1770 // there are sufficient fast track slots available
1771 (mFastTrackAvailMask != 0)
1772 // FIXME test that MixerThread for this fast track has a capable output HAL
1773 // FIXME add a permission test also?
1774 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001775 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1776 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001777 // read the fast track multiplier property the first time it is needed
1778 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1779 if (ok != 0) {
1780 ALOGE("%s pthread_once failed: %d", __func__, ok);
1781 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001782 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001783 }
Eric Laurent4c415062016-06-17 16:14:16 -07001784
1785 // check compatibility with audio effects.
1786 { // scope for mLock
1787 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001788 for (audio_session_t session : {
1789 AUDIO_SESSION_OUTPUT_STAGE,
1790 AUDIO_SESSION_OUTPUT_MIX,
1791 sessionId,
1792 }) {
1793 sp<EffectChain> chain = getEffectChain_l(session);
1794 if (chain.get() != nullptr) {
1795 audio_output_flags_t old = *flags;
1796 chain->checkOutputFlagCompatibility(flags);
1797 if (old != *flags) {
1798 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1799 (int)session, (int)old, (int)*flags);
1800 }
Eric Laurent4c415062016-06-17 16:14:16 -07001801 }
1802 }
1803 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001804 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001805 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1806 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001807 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001808 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1809 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001810 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001811 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001812 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001813 audio_is_linear_pcm(format),
1814 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001815 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001816 }
1817 }
1818 // For normal PCM streaming tracks, update minimum frame count.
1819 // For compatibility with AudioTrack calculation, buffer depth is forced
1820 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1821 // This is probably too conservative, but legacy application code may depend on it.
1822 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001823 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001824 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001825 // this must match AudioTrack.cpp calculateMinFrameCount().
1826 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001827 uint32_t latencyMs = 0;
1828 lStatus = mOutput->stream->getLatency(&latencyMs);
1829 if (lStatus != OK) {
1830 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1831 goto Exit;
1832 }
Eric Laurent81784c32012-11-19 14:55:58 -08001833 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1834 if (minBufCount < 2) {
1835 minBufCount = 2;
1836 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001837 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1838 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001839 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001840 minBufCount * sourceFramesNeededWithTimestretch(
1841 sampleRate, mNormalFrameCount,
1842 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001843 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001844 frameCount = minFrameCount;
1845 }
Eric Laurent81784c32012-11-19 14:55:58 -08001846 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001847 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001848
Glenn Kastenc3df8382014-03-13 15:05:25 -07001849 switch (mType) {
1850
1851 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001852 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001853 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001854 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1855 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001856 sampleRate, format, channelMask, mOutput, mFormat);
1857 lStatus = BAD_VALUE;
1858 goto Exit;
1859 }
1860 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001861 break;
1862
1863 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001864 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001865 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1866 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001867 sampleRate, format, channelMask, mOutput, mFormat);
1868 lStatus = BAD_VALUE;
1869 goto Exit;
1870 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001871 break;
1872
1873 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001874 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001875 ALOGE("createTrack_l() Bad parameter: format %#x \""
1876 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001877 format, mOutput, mFormat);
1878 lStatus = BAD_VALUE;
1879 goto Exit;
1880 }
Andy Hungcd044842014-08-07 11:04:34 -07001881 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001882 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1883 lStatus = BAD_VALUE;
1884 goto Exit;
1885 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001886 break;
1887
Eric Laurent81784c32012-11-19 14:55:58 -08001888 }
1889
1890 lStatus = initCheck();
1891 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001892 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001893 goto Exit;
1894 }
1895
1896 { // scope for mLock
1897 Mutex::Autolock _l(mLock);
1898
1899 // all tracks in same audio session must share the same routing strategy otherwise
1900 // conflicts will happen when tracks are moved from one output to another by audio policy
1901 // manager
1902 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1903 for (size_t i = 0; i < mTracks.size(); ++i) {
1904 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001905 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001906 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1907 if (sessionId == t->sessionId() && strategy != actual) {
1908 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1909 strategy, actual);
1910 lStatus = BAD_VALUE;
1911 goto Exit;
1912 }
1913 }
1914 }
1915
Glenn Kastend79072e2016-01-06 08:41:20 -08001916 track = new Track(this, client, streamType, sampleRate, format,
1917 channelMask, frameCount, NULL, sharedBuffer,
1918 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001919
Glenn Kasten03003332013-08-06 15:40:54 -07001920 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1921 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001922 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001923 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001924 goto Exit;
1925 }
1926 mTracks.add(track);
1927
1928 sp<EffectChain> chain = getEffectChain_l(sessionId);
1929 if (chain != 0) {
1930 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1931 track->setMainBuffer(chain->inBuffer());
1932 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1933 chain->incTrackCnt();
1934 }
1935
Eric Laurent05067782016-06-01 18:27:28 -07001936 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001937 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1938 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1939 // so ask activity manager to do this on our behalf
1940 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1941 }
1942 }
1943
1944 lStatus = NO_ERROR;
1945
1946Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001947 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001948 return track;
1949}
1950
1951uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1952{
1953 return latency;
1954}
1955
1956uint32_t AudioFlinger::PlaybackThread::latency() const
1957{
1958 Mutex::Autolock _l(mLock);
1959 return latency_l();
1960}
1961uint32_t AudioFlinger::PlaybackThread::latency_l() const
1962{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001963 uint32_t latency;
1964 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
1965 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08001966 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001967 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001968}
1969
1970void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1971{
1972 Mutex::Autolock _l(mLock);
1973 // Don't apply master volume in SW if our HAL can do it for us.
1974 if (mOutput && mOutput->audioHwDev &&
1975 mOutput->audioHwDev->canSetMasterVolume()) {
1976 mMasterVolume = 1.0;
1977 } else {
1978 mMasterVolume = value;
1979 }
1980}
1981
1982void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1983{
1984 Mutex::Autolock _l(mLock);
1985 // Don't apply master mute in SW if our HAL can do it for us.
1986 if (mOutput && mOutput->audioHwDev &&
1987 mOutput->audioHwDev->canSetMasterMute()) {
1988 mMasterMute = false;
1989 } else {
1990 mMasterMute = muted;
1991 }
1992}
1993
1994void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1995{
1996 Mutex::Autolock _l(mLock);
1997 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001998 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001999}
2000
2001void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2002{
2003 Mutex::Autolock _l(mLock);
2004 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002005 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002006}
2007
2008float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2009{
2010 Mutex::Autolock _l(mLock);
2011 return mStreamTypes[stream].volume;
2012}
2013
2014// addTrack_l() must be called with ThreadBase::mLock held
2015status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2016{
2017 status_t status = ALREADY_EXISTS;
2018
Eric Laurent81784c32012-11-19 14:55:58 -08002019 if (mActiveTracks.indexOf(track) < 0) {
2020 // the track is newly added, make sure it fills up all its
2021 // buffers before playing. This is to ensure the client will
2022 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002023 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002024 TrackBase::track_state state = track->mState;
2025 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002026 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002027 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002028 mLock.lock();
2029 // abort track was stopped/paused while we released the lock
2030 if (state != track->mState) {
2031 if (status == NO_ERROR) {
2032 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002033 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002034 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002035 mLock.lock();
2036 }
2037 return INVALID_OPERATION;
2038 }
2039 // abort if start is rejected by audio policy manager
2040 if (status != NO_ERROR) {
2041 return PERMISSION_DENIED;
2042 }
2043#ifdef ADD_BATTERY_DATA
2044 // to track the speaker usage
2045 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2046#endif
2047 }
2048
Eric Laurent51716182016-02-29 18:00:56 -08002049 // set retry count for buffer fill
2050 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002051 if (track->isStopping_1()) {
2052 track->mRetryCount = kMaxTrackStopRetriesOffload;
2053 } else {
2054 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2055 }
2056 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002057 } else {
2058 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002059 track->mFillingUpStatus =
2060 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002061 }
2062
Eric Laurent81784c32012-11-19 14:55:58 -08002063 track->mResetDone = false;
2064 track->mPresentationCompleteFrames = 0;
2065 mActiveTracks.add(track);
Eric Laurent9cab7462016-11-10 13:05:20 -08002066 mWakeLockUids.add(track->uid());
2067 mActiveTracksGeneration++;
2068 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002069 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2070 if (chain != 0) {
2071 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2072 track->sessionId());
2073 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002074 }
2075
Andy Hung2148bf02016-11-28 19:01:02 -08002076 char buffer[256];
2077 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2078 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2079
Eric Laurent81784c32012-11-19 14:55:58 -08002080 status = NO_ERROR;
2081 }
2082
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002083 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002084 return status;
2085}
2086
Eric Laurentbfb1b832013-01-07 09:53:42 -08002087bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002088{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002089 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002090 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002091 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2092 track->mState = TrackBase::STOPPED;
2093 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002094 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002095 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002096 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002097 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002098
2099 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002100}
2101
2102void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2103{
2104 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002105
2106 char buffer[256];
2107 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2108 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2109
Eric Laurent81784c32012-11-19 14:55:58 -08002110 mTracks.remove(track);
2111 deleteTrackName_l(track->name());
2112 // redundant as track is about to be destroyed, for dumpsys only
2113 track->mName = -1;
2114 if (track->isFastTrack()) {
2115 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002116 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002117 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2118 mFastTrackAvailMask |= 1 << index;
2119 // redundant as track is about to be destroyed, for dumpsys only
2120 track->mFastIndex = -1;
2121 }
2122 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2123 if (chain != 0) {
2124 chain->decTrackCnt();
2125 }
2126}
2127
Eric Laurentede6c3b2013-09-19 14:37:46 -07002128void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002129{
2130 // Thread could be blocked waiting for async
2131 // so signal it to handle state changes immediately
2132 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2133 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2134 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002135 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002136}
2137
Eric Laurent81784c32012-11-19 14:55:58 -08002138String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2139{
Eric Laurent81784c32012-11-19 14:55:58 -08002140 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002141 String8 out_s8;
2142 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2143 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002144 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002145 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002146}
2147
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002148void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002149 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2150 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002151
Eric Laurent73e26b62015-04-27 16:55:58 -07002152 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002153
2154 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002155 case AUDIO_OUTPUT_OPENED:
2156 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002157 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002158 desc->mChannelMask = mChannelMask;
2159 desc->mSamplingRate = mSampleRate;
2160 desc->mFormat = mFormat;
2161 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002162 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002163 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002164 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002165 break;
2166
Eric Laurent73e26b62015-04-27 16:55:58 -07002167 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002168 default:
2169 break;
2170 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002171 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002172}
2173
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002174void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002175{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002176 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002177}
2178
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002179void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002180{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002181 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002182}
2183
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002184void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002185{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002186 mCallbackThread->setAsyncError();
2187}
2188
Eric Laurent3b4529e2013-09-05 18:09:19 -07002189void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002190{
2191 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002192 // reject out of sequence requests
2193 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2194 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002195 mWaitWorkCV.signal();
2196 }
2197}
2198
Eric Laurent3b4529e2013-09-05 18:09:19 -07002199void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200{
2201 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002202 // reject out of sequence requests
2203 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2204 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002205 mWaitWorkCV.signal();
2206 }
2207}
2208
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002209void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002210{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002211 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002212 mSampleRate = mOutput->getSampleRate();
2213 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002214 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002215 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002216 }
Andy Hung9a592762014-07-21 21:56:01 -07002217 if ((mType == MIXER || mType == DUPLICATING)
2218 && !isValidPcmSinkChannelMask(mChannelMask)) {
2219 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2220 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002221 }
Andy Hunge5412692014-05-16 11:25:07 -07002222 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002223
2224 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002225 status_t result = mOutput->stream->getFormat(&mHALFormat);
2226 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002227 // Get format from the shim, which will be different than the HAL format
2228 // if playing compressed audio over HDMI passthrough.
2229 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002230 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002231 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002232 }
Andy Hung6146c082014-03-18 11:56:15 -07002233 if ((mType == MIXER || mType == DUPLICATING)
2234 && !isValidPcmSinkFormat(mFormat)) {
2235 LOG_FATAL("HAL format %#x not supported for mixed output",
2236 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002237 }
Phil Burk062e67a2015-02-11 13:40:50 -08002238 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002239 result = mOutput->stream->getBufferSize(&mBufferSize);
2240 LOG_ALWAYS_FATAL_IF(result != OK,
2241 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002242 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002243 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002244 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002245 mFrameCount);
2246 }
2247
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002248 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2249 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002250 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002251 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002252 }
2253 }
2254
Eric Laurentd1f69b02014-12-15 14:33:13 -08002255 mHwSupportsPause = false;
2256 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002257 bool supportsPause = false, supportsResume = false;
2258 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2259 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002260 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002261 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002262 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002263 } else if (supportsResume) {
2264 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002265 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002266 }
2267 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002268 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2269 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2270 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002271
Andy Hungfbfc3952015-01-15 13:33:51 -08002272 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2273 // For best precision, we use float instead of the associated output
2274 // device format (typically PCM 16 bit).
2275
2276 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2277 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2278 mBufferSize = mFrameSize * mFrameCount;
2279
2280 // TODO: We currently use the associated output device channel mask and sample rate.
2281 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2282 // (if a valid mask) to avoid premature downmix.
2283 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2284 // instead of the output device sample rate to avoid loss of high frequency information.
2285 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2286 }
2287
Andy Hung09a50072014-02-27 14:30:47 -08002288 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002289 double multiplier = 1.0;
2290 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2291 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002292 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2293 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002294
Eric Laurent81784c32012-11-19 14:55:58 -08002295 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2296 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2297 maxNormalFrameCount = maxNormalFrameCount & ~15;
2298 if (maxNormalFrameCount < minNormalFrameCount) {
2299 maxNormalFrameCount = minNormalFrameCount;
2300 }
2301 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2302 if (multiplier <= 1.0) {
2303 multiplier = 1.0;
2304 } else if (multiplier <= 2.0) {
2305 if (2 * mFrameCount <= maxNormalFrameCount) {
2306 multiplier = 2.0;
2307 } else {
2308 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2309 }
2310 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002311 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002312 }
2313 }
2314 mNormalFrameCount = multiplier * mFrameCount;
2315 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002316 if (mType == MIXER || mType == DUPLICATING) {
2317 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2318 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002319 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002320 mNormalFrameCount);
2321
Andy Hung08fb1742015-05-31 23:22:10 -07002322 // Check if we want to throttle the processing to no more than 2x normal rate
2323 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002324 mThreadThrottleTimeMs = 0;
2325 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002326 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2327
Andy Hung010a1a12014-03-13 13:57:33 -07002328 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2329 // Originally this was int16_t[] array, need to remove legacy implications.
2330 free(mSinkBuffer);
2331 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002332 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2333 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2334 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002335 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002336
Andy Hung69aed5f2014-02-25 17:24:40 -08002337 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2338 // drives the output.
2339 free(mMixerBuffer);
2340 mMixerBuffer = NULL;
2341 if (mMixerBufferEnabled) {
2342 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2343 mMixerBufferSize = mNormalFrameCount * mChannelCount
2344 * audio_bytes_per_sample(mMixerBufferFormat);
2345 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2346 }
Andy Hung98ef9782014-03-04 14:46:50 -08002347 free(mEffectBuffer);
2348 mEffectBuffer = NULL;
2349 if (mEffectBufferEnabled) {
2350 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2351 mEffectBufferSize = mNormalFrameCount * mChannelCount
2352 * audio_bytes_per_sample(mEffectBufferFormat);
2353 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2354 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002355
Eric Laurent81784c32012-11-19 14:55:58 -08002356 // force reconfiguration of effect chains and engines to take new buffer size and audio
2357 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002358 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002359 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2360 // matter.
2361 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2362 Vector< sp<EffectChain> > effectChains = mEffectChains;
2363 for (size_t i = 0; i < effectChains.size(); i ++) {
2364 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2365 }
2366}
2367
2368
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002369status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002370{
2371 if (halFrames == NULL || dspFrames == NULL) {
2372 return BAD_VALUE;
2373 }
2374 Mutex::Autolock _l(mLock);
2375 if (initCheck() != NO_ERROR) {
2376 return INVALID_OPERATION;
2377 }
Andy Hung818e7a32016-02-16 18:08:07 -08002378 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002379 *halFrames = framesWritten;
2380
2381 if (isSuspended()) {
2382 // return an estimation of rendered frames when the output is suspended
2383 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002384 *dspFrames = (uint32_t)
2385 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002386 return NO_ERROR;
2387 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002388 status_t status;
2389 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002390 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002391 *dspFrames = (size_t)frames;
2392 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002393 }
2394}
2395
Eric Laurent4c415062016-06-17 16:14:16 -07002396// hasAudioSession_l() must be called with ThreadBase::mLock held
2397uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002398{
Eric Laurent81784c32012-11-19 14:55:58 -08002399 uint32_t result = 0;
2400 if (getEffectChain_l(sessionId) != 0) {
2401 result = EFFECT_SESSION;
2402 }
2403
2404 for (size_t i = 0; i < mTracks.size(); ++i) {
2405 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002406 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002407 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002408 if (track->isFastTrack()) {
2409 result |= FAST_SESSION;
2410 }
Eric Laurent81784c32012-11-19 14:55:58 -08002411 break;
2412 }
2413 }
2414
2415 return result;
2416}
2417
Glenn Kastend848eb42016-03-08 13:42:11 -08002418uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002419{
2420 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2421 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2422 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2423 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2424 }
2425 for (size_t i = 0; i < mTracks.size(); i++) {
2426 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002427 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002428 return AudioSystem::getStrategyForStream(track->streamType());
2429 }
2430 }
2431 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2432}
2433
2434
Phil Burk062e67a2015-02-11 13:40:50 -08002435AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002436{
2437 Mutex::Autolock _l(mLock);
2438 return mOutput;
2439}
2440
Phil Burk062e67a2015-02-11 13:40:50 -08002441AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002442{
2443 Mutex::Autolock _l(mLock);
2444 AudioStreamOut *output = mOutput;
2445 mOutput = NULL;
2446 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2447 // must push a NULL and wait for ack
2448 mOutputSink.clear();
2449 mPipeSink.clear();
2450 mNormalSink.clear();
2451 return output;
2452}
2453
2454// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002455sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002456{
2457 if (mOutput == NULL) {
2458 return NULL;
2459 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002460 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002461}
2462
2463uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2464{
2465 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2466}
2467
2468status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2469{
2470 if (!isValidSyncEvent(event)) {
2471 return BAD_VALUE;
2472 }
2473
2474 Mutex::Autolock _l(mLock);
2475
2476 for (size_t i = 0; i < mTracks.size(); ++i) {
2477 sp<Track> track = mTracks[i];
2478 if (event->triggerSession() == track->sessionId()) {
2479 (void) track->setSyncEvent(event);
2480 return NO_ERROR;
2481 }
2482 }
2483
2484 return NAME_NOT_FOUND;
2485}
2486
2487bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2488{
2489 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2490}
2491
2492void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2493 const Vector< sp<Track> >& tracksToRemove)
2494{
2495 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002496 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002497 for (size_t i = 0 ; i < count ; i++) {
2498 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002499 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002500 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002501 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002502#ifdef ADD_BATTERY_DATA
2503 // to track the speaker usage
2504 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2505#endif
2506 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002507 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002508 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002509 }
Eric Laurent81784c32012-11-19 14:55:58 -08002510 }
2511 }
2512 }
Eric Laurent81784c32012-11-19 14:55:58 -08002513}
2514
2515void AudioFlinger::PlaybackThread::checkSilentMode_l()
2516{
2517 if (!mMasterMute) {
2518 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002519 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2520 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2521 return;
2522 }
Eric Laurent81784c32012-11-19 14:55:58 -08002523 if (property_get("ro.audio.silent", value, "0") > 0) {
2524 char *endptr;
2525 unsigned long ul = strtoul(value, &endptr, 0);
2526 if (*endptr == '\0' && ul != 0) {
2527 ALOGD("Silence is golden");
2528 // The setprop command will not allow a property to be changed after
2529 // the first time it is set, so we don't have to worry about un-muting.
2530 setMasterMute_l(true);
2531 }
2532 }
2533 }
2534}
2535
2536// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002537ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002538{
Eric Laurent81784c32012-11-19 14:55:58 -08002539 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002540 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002541 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002542
2543 // If an NBAIO sink is present, use it to write the normal mixer's submix
2544 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002545
Andy Hung010a1a12014-03-13 13:57:33 -07002546 const size_t count = mBytesRemaining / mFrameSize;
2547
Simon Wilson2d590962012-11-29 15:18:50 -08002548 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002549 // update the setpoint when AudioFlinger::mScreenState changes
2550 uint32_t screenState = AudioFlinger::mScreenState;
2551 if (screenState != mScreenState) {
2552 mScreenState = screenState;
2553 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2554 if (pipe != NULL) {
2555 pipe->setAvgFrames((mScreenState & 1) ?
2556 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2557 }
2558 }
Andy Hung010a1a12014-03-13 13:57:33 -07002559 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002560 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002561 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002562 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002563 } else {
2564 bytesWritten = framesWritten;
2565 }
2566 // otherwise use the HAL / AudioStreamOut directly
2567 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002568 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002569
Eric Laurentbfb1b832013-01-07 09:53:42 -08002570 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002571 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2572 mWriteAckSequence += 2;
2573 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002575 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002576 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002577 // FIXME We should have an implementation of timestamps for direct output threads.
2578 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002579 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002580
Eric Laurentbfb1b832013-01-07 09:53:42 -08002581 if (mUseAsyncWrite &&
2582 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2583 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002584 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002586 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002587 }
Eric Laurent81784c32012-11-19 14:55:58 -08002588 }
2589
Eric Laurent81784c32012-11-19 14:55:58 -08002590 mNumWrites++;
2591 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002592 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002593 return bytesWritten;
2594}
2595
2596void AudioFlinger::PlaybackThread::threadLoop_drain()
2597{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002598 bool supportsDrain = false;
2599 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002600 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2601 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002602 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2603 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002604 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002605 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002606 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002607 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002608 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002609 }
2610}
2611
2612void AudioFlinger::PlaybackThread::threadLoop_exit()
2613{
Eric Laurent275e8e92014-11-30 15:14:47 -08002614 {
2615 Mutex::Autolock _l(mLock);
2616 for (size_t i = 0; i < mTracks.size(); i++) {
2617 sp<Track> track = mTracks[i];
2618 track->invalidate();
2619 }
2620 }
Eric Laurent81784c32012-11-19 14:55:58 -08002621}
2622
2623/*
2624The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002625 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002626 - mActiveSleepTimeUs from activeSleepTimeUs()
2627 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002628 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2629 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002630 - maxPeriod from frame count and sample rate (MIXER only)
2631
2632The parameters that affect these derived values are:
2633 - frame count
2634 - frame size
2635 - sample rate
2636 - device type: A2DP or not
2637 - device latency
2638 - format: PCM or not
2639 - active sleep time
2640 - idle sleep time
2641*/
2642
2643void AudioFlinger::PlaybackThread::cacheParameters_l()
2644{
Andy Hung25c2dac2014-02-27 14:56:00 -08002645 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002646 mActiveSleepTimeUs = activeSleepTimeUs();
2647 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002648
2649 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2650 // truncating audio when going to standby.
2651 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2652 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2653 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2654 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2655 }
2656 }
Eric Laurent81784c32012-11-19 14:55:58 -08002657}
2658
Eric Laurent13084622016-05-17 10:51:49 -07002659bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002660{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002661 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002662 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002663 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002664 size_t size = mTracks.size();
2665 for (size_t i = 0; i < size; i++) {
2666 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002667 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002668 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002669 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002670 }
2671 }
Eric Laurent13084622016-05-17 10:51:49 -07002672 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002673}
2674
Haynes Mathew George05317d22016-05-03 16:34:26 -07002675void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2676{
2677 Mutex::Autolock _l(mLock);
2678 invalidateTracks_l(streamType);
2679}
2680
Eric Laurent81784c32012-11-19 14:55:58 -08002681status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2682{
Glenn Kastend848eb42016-03-08 13:42:11 -08002683 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002684 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2685 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002686 bool ownsBuffer = false;
2687
2688 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002689 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002690 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002691 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002692 if (mType != DIRECT) {
2693 size_t numSamples = mNormalFrameCount * mChannelCount;
2694 buffer = new int16_t[numSamples];
2695 memset(buffer, 0, numSamples * sizeof(int16_t));
2696 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2697 ownsBuffer = true;
2698 }
2699
2700 // Attach all tracks with same session ID to this chain.
2701 for (size_t i = 0; i < mTracks.size(); ++i) {
2702 sp<Track> track = mTracks[i];
2703 if (session == track->sessionId()) {
2704 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2705 buffer);
2706 track->setMainBuffer(buffer);
2707 chain->incTrackCnt();
2708 }
2709 }
2710
2711 // indicate all active tracks in the chain
Eric Laurent9cab7462016-11-10 13:05:20 -08002712 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2713 sp<Track> track = mActiveTracks[i].promote();
2714 if (track == 0) {
2715 continue;
2716 }
Eric Laurent81784c32012-11-19 14:55:58 -08002717 if (session == track->sessionId()) {
2718 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2719 chain->incActiveTrackCnt();
2720 }
2721 }
2722 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002723 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002724 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002725 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2726 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002727 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002728 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002729 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2730 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002731 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002732 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002733 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002734 // Effect chain for other sessions are inserted at beginning of effect
2735 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002736 // sessions is not important.
2737 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2738 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2739 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002740 size_t size = mEffectChains.size();
2741 size_t i = 0;
2742 for (i = 0; i < size; i++) {
2743 if (mEffectChains[i]->sessionId() < session) {
2744 break;
2745 }
2746 }
2747 mEffectChains.insertAt(chain, i);
2748 checkSuspendOnAddEffectChain_l(chain);
2749
2750 return NO_ERROR;
2751}
2752
2753size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2754{
Glenn Kastend848eb42016-03-08 13:42:11 -08002755 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002756
2757 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2758
2759 for (size_t i = 0; i < mEffectChains.size(); i++) {
2760 if (chain == mEffectChains[i]) {
2761 mEffectChains.removeAt(i);
2762 // detach all active tracks from the chain
Eric Laurent9cab7462016-11-10 13:05:20 -08002763 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2764 sp<Track> track = mActiveTracks[i].promote();
2765 if (track == 0) {
2766 continue;
2767 }
Eric Laurent81784c32012-11-19 14:55:58 -08002768 if (session == track->sessionId()) {
2769 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2770 chain.get(), session);
2771 chain->decActiveTrackCnt();
2772 }
2773 }
2774
2775 // detach all tracks with same session ID from this chain
2776 for (size_t i = 0; i < mTracks.size(); ++i) {
2777 sp<Track> track = mTracks[i];
2778 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002779 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002780 chain->decTrackCnt();
2781 }
2782 }
2783 break;
2784 }
2785 }
2786 return mEffectChains.size();
2787}
2788
2789status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002790 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002791{
2792 Mutex::Autolock _l(mLock);
2793 return attachAuxEffect_l(track, EffectId);
2794}
2795
2796status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002797 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002798{
2799 status_t status = NO_ERROR;
2800
2801 if (EffectId == 0) {
2802 track->setAuxBuffer(0, NULL);
2803 } else {
2804 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2805 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2806 if (effect != 0) {
2807 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2808 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2809 } else {
2810 status = INVALID_OPERATION;
2811 }
2812 } else {
2813 status = BAD_VALUE;
2814 }
2815 }
2816 return status;
2817}
2818
2819void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2820{
2821 for (size_t i = 0; i < mTracks.size(); ++i) {
2822 sp<Track> track = mTracks[i];
2823 if (track->auxEffectId() == effectId) {
2824 attachAuxEffect_l(track, 0);
2825 }
2826 }
2827}
2828
2829bool AudioFlinger::PlaybackThread::threadLoop()
2830{
2831 Vector< sp<Track> > tracksToRemove;
2832
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002833 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002834 nsecs_t lastWriteFinished = -1; // time last server write completed
2835 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002836
2837 // MIXER
2838 nsecs_t lastWarning = 0;
2839
2840 // DUPLICATING
2841 // FIXME could this be made local to while loop?
2842 writeFrames = 0;
2843
Eric Laurent9cab7462016-11-10 13:05:20 -08002844 int lastGeneration = 0;
2845
Eric Laurent81784c32012-11-19 14:55:58 -08002846 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002847 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002848
2849 if (mType == MIXER) {
2850 sleepTimeShift = 0;
2851 }
2852
2853 CpuStats cpuStats;
2854 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2855
2856 acquireWakeLock();
2857
Glenn Kasten9e58b552013-01-18 15:09:48 -08002858 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2859 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2860 // and then that string will be logged at the next convenient opportunity.
2861 const char *logString = NULL;
2862
Eric Laurent664539d2013-09-23 18:24:31 -07002863 checkSilentMode_l();
2864
Eric Laurent81784c32012-11-19 14:55:58 -08002865 while (!exitPending())
2866 {
2867 cpuStats.sample(myName);
2868
2869 Vector< sp<EffectChain> > effectChains;
2870
Eric Laurent81784c32012-11-19 14:55:58 -08002871 { // scope for mLock
2872
2873 Mutex::Autolock _l(mLock);
2874
Eric Laurent021cf962014-05-13 10:18:14 -07002875 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002876
Glenn Kasten9e58b552013-01-18 15:09:48 -08002877 if (logString != NULL) {
2878 mNBLogWriter->logTimestamp();
2879 mNBLogWriter->log(logString);
2880 logString = NULL;
2881 }
2882
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002883 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002884 // and associate with the sink frames written out. We need
2885 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002886 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002887 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002888 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002889 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002890 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002891 ExtendedTimestamp timestamp; // use private copy to fetch
2892 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002893
2894 // We keep track of the last valid kernel position in case we are in underrun
2895 // and the normal mixer period is the same as the fast mixer period, or there
2896 // is some error from the HAL.
2897 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2898 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2899 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2900 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2901 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2902
2903 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2904 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2905 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2906 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002907 }
2908
2909 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2910 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002911 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002912 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002913 }
2914
Andy Hung818e7a32016-02-16 18:08:07 -08002915 // copy over kernel info
2916 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07002917 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
2918 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08002919 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2920 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002921 }
2922 // mFramesWritten for non-offloaded tracks are contiguous
2923 // even after standby() is called. This is useful for the track frame
2924 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07002925 bool serverLocationUpdate = false;
2926 if (mFramesWritten != lastFramesWritten) {
2927 serverLocationUpdate = true;
2928 lastFramesWritten = mFramesWritten;
2929 }
2930 // Only update timestamps if there is a meaningful change.
2931 // Either the kernel timestamp must be valid or we have written something.
2932 if (kernelLocationUpdate || serverLocationUpdate) {
2933 if (serverLocationUpdate) {
2934 // use the time before we called the HAL write - it is a bit more accurate
2935 // to when the server last read data than the current time here.
2936 //
2937 // If we haven't written anything, mLastWriteTime will be -1
2938 // and we use systemTime().
2939 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2940 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
2941 ? systemTime() : mLastWriteTime;
2942 }
Eric Laurent9cab7462016-11-10 13:05:20 -08002943 const size_t size = mActiveTracks.size();
2944 for (size_t i = 0; i < size; ++i) {
2945 sp<Track> t = mActiveTracks[i].promote();
2946 if (t != 0 && !t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07002947 t->updateTrackFrameInfo(
2948 t->mAudioTrackServerProxy->framesReleased(),
2949 mFramesWritten,
2950 mTimestamp);
2951 }
Andy Hunge10393e2015-06-12 13:59:33 -07002952 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002953 }
2954
Eric Laurent81784c32012-11-19 14:55:58 -08002955 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956 if (mSignalPending) {
2957 // A signal was raised while we were unlocked
2958 mSignalPending = false;
2959 } else if (waitingAsyncCallback_l()) {
2960 if (exitPending()) {
2961 break;
2962 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002963 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07002964 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07002965 releaseWakeLock_l();
2966 released = true;
Eric Laurent9cab7462016-11-10 13:05:20 -08002967 mWakeLockUids.clear();
2968 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07002969 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002970 ALOGV("wait async completion");
2971 mWaitWorkCV.wait(mLock);
2972 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002973 if (released) {
2974 acquireWakeLock_l();
2975 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002976 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2977 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002978
2979 continue;
2980 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002981 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982 isSuspended()) {
2983 // put audio hardware into standby after short delay
2984 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002985
2986 threadLoop_standby();
2987
2988 mStandby = true;
2989 }
2990
2991 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2992 // we're about to wait, flush the binder command buffer
2993 IPCThreadState::self()->flushCommands();
2994
2995 clearOutputTracks();
2996
2997 if (exitPending()) {
2998 break;
2999 }
3000
3001 releaseWakeLock_l();
Eric Laurent9cab7462016-11-10 13:05:20 -08003002 mWakeLockUids.clear();
3003 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003004 // wait until we have something to do...
3005 ALOGV("%s going to sleep", myName.string());
3006 mWaitWorkCV.wait(mLock);
3007 ALOGV("%s waking up", myName.string());
3008 acquireWakeLock_l();
3009
3010 mMixerStatus = MIXER_IDLE;
3011 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3012 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003013 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003014 checkSilentMode_l();
3015
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003016 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3017 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003018 if (mType == MIXER) {
3019 sleepTimeShift = 0;
3020 }
3021
3022 continue;
3023 }
3024 }
Eric Laurent81784c32012-11-19 14:55:58 -08003025 // mMixerStatusIgnoringFastTracks is also updated internally
3026 mMixerStatus = prepareTracks_l(&tracksToRemove);
3027
Eric Laurent9cab7462016-11-10 13:05:20 -08003028 // compare with previously applied list
3029 if (lastGeneration != mActiveTracksGeneration) {
3030 // update wakelock
3031 updateWakeLockUids_l(mWakeLockUids);
3032 lastGeneration = mActiveTracksGeneration;
3033 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003034
Eric Laurent81784c32012-11-19 14:55:58 -08003035 // prevent any changes in effect chain list and in each effect chain
3036 // during mixing and effect process as the audio buffers could be deleted
3037 // or modified if an effect is created or deleted
3038 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003039 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003040
Eric Laurentbfb1b832013-01-07 09:53:42 -08003041 if (mBytesRemaining == 0) {
3042 mCurrentWriteLength = 0;
3043 if (mMixerStatus == MIXER_TRACKS_READY) {
3044 // threadLoop_mix() sets mCurrentWriteLength
3045 threadLoop_mix();
3046 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3047 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003048 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003049 // must be written to HAL
3050 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003051 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003052 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003053 }
3054 }
Andy Hung98ef9782014-03-04 14:46:50 -08003055 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003056 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003057 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3058 // or mSinkBuffer (if there are no effects).
3059 //
3060 // This is done pre-effects computation; if effects change to
3061 // support higher precision, this needs to move.
3062 //
3063 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003064 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003065 if (mMixerBufferValid) {
3066 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3067 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3068
Andy Hung2ddee192015-12-18 17:34:44 -08003069 // mono blend occurs for mixer threads only (not direct or offloaded)
3070 // and is handled here if we're going directly to the sink.
3071 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003072 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3073 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003074 }
3075
Andy Hung98ef9782014-03-04 14:46:50 -08003076 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3077 mNormalFrameCount * mChannelCount);
3078 }
3079
Eric Laurentbfb1b832013-01-07 09:53:42 -08003080 mBytesRemaining = mCurrentWriteLength;
3081 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003082 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3083 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3084 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3085 mBytesWritten += mBytesRemaining;
3086 mFramesWritten += framesRemaining;
3087 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003088 mBytesRemaining = 0;
3089 }
Eric Laurent81784c32012-11-19 14:55:58 -08003090
Eric Laurentbfb1b832013-01-07 09:53:42 -08003091 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003092 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003093 for (size_t i = 0; i < effectChains.size(); i ++) {
3094 effectChains[i]->process_l();
3095 }
Eric Laurent81784c32012-11-19 14:55:58 -08003096 }
3097 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003098 // Process effect chains for offloaded thread even if no audio
3099 // was read from audio track: process only updates effect state
3100 // and thus does have to be synchronized with audio writes but may have
3101 // to be called while waiting for async write callback
3102 if (mType == OFFLOAD) {
3103 for (size_t i = 0; i < effectChains.size(); i ++) {
3104 effectChains[i]->process_l();
3105 }
3106 }
Eric Laurent81784c32012-11-19 14:55:58 -08003107
Andy Hung98ef9782014-03-04 14:46:50 -08003108 // Only if the Effects buffer is enabled and there is data in the
3109 // Effects buffer (buffer valid), we need to
3110 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003111 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003112 if (mEffectBufferValid) {
3113 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003114
3115 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003116 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3117 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003118 }
3119
Andy Hung98ef9782014-03-04 14:46:50 -08003120 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3121 mNormalFrameCount * mChannelCount);
3122 }
3123
Eric Laurent81784c32012-11-19 14:55:58 -08003124 // enable changes in effect chain
3125 unlockEffectChains(effectChains);
3126
Eric Laurentbfb1b832013-01-07 09:53:42 -08003127 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003128 // mSleepTimeUs == 0 means we must write to audio hardware
3129 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003130 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003131 // We save lastWriteFinished here, as previousLastWriteFinished,
3132 // for throttling. On thread start, previousLastWriteFinished will be
3133 // set to -1, which properly results in no throttling after the first write.
3134 nsecs_t previousLastWriteFinished = lastWriteFinished;
3135 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003136 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003137 // FIXME rewrite to reduce number of system calls
3138 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003139 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003140 lastWriteFinished = systemTime();
3141 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003142 if (ret < 0) {
3143 mBytesRemaining = 0;
3144 } else {
3145 mBytesWritten += ret;
3146 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003147 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003148 }
3149 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3150 (mMixerStatus == MIXER_DRAIN_ALL)) {
3151 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003152 }
Andy Hung08fb1742015-05-31 23:22:10 -07003153 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003154 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003155 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003156 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003157 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003158 ATRACE_NAME("underrun");
3159 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003160 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003161 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003162 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003163 }
Andy Hung08fb1742015-05-31 23:22:10 -07003164
3165 if (mThreadThrottle
3166 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3167 && ret > 0) { // we wrote something
3168 // Limit MixerThread data processing to no more than twice the
3169 // expected processing rate.
3170 //
3171 // This helps prevent underruns with NuPlayer and other applications
3172 // which may set up buffers that are close to the minimum size, or use
3173 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3174 //
3175 // The throttle smooths out sudden large data drains from the device,
3176 // e.g. when it comes out of standby, which often causes problems with
3177 // (1) mixer threads without a fast mixer (which has its own warm-up)
3178 // (2) minimum buffer sized tracks (even if the track is full,
3179 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003180 //
3181 // Total time spent in last processing cycle equals time spent in
3182 // 1. threadLoop_write, as well as time spent in
3183 // 2. threadLoop_mix (significant for heavy mixing, especially
3184 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003185
Andy Hung69488c42016-05-16 18:43:33 -07003186 // it's OK if deltaMs is an overestimate.
3187 const int32_t deltaMs =
3188 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003189 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3190 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3191 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003192 // notify of throttle start on verbose log
3193 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3194 "mixer(%p) throttle begin:"
3195 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003196 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003197 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003198 // Throttle must be attributed to the previous mixer loop's write time
3199 // to allow back-to-back throttling.
3200 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003201 } else {
3202 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3203 if (diff > 0) {
3204 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003205 // but prevent spamming for bluetooth
3206 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3207 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003208 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3209 }
Andy Hung08fb1742015-05-31 23:22:10 -07003210 }
3211 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003212 }
Eric Laurent81784c32012-11-19 14:55:58 -08003213
Eric Laurentbfb1b832013-01-07 09:53:42 -08003214 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003215 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003216 Mutex::Autolock _l(mLock);
3217 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3218 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003219 }
Glenn Kastene7754022014-10-31 12:11:26 -07003220 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003221 }
Eric Laurent81784c32012-11-19 14:55:58 -08003222 }
3223
3224 // Finally let go of removed track(s), without the lock held
3225 // since we can't guarantee the destructors won't acquire that
3226 // same lock. This will also mutate and push a new fast mixer state.
3227 threadLoop_removeTracks(tracksToRemove);
3228 tracksToRemove.clear();
3229
3230 // FIXME I don't understand the need for this here;
3231 // it was in the original code but maybe the
3232 // assignment in saveOutputTracks() makes this unnecessary?
3233 clearOutputTracks();
3234
3235 // Effect chains will be actually deleted here if they were removed from
3236 // mEffectChains list during mixing or effects processing
3237 effectChains.clear();
3238
3239 // FIXME Note that the above .clear() is no longer necessary since effectChains
3240 // is now local to this block, but will keep it for now (at least until merge done).
3241 }
3242
Eric Laurentbfb1b832013-01-07 09:53:42 -08003243 threadLoop_exit();
3244
Eric Laurentcf817a22014-08-04 20:36:31 -07003245 if (!mStandby) {
3246 threadLoop_standby();
3247 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003248 }
3249
3250 releaseWakeLock();
Eric Laurent9cab7462016-11-10 13:05:20 -08003251 mWakeLockUids.clear();
3252 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003253
3254 ALOGV("Thread %p type %d exiting", this, mType);
3255 return false;
3256}
3257
Eric Laurentbfb1b832013-01-07 09:53:42 -08003258// removeTracks_l() must be called with ThreadBase::mLock held
3259void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3260{
3261 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003262 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003263 for (size_t i=0 ; i<count ; i++) {
3264 const sp<Track>& track = tracksToRemove.itemAt(i);
3265 mActiveTracks.remove(track);
Eric Laurent9cab7462016-11-10 13:05:20 -08003266 mWakeLockUids.remove(track->uid());
3267 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003268 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3269 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3270 if (chain != 0) {
3271 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3272 track->sessionId());
3273 chain->decActiveTrackCnt();
3274 }
3275 if (track->isTerminated()) {
3276 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003277 } else { // inactive but not terminated
3278 char buffer[256];
3279 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3280 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003281 }
3282 }
3283 }
3284
3285}
Eric Laurent81784c32012-11-19 14:55:58 -08003286
Eric Laurentaccc1472013-09-20 09:36:34 -07003287status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3288{
3289 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003290 ExtendedTimestamp ets;
3291 status_t status = mNormalSink->getTimestamp(ets);
3292 if (status == NO_ERROR) {
3293 status = ets.getBestTimestamp(&timestamp);
3294 }
3295 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003296 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003297 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003298 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003299 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003300 timestamp.mPosition = (uint32_t)position64;
3301 return NO_ERROR;
3302 }
3303 }
3304 return INVALID_OPERATION;
3305}
Eric Laurent1c333e22014-05-20 10:48:17 -07003306
Eric Laurent054d9d32015-04-24 08:48:48 -07003307status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3308 audio_patch_handle_t *handle)
3309{
Andy Hungf60abce2016-08-26 11:37:54 -07003310 status_t status;
3311 if (property_get_bool("af.patch_park", false /* default_value */)) {
3312 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3313 // or if HAL does not properly lock against access.
3314 AutoPark<FastMixer> park(mFastMixer);
3315 status = PlaybackThread::createAudioPatch_l(patch, handle);
3316 } else {
3317 status = PlaybackThread::createAudioPatch_l(patch, handle);
3318 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003319 return status;
3320}
3321
Eric Laurent1c333e22014-05-20 10:48:17 -07003322status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3323 audio_patch_handle_t *handle)
3324{
3325 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003326
3327 // store new device and send to effects
3328 audio_devices_t type = AUDIO_DEVICE_NONE;
3329 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3330 type |= patch->sinks[i].ext.device.type;
3331 }
3332
3333#ifdef ADD_BATTERY_DATA
3334 // when changing the audio output device, call addBatteryData to notify
3335 // the change
3336 if (mOutDevice != type) {
3337 uint32_t params = 0;
3338 // check whether speaker is on
3339 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3340 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003341 }
3342
Eric Laurent054d9d32015-04-24 08:48:48 -07003343 audio_devices_t deviceWithoutSpeaker
3344 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3345 // check if any other device (except speaker) is on
3346 if (type & deviceWithoutSpeaker) {
3347 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3348 }
3349
3350 if (params != 0) {
3351 addBatteryData(params);
3352 }
3353 }
3354#endif
3355
3356 for (size_t i = 0; i < mEffectChains.size(); i++) {
3357 mEffectChains[i]->setDevice_l(type);
3358 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003359
3360 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3361 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3362 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003363 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003364 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003365
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003366 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003367 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3368 status = hwDevice->createAudioPatch(patch->num_sources,
3369 patch->sources,
3370 patch->num_sinks,
3371 patch->sinks,
3372 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003373 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003374 char *address;
3375 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3376 //FIXME: we only support address on first sink with HAL version < 3.0
3377 address = audio_device_address_to_parameter(
3378 patch->sinks[0].ext.device.type,
3379 patch->sinks[0].ext.device.address);
3380 } else {
3381 address = (char *)calloc(1, 1);
3382 }
3383 AudioParameter param = AudioParameter(String8(address));
3384 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003385 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003386 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003387 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003388 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003389 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003390 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003391 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3392 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003393 return status;
3394}
3395
Eric Laurent054d9d32015-04-24 08:48:48 -07003396status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3397{
Andy Hungf60abce2016-08-26 11:37:54 -07003398 status_t status;
3399 if (property_get_bool("af.patch_park", false /* default_value */)) {
3400 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3401 // or if HAL does not properly lock against access.
3402 AutoPark<FastMixer> park(mFastMixer);
3403 status = PlaybackThread::releaseAudioPatch_l(handle);
3404 } else {
3405 status = PlaybackThread::releaseAudioPatch_l(handle);
3406 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003407 return status;
3408}
3409
Eric Laurent1c333e22014-05-20 10:48:17 -07003410status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3411{
3412 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003413
3414 mOutDevice = AUDIO_DEVICE_NONE;
3415
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003416 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003417 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3418 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003419 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003420 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003421 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003422 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003423 }
3424 return status;
3425}
3426
Eric Laurent83b88082014-06-20 18:31:16 -07003427void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3428{
3429 Mutex::Autolock _l(mLock);
3430 mTracks.add(track);
3431}
3432
3433void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3434{
3435 Mutex::Autolock _l(mLock);
3436 destroyTrack_l(track);
3437}
3438
3439void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3440{
3441 ThreadBase::getAudioPortConfig(config);
3442 config->role = AUDIO_PORT_ROLE_SOURCE;
3443 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3444 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3445}
3446
Eric Laurent81784c32012-11-19 14:55:58 -08003447// ----------------------------------------------------------------------------
3448
3449AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003450 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3451 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003452 // mAudioMixer below
3453 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003454 mFastMixerFutex(0),
3455 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003456 // mOutputSink below
3457 // mPipeSink below
3458 // mNormalSink below
3459{
3460 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003461 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3462 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003463 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3464 mNormalFrameCount);
3465 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3466
Andy Hungfbfc3952015-01-15 13:33:51 -08003467 if (type == DUPLICATING) {
3468 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3469 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3470 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3471 return;
3472 }
Eric Laurent81784c32012-11-19 14:55:58 -08003473 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003474 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003475 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003476 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003477#if !LOG_NDEBUG
3478 ssize_t index =
3479#else
3480 (void)
3481#endif
3482 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003483 ALOG_ASSERT(index == 0);
3484
3485 // initialize fast mixer depending on configuration
3486 bool initFastMixer;
3487 switch (kUseFastMixer) {
3488 case FastMixer_Never:
3489 initFastMixer = false;
3490 break;
3491 case FastMixer_Always:
3492 initFastMixer = true;
3493 break;
3494 case FastMixer_Static:
3495 case FastMixer_Dynamic:
3496 initFastMixer = mFrameCount < mNormalFrameCount;
3497 break;
3498 }
3499 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003500 audio_format_t fastMixerFormat;
3501 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3502 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3503 } else {
3504 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3505 }
3506 if (mFormat != fastMixerFormat) {
3507 // change our Sink format to accept our intermediate precision
3508 mFormat = fastMixerFormat;
3509 free(mSinkBuffer);
3510 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3511 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3512 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3513 }
Eric Laurent81784c32012-11-19 14:55:58 -08003514
3515 // create a MonoPipe to connect our submix to FastMixer
3516 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003517#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003518 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003519#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003520 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003521 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003522 format.mFormat = fastMixerFormat;
3523 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3524
Eric Laurent81784c32012-11-19 14:55:58 -08003525 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3526 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3527 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3528 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3529 const NBAIO_Format offers[1] = {format};
3530 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003531#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003532 ssize_t index =
3533#else
3534 (void)
3535#endif
3536 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003537 ALOG_ASSERT(index == 0);
3538 monoPipe->setAvgFrames((mScreenState & 1) ?
3539 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3540 mPipeSink = monoPipe;
3541
Glenn Kasten46909e72013-02-26 09:20:22 -08003542#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003543 if (mTeeSinkOutputEnabled) {
3544 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003545 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3546 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003547 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003548 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003549 ALOG_ASSERT(index == 0);
3550 mTeeSink = teeSink;
3551 PipeReader *teeSource = new PipeReader(*teeSink);
3552 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003553 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003554 ALOG_ASSERT(index == 0);
3555 mTeeSource = teeSource;
3556 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003557#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003558
3559 // create fast mixer and configure it initially with just one fast track for our submix
3560 mFastMixer = new FastMixer();
3561 FastMixerStateQueue *sq = mFastMixer->sq();
3562#ifdef STATE_QUEUE_DUMP
3563 sq->setObserverDump(&mStateQueueObserverDump);
3564 sq->setMutatorDump(&mStateQueueMutatorDump);
3565#endif
3566 FastMixerState *state = sq->begin();
3567 FastTrack *fastTrack = &state->mFastTracks[0];
3568 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3569 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3570 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003571 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3572 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003573 fastTrack->mGeneration++;
3574 state->mFastTracksGen++;
3575 state->mTrackMask = 1;
3576 // fast mixer will use the HAL output sink
3577 state->mOutputSink = mOutputSink.get();
3578 state->mOutputSinkGen++;
3579 state->mFrameCount = mFrameCount;
3580 state->mCommand = FastMixerState::COLD_IDLE;
3581 // already done in constructor initialization list
3582 //mFastMixerFutex = 0;
3583 state->mColdFutexAddr = &mFastMixerFutex;
3584 state->mColdGen++;
3585 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003586#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003587 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003588#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003589 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3590 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003591 sq->end();
3592 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3593
3594 // start the fast mixer
3595 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3596 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003597 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003598
3599#ifdef AUDIO_WATCHDOG
3600 // create and start the watchdog
3601 mAudioWatchdog = new AudioWatchdog();
3602 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3603 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3604 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003605 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003606#endif
3607
Eric Laurent81784c32012-11-19 14:55:58 -08003608 }
3609
3610 switch (kUseFastMixer) {
3611 case FastMixer_Never:
3612 case FastMixer_Dynamic:
3613 mNormalSink = mOutputSink;
3614 break;
3615 case FastMixer_Always:
3616 mNormalSink = mPipeSink;
3617 break;
3618 case FastMixer_Static:
3619 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3620 break;
3621 }
3622}
3623
3624AudioFlinger::MixerThread::~MixerThread()
3625{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003626 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003627 FastMixerStateQueue *sq = mFastMixer->sq();
3628 FastMixerState *state = sq->begin();
3629 if (state->mCommand == FastMixerState::COLD_IDLE) {
3630 int32_t old = android_atomic_inc(&mFastMixerFutex);
3631 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003632 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003633 }
3634 }
3635 state->mCommand = FastMixerState::EXIT;
3636 sq->end();
3637 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3638 mFastMixer->join();
3639 // Though the fast mixer thread has exited, it's state queue is still valid.
3640 // We'll use that extract the final state which contains one remaining fast track
3641 // corresponding to our sub-mix.
3642 state = sq->begin();
3643 ALOG_ASSERT(state->mTrackMask == 1);
3644 FastTrack *fastTrack = &state->mFastTracks[0];
3645 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3646 delete fastTrack->mBufferProvider;
3647 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003648 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003649#ifdef AUDIO_WATCHDOG
3650 if (mAudioWatchdog != 0) {
3651 mAudioWatchdog->requestExit();
3652 mAudioWatchdog->requestExitAndWait();
3653 mAudioWatchdog.clear();
3654 }
3655#endif
3656 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003657 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003658 delete mAudioMixer;
3659}
3660
3661
3662uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3663{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003664 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003665 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3666 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3667 }
3668 return latency;
3669}
3670
3671
3672void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3673{
3674 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3675}
3676
Eric Laurentbfb1b832013-01-07 09:53:42 -08003677ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003678{
3679 // FIXME we should only do one push per cycle; confirm this is true
3680 // Start the fast mixer if it's not already running
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::MIX_WRITE &&
3685 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3686 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003687
3688 // FIXME workaround for first HAL write being CPU bound on some devices
3689 ATRACE_BEGIN("write");
3690 mOutput->write((char *)mSinkBuffer, 0);
3691 ATRACE_END();
3692
Eric Laurent81784c32012-11-19 14:55:58 -08003693 int32_t old = android_atomic_inc(&mFastMixerFutex);
3694 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003695 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003696 }
3697#ifdef AUDIO_WATCHDOG
3698 if (mAudioWatchdog != 0) {
3699 mAudioWatchdog->resume();
3700 }
3701#endif
3702 }
3703 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003704#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003705 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003706 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003707#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003708 sq->end();
3709 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3710 if (kUseFastMixer == FastMixer_Dynamic) {
3711 mNormalSink = mPipeSink;
3712 }
3713 } else {
3714 sq->end(false /*didModify*/);
3715 }
3716 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003717 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003718}
3719
3720void AudioFlinger::MixerThread::threadLoop_standby()
3721{
3722 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003723 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003724 FastMixerStateQueue *sq = mFastMixer->sq();
3725 FastMixerState *state = sq->begin();
3726 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003727 // Report any frames trapped in the Monopipe
3728 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3729 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3730 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3731 "monoPipeWritten:%lld monoPipeLeft:%lld",
3732 (long long)mFramesWritten, (long long)mSuspendedFrames,
3733 (long long)mPipeSink->framesWritten(), pipeFrames);
3734 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3735
Eric Laurent81784c32012-11-19 14:55:58 -08003736 state->mCommand = FastMixerState::COLD_IDLE;
3737 state->mColdFutexAddr = &mFastMixerFutex;
3738 state->mColdGen++;
3739 mFastMixerFutex = 0;
3740 sq->end();
3741 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3742 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3743 if (kUseFastMixer == FastMixer_Dynamic) {
3744 mNormalSink = mOutputSink;
3745 }
3746#ifdef AUDIO_WATCHDOG
3747 if (mAudioWatchdog != 0) {
3748 mAudioWatchdog->pause();
3749 }
3750#endif
3751 } else {
3752 sq->end(false /*didModify*/);
3753 }
3754 }
3755 PlaybackThread::threadLoop_standby();
3756}
3757
Eric Laurentbfb1b832013-01-07 09:53:42 -08003758bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3759{
3760 return false;
3761}
3762
3763bool AudioFlinger::PlaybackThread::shouldStandby_l()
3764{
3765 return !mStandby;
3766}
3767
3768bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3769{
3770 Mutex::Autolock _l(mLock);
3771 return waitingAsyncCallback_l();
3772}
3773
Eric Laurent81784c32012-11-19 14:55:58 -08003774// shared by MIXER and DIRECT, overridden by DUPLICATING
3775void AudioFlinger::PlaybackThread::threadLoop_standby()
3776{
3777 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003778 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003779 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003780 // discard any pending drain or write ack by incrementing sequence
3781 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3782 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003783 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003784 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3785 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003786 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003787 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003788}
3789
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003790void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3791{
3792 ALOGV("signal playback thread");
3793 broadcast_l();
3794}
3795
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003796void AudioFlinger::PlaybackThread::onAsyncError()
3797{
3798 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3799 invalidateTracks((audio_stream_type_t)i);
3800 }
3801}
3802
Eric Laurent81784c32012-11-19 14:55:58 -08003803void AudioFlinger::MixerThread::threadLoop_mix()
3804{
Eric Laurent81784c32012-11-19 14:55:58 -08003805 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003806 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003807 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003808 // increase sleep time progressively when application underrun condition clears.
3809 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3810 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3811 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003812 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003813 sleepTimeShift--;
3814 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003815 mSleepTimeUs = 0;
3816 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003817 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003818
Eric Laurent81784c32012-11-19 14:55:58 -08003819}
3820
3821void AudioFlinger::MixerThread::threadLoop_sleepTime()
3822{
3823 // If no tracks are ready, sleep once for the duration of an output
3824 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003825 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003826 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003827 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3828 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3829 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003830 }
3831 // reduce sleep time in case of consecutive application underruns to avoid
3832 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3833 // duration we would end up writing less data than needed by the audio HAL if
3834 // the condition persists.
3835 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3836 sleepTimeShift++;
3837 }
3838 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003839 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003840 }
3841 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003842 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3843 // before effects processing or output.
3844 if (mMixerBufferValid) {
3845 memset(mMixerBuffer, 0, mMixerBufferSize);
3846 } else {
3847 memset(mSinkBuffer, 0, mSinkBufferSize);
3848 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003849 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003850 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3851 "anticipated start");
3852 }
3853 // TODO add standby time extension fct of effect tail
3854}
3855
3856// prepareTracks_l() must be called with ThreadBase::mLock held
3857AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3858 Vector< sp<Track> > *tracksToRemove)
3859{
3860
3861 mixer_state mixerStatus = MIXER_IDLE;
3862 // find out which tracks need to be processed
3863 size_t count = mActiveTracks.size();
3864 size_t mixedTracks = 0;
3865 size_t tracksWithEffect = 0;
3866 // counts only _active_ fast tracks
3867 size_t fastTracks = 0;
3868 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3869
3870 float masterVolume = mMasterVolume;
3871 bool masterMute = mMasterMute;
3872
3873 if (masterMute) {
3874 masterVolume = 0;
3875 }
3876 // Delegate master volume control to effect in output mix effect chain if needed
3877 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3878 if (chain != 0) {
3879 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3880 chain->setVolume_l(&v, &v);
3881 masterVolume = (float)((v + (1 << 23)) >> 24);
3882 chain.clear();
3883 }
3884
3885 // prepare a new state to push
3886 FastMixerStateQueue *sq = NULL;
3887 FastMixerState *state = NULL;
3888 bool didModify = false;
3889 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003890 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003891 sq = mFastMixer->sq();
3892 state = sq->begin();
3893 }
3894
Andy Hung69aed5f2014-02-25 17:24:40 -08003895 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003896 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003897
Eric Laurent81784c32012-11-19 14:55:58 -08003898 for (size_t i=0 ; i<count ; i++) {
Eric Laurent9cab7462016-11-10 13:05:20 -08003899 const sp<Track> t = mActiveTracks[i].promote();
3900 if (t == 0) {
3901 continue;
3902 }
Eric Laurent81784c32012-11-19 14:55:58 -08003903
3904 // this const just means the local variable doesn't change
3905 Track* const track = t.get();
3906
3907 // process fast tracks
3908 if (track->isFastTrack()) {
3909
3910 // It's theoretically possible (though unlikely) for a fast track to be created
3911 // and then removed within the same normal mix cycle. This is not a problem, as
3912 // the track never becomes active so it's fast mixer slot is never touched.
3913 // The converse, of removing an (active) track and then creating a new track
3914 // at the identical fast mixer slot within the same normal mix cycle,
3915 // is impossible because the slot isn't marked available until the end of each cycle.
3916 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003917 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003918 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3919 FastTrack *fastTrack = &state->mFastTracks[j];
3920
3921 // Determine whether the track is currently in underrun condition,
3922 // and whether it had a recent underrun.
3923 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3924 FastTrackUnderruns underruns = ftDump->mUnderruns;
3925 uint32_t recentFull = (underruns.mBitFields.mFull -
3926 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3927 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3928 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3929 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3930 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3931 uint32_t recentUnderruns = recentPartial + recentEmpty;
3932 track->mObservedUnderruns = underruns;
3933 // don't count underruns that occur while stopping or pausing
3934 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003935 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3936 recentUnderruns > 0) {
3937 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3938 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003939 } else {
3940 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003941 }
3942
3943 // This is similar to the state machine for normal tracks,
3944 // with a few modifications for fast tracks.
3945 bool isActive = true;
3946 switch (track->mState) {
3947 case TrackBase::STOPPING_1:
3948 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003949 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003950 track->mState = TrackBase::STOPPING_2;
3951 }
3952 break;
3953 case TrackBase::PAUSING:
3954 // ramp down is not yet implemented
3955 track->setPaused();
3956 break;
3957 case TrackBase::RESUMING:
3958 // ramp up is not yet implemented
3959 track->mState = TrackBase::ACTIVE;
3960 break;
3961 case TrackBase::ACTIVE:
3962 if (recentFull > 0 || recentPartial > 0) {
3963 // track has provided at least some frames recently: reset retry count
3964 track->mRetryCount = kMaxTrackRetries;
3965 }
3966 if (recentUnderruns == 0) {
3967 // no recent underruns: stay active
3968 break;
3969 }
3970 // there has recently been an underrun of some kind
3971 if (track->sharedBuffer() == 0) {
3972 // were any of the recent underruns "empty" (no frames available)?
3973 if (recentEmpty == 0) {
3974 // no, then ignore the partial underruns as they are allowed indefinitely
3975 break;
3976 }
3977 // there has recently been an "empty" underrun: decrement the retry counter
3978 if (--(track->mRetryCount) > 0) {
3979 break;
3980 }
3981 // indicate to client process that the track was disabled because of underrun;
3982 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003983 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003984 // remove from active list, but state remains ACTIVE [confusing but true]
3985 isActive = false;
3986 break;
3987 }
3988 // fall through
3989 case TrackBase::STOPPING_2:
3990 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003991 case TrackBase::STOPPED:
3992 case TrackBase::FLUSHED: // flush() while active
3993 // Check for presentation complete if track is inactive
3994 // We have consumed all the buffers of this track.
3995 // This would be incomplete if we auto-paused on underrun
3996 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003997 uint32_t latency = 0;
3998 status_t result = mOutput->stream->getLatency(&latency);
3999 ALOGE_IF(result != OK,
4000 "Error when retrieving output stream latency: %d", result);
4001 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004002 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004003 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4004 // track stays in active list until presentation is complete
4005 break;
4006 }
4007 }
4008 if (track->isStopping_2()) {
4009 track->mState = TrackBase::STOPPED;
4010 }
4011 if (track->isStopped()) {
4012 // Can't reset directly, as fast mixer is still polling this track
4013 // track->reset();
4014 // So instead mark this track as needing to be reset after push with ack
4015 resetMask |= 1 << i;
4016 }
4017 isActive = false;
4018 break;
4019 case TrackBase::IDLE:
4020 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004021 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004022 }
4023
4024 if (isActive) {
4025 // was it previously inactive?
4026 if (!(state->mTrackMask & (1 << j))) {
4027 ExtendedAudioBufferProvider *eabp = track;
4028 VolumeProvider *vp = track;
4029 fastTrack->mBufferProvider = eabp;
4030 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004031 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004032 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004033 fastTrack->mGeneration++;
4034 state->mTrackMask |= 1 << j;
4035 didModify = true;
4036 // no acknowledgement required for newly active tracks
4037 }
4038 // cache the combined master volume and stream type volume for fast mixer; this
4039 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004040 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004041 ++fastTracks;
4042 } else {
4043 // was it previously active?
4044 if (state->mTrackMask & (1 << j)) {
4045 fastTrack->mBufferProvider = NULL;
4046 fastTrack->mGeneration++;
4047 state->mTrackMask &= ~(1 << j);
4048 didModify = true;
4049 // If any fast tracks were removed, we must wait for acknowledgement
4050 // because we're about to decrement the last sp<> on those tracks.
4051 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4052 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004053 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4054 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4055 j, track->mState, state->mTrackMask, recentUnderruns,
4056 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004057 }
4058 tracksToRemove->add(track);
4059 // Avoids a misleading display in dumpsys
4060 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4061 }
4062 continue;
4063 }
4064
4065 { // local variable scope to avoid goto warning
4066
4067 audio_track_cblk_t* cblk = track->cblk();
4068
4069 // The first time a track is added we wait
4070 // for all its buffers to be filled before processing it
4071 int name = track->name();
4072 // make sure that we have enough frames to mix one full buffer.
4073 // enforce this condition only once to enable draining the buffer in case the client
4074 // app does not call stop() and relies on underrun to stop:
4075 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4076 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004077 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004078 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004079 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004080
4081 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004082 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004083 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4084 // add frames already consumed but not yet released by the resampler
4085 // because mAudioTrackServerProxy->framesReady() will include these frames
4086 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4087
Eric Laurent81784c32012-11-19 14:55:58 -08004088 uint32_t minFrames = 1;
4089 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4090 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004091 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004092 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004093
4094 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004095 if (ATRACE_ENABLED()) {
4096 // I wish we had formatted trace names
4097 char traceName[16];
4098 strcpy(traceName, "nRdy");
4099 int name = track->name();
4100 if (AudioMixer::TRACK0 <= name &&
4101 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4102 name -= AudioMixer::TRACK0;
4103 traceName[4] = (name / 10) + '0';
4104 traceName[5] = (name % 10) + '0';
4105 } else {
4106 traceName[4] = '?';
4107 traceName[5] = '?';
4108 }
4109 traceName[6] = '\0';
4110 ATRACE_INT(traceName, framesReady);
4111 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004112 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004113 !track->isPaused() && !track->isTerminated())
4114 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004115 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004116
4117 mixedTracks++;
4118
Andy Hung69aed5f2014-02-25 17:24:40 -08004119 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4120 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004121 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004122 if (track->mainBuffer() != mSinkBuffer &&
4123 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004124 if (mEffectBufferEnabled) {
4125 mEffectBufferValid = true; // Later can set directly.
4126 }
Eric Laurent81784c32012-11-19 14:55:58 -08004127 chain = getEffectChain_l(track->sessionId());
4128 // Delegate volume control to effect in track effect chain if needed
4129 if (chain != 0) {
4130 tracksWithEffect++;
4131 } else {
4132 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4133 "session %d",
4134 name, track->sessionId());
4135 }
4136 }
4137
4138
4139 int param = AudioMixer::VOLUME;
4140 if (track->mFillingUpStatus == Track::FS_FILLED) {
4141 // no ramp for the first volume setting
4142 track->mFillingUpStatus = Track::FS_ACTIVE;
4143 if (track->mState == TrackBase::RESUMING) {
4144 track->mState = TrackBase::ACTIVE;
4145 param = AudioMixer::RAMP_VOLUME;
4146 }
4147 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004148 // FIXME should not make a decision based on mServer
4149 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004150 // If the track is stopped before the first frame was mixed,
4151 // do not apply ramp
4152 param = AudioMixer::RAMP_VOLUME;
4153 }
4154
4155 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004156 uint32_t vl, vr; // in U8.24 integer format
4157 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004158 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004159 vl = vr = 0;
4160 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004161 if (track->isPausing()) {
4162 track->setPaused();
4163 }
4164 } else {
4165
4166 // read original volumes with volume control
4167 float typeVolume = mStreamTypes[track->streamType()].volume;
4168 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004169 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004170 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004171 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4172 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004173 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004174 if (vlf > GAIN_FLOAT_UNITY) {
4175 ALOGV("Track left volume out of range: %.3g", vlf);
4176 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004177 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004178 if (vrf > GAIN_FLOAT_UNITY) {
4179 ALOGV("Track right volume out of range: %.3g", vrf);
4180 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004181 }
4182 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004183 vlf *= v;
4184 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004185 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004186 // then derive vl and vr as U8.24 versions for the effect chain
4187 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4188 vl = (uint32_t) (scaleto8_24 * vlf);
4189 vr = (uint32_t) (scaleto8_24 * vrf);
4190 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004191 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004192 // send level comes from shared memory and so may be corrupt
4193 if (sendLevel > MAX_GAIN_INT) {
4194 ALOGV("Track send level out of range: %04X", sendLevel);
4195 sendLevel = MAX_GAIN_INT;
4196 }
Andy Hung6be49402014-05-30 10:42:03 -07004197 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4198 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004199 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004200
Eric Laurent81784c32012-11-19 14:55:58 -08004201 // Delegate volume control to effect in track effect chain if needed
4202 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4203 // Do not ramp volume if volume is controlled by effect
4204 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004205 // Update remaining floating point volume levels
4206 vlf = (float)vl / (1 << 24);
4207 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004208 track->mHasVolumeController = true;
4209 } else {
4210 // force no volume ramp when volume controller was just disabled or removed
4211 // from effect chain to avoid volume spike
4212 if (track->mHasVolumeController) {
4213 param = AudioMixer::VOLUME;
4214 }
4215 track->mHasVolumeController = false;
4216 }
4217
Eric Laurent81784c32012-11-19 14:55:58 -08004218 // XXX: these things DON'T need to be done each time
4219 mAudioMixer->setBufferProvider(name, track);
4220 mAudioMixer->enable(name);
4221
Andy Hung6be49402014-05-30 10:42:03 -07004222 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4223 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4224 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004225 mAudioMixer->setParameter(
4226 name,
4227 AudioMixer::TRACK,
4228 AudioMixer::FORMAT, (void *)track->format());
4229 mAudioMixer->setParameter(
4230 name,
4231 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004232 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004233 mAudioMixer->setParameter(
4234 name,
4235 AudioMixer::TRACK,
4236 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004237 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004238 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004239 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004240 if (reqSampleRate == 0) {
4241 reqSampleRate = mSampleRate;
4242 } else if (reqSampleRate > maxSampleRate) {
4243 reqSampleRate = maxSampleRate;
4244 }
Eric Laurent81784c32012-11-19 14:55:58 -08004245 mAudioMixer->setParameter(
4246 name,
4247 AudioMixer::RESAMPLE,
4248 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004249 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004250
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004251 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004252 mAudioMixer->setParameter(
4253 name,
4254 AudioMixer::TIMESTRETCH,
4255 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004256 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004257
Andy Hung69aed5f2014-02-25 17:24:40 -08004258 /*
4259 * Select the appropriate output buffer for the track.
4260 *
Andy Hung98ef9782014-03-04 14:46:50 -08004261 * Tracks with effects go into their own effects chain buffer
4262 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004263 *
4264 * Other tracks can use mMixerBuffer for higher precision
4265 * channel accumulation. If this buffer is enabled
4266 * (mMixerBufferEnabled true), then selected tracks will accumulate
4267 * into it.
4268 *
4269 */
4270 if (mMixerBufferEnabled
4271 && (track->mainBuffer() == mSinkBuffer
4272 || track->mainBuffer() == mMixerBuffer)) {
4273 mAudioMixer->setParameter(
4274 name,
4275 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004276 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004277 mAudioMixer->setParameter(
4278 name,
4279 AudioMixer::TRACK,
4280 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4281 // TODO: override track->mainBuffer()?
4282 mMixerBufferValid = true;
4283 } else {
4284 mAudioMixer->setParameter(
4285 name,
4286 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004287 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004288 mAudioMixer->setParameter(
4289 name,
4290 AudioMixer::TRACK,
4291 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4292 }
Eric Laurent81784c32012-11-19 14:55:58 -08004293 mAudioMixer->setParameter(
4294 name,
4295 AudioMixer::TRACK,
4296 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4297
4298 // reset retry count
4299 track->mRetryCount = kMaxTrackRetries;
4300
4301 // If one track is ready, set the mixer ready if:
4302 // - the mixer was not ready during previous round OR
4303 // - no other track is not ready
4304 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4305 mixerStatus != MIXER_TRACKS_ENABLED) {
4306 mixerStatus = MIXER_TRACKS_READY;
4307 }
4308 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004309 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004310 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4311 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004312 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004313 } else {
4314 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004315 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004316
Eric Laurent81784c32012-11-19 14:55:58 -08004317 // clear effect chain input buffer if an active track underruns to avoid sending
4318 // previous audio buffer again to effects
4319 chain = getEffectChain_l(track->sessionId());
4320 if (chain != 0) {
4321 chain->clearInputBuffer();
4322 }
4323
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004324 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004325 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4326 track->isStopped() || track->isPaused()) {
4327 // We have consumed all the buffers of this track.
4328 // Remove it from the list of active tracks.
4329 // TODO: use actual buffer filling status instead of latency when available from
4330 // audio HAL
4331 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004332 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004333 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4334 if (track->isStopped()) {
4335 track->reset();
4336 }
4337 tracksToRemove->add(track);
4338 }
4339 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004340 // No buffers for this track. Give it a few chances to
4341 // fill a buffer, then remove it from active list.
4342 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004343 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004344 tracksToRemove->add(track);
4345 // indicate to client process that the track was disabled because of underrun;
4346 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004347 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004348 // If one track is not ready, mark the mixer also not ready if:
4349 // - the mixer was ready during previous round OR
4350 // - no other track is ready
4351 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4352 mixerStatus != MIXER_TRACKS_READY) {
4353 mixerStatus = MIXER_TRACKS_ENABLED;
4354 }
4355 }
4356 mAudioMixer->disable(name);
4357 }
4358
4359 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004360
4361 }
4362
4363 // Push the new FastMixer state if necessary
4364 bool pauseAudioWatchdog = false;
4365 if (didModify) {
4366 state->mFastTracksGen++;
4367 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4368 if (kUseFastMixer == FastMixer_Dynamic &&
4369 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4370 state->mCommand = FastMixerState::COLD_IDLE;
4371 state->mColdFutexAddr = &mFastMixerFutex;
4372 state->mColdGen++;
4373 mFastMixerFutex = 0;
4374 if (kUseFastMixer == FastMixer_Dynamic) {
4375 mNormalSink = mOutputSink;
4376 }
4377 // If we go into cold idle, need to wait for acknowledgement
4378 // so that fast mixer stops doing I/O.
4379 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4380 pauseAudioWatchdog = true;
4381 }
Eric Laurent81784c32012-11-19 14:55:58 -08004382 }
4383 if (sq != NULL) {
4384 sq->end(didModify);
4385 sq->push(block);
4386 }
4387#ifdef AUDIO_WATCHDOG
4388 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4389 mAudioWatchdog->pause();
4390 }
4391#endif
4392
4393 // Now perform the deferred reset on fast tracks that have stopped
4394 while (resetMask != 0) {
4395 size_t i = __builtin_ctz(resetMask);
4396 ALOG_ASSERT(i < count);
4397 resetMask &= ~(1 << i);
Eric Laurent9cab7462016-11-10 13:05:20 -08004398 sp<Track> t = mActiveTracks[i].promote();
4399 if (t == 0) {
4400 continue;
4401 }
4402 Track* track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004403 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4404 track->reset();
4405 }
4406
4407 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004408 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004409
Eric Laurent97d547d2014-09-02 14:45:53 -07004410 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4411 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004412 }
4413
4414 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004415 // as long as there are effects we should clear the effects buffer, to avoid
4416 // passing a non-clean buffer to the effect chain
4417 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004418 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004419 // sink or mix buffer must be cleared if all tracks are connected to an
4420 // effect chain as in this case the mixer will not write to the sink or mix buffer
4421 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004422 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4423 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004424 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004425 if (mMixerBufferValid) {
4426 memset(mMixerBuffer, 0, mMixerBufferSize);
4427 // TODO: In testing, mSinkBuffer below need not be cleared because
4428 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4429 // after mixing.
4430 //
4431 // To enforce this guarantee:
4432 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4433 // (mixedTracks == 0 && fastTracks > 0))
4434 // must imply MIXER_TRACKS_READY.
4435 // Later, we may clear buffers regardless, and skip much of this logic.
4436 }
Andy Hung98ef9782014-03-04 14:46:50 -08004437 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004438 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004439 }
4440
4441 // if any fast tracks, then status is ready
4442 mMixerStatusIgnoringFastTracks = mixerStatus;
4443 if (fastTracks > 0) {
4444 mixerStatus = MIXER_TRACKS_READY;
4445 }
4446 return mixerStatus;
4447}
4448
Eric Laurentad7dd962016-09-22 12:38:37 -07004449// trackCountForUid_l() must be called with ThreadBase::mLock held
4450uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4451{
4452 uint32_t trackCount = 0;
4453 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004454 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004455 trackCount++;
4456 }
4457 }
4458 return trackCount;
4459}
4460
Eric Laurent81784c32012-11-19 14:55:58 -08004461// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004462int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004463 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004464{
Eric Laurentad7dd962016-09-22 12:38:37 -07004465 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4466 return -1;
4467 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004468 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004469}
4470
4471// deleteTrackName_l() must be called with ThreadBase::mLock held
4472void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4473{
4474 ALOGV("remove track (%d) and delete from mixer", name);
4475 mAudioMixer->deleteTrackName(name);
4476}
4477
Eric Laurent10351942014-05-08 18:49:52 -07004478// checkForNewParameter_l() must be called with ThreadBase::mLock held
4479bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4480 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004481{
Eric Laurent81784c32012-11-19 14:55:58 -08004482 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004483 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004484
Eric Laurent10351942014-05-08 18:49:52 -07004485 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004486
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004487 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004488
Eric Laurent10351942014-05-08 18:49:52 -07004489 AudioParameter param = AudioParameter(keyValuePair);
4490 int value;
4491 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4492 reconfig = true;
4493 }
4494 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004495 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004496 status = BAD_VALUE;
4497 } else {
4498 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004499 reconfig = true;
4500 }
Eric Laurent10351942014-05-08 18:49:52 -07004501 }
4502 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004503 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004504 status = BAD_VALUE;
4505 } else {
4506 // no need to save value, since it's constant
4507 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004508 }
Eric Laurent10351942014-05-08 18:49:52 -07004509 }
4510 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4511 // do not accept frame count changes if tracks are open as the track buffer
4512 // size depends on frame count and correct behavior would not be guaranteed
4513 // if frame count is changed after track creation
4514 if (!mTracks.isEmpty()) {
4515 status = INVALID_OPERATION;
4516 } else {
4517 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004518 }
Eric Laurent10351942014-05-08 18:49:52 -07004519 }
4520 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004521#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004522 // when changing the audio output device, call addBatteryData to notify
4523 // the change
4524 if (mOutDevice != value) {
4525 uint32_t params = 0;
4526 // check whether speaker is on
4527 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4528 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004529 }
Eric Laurent10351942014-05-08 18:49:52 -07004530
4531 audio_devices_t deviceWithoutSpeaker
4532 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4533 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004534 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004535 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4536 }
4537
4538 if (params != 0) {
4539 addBatteryData(params);
4540 }
4541 }
Eric Laurent81784c32012-11-19 14:55:58 -08004542#endif
4543
Eric Laurent10351942014-05-08 18:49:52 -07004544 // forward device change to effects that have requested to be
4545 // aware of attached audio device.
4546 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004547 a2dpDeviceChanged =
4548 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004549 mOutDevice = value;
4550 for (size_t i = 0; i < mEffectChains.size(); i++) {
4551 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004552 }
4553 }
Eric Laurent10351942014-05-08 18:49:52 -07004554 }
Eric Laurent81784c32012-11-19 14:55:58 -08004555
Eric Laurent10351942014-05-08 18:49:52 -07004556 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004557 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004558 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004559 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004560 mStandby = true;
4561 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004562 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004563 }
Eric Laurent10351942014-05-08 18:49:52 -07004564 if (status == NO_ERROR && reconfig) {
4565 readOutputParameters_l();
4566 delete mAudioMixer;
4567 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4568 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004569 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004570 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004571 if (name < 0) {
4572 break;
4573 }
4574 mTracks[i]->mName = name;
4575 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004576 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004577 }
Eric Laurent81784c32012-11-19 14:55:58 -08004578 }
4579
Eric Laurent42537be2016-01-08 17:16:42 -08004580 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004581}
4582
4583
4584void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4585{
Eric Laurent81784c32012-11-19 14:55:58 -08004586 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004587 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004588 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004589 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004590
4591 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004592 // while we are dumping it. It may be inconsistent, but it won't mutate!
4593 // This is a large object so we place it on the heap.
4594 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4595 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4596 copy->dump(fd);
4597 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004598
4599#ifdef STATE_QUEUE_DUMP
4600 // Similar for state queue
4601 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4602 observerCopy.dump(fd);
4603 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4604 mutatorCopy.dump(fd);
4605#endif
4606
Glenn Kasten46909e72013-02-26 09:20:22 -08004607#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004608 // Write the tee output to a .wav file
4609 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004610#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004611
4612#ifdef AUDIO_WATCHDOG
4613 if (mAudioWatchdog != 0) {
4614 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4615 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4616 wdCopy.dump(fd);
4617 }
4618#endif
4619}
4620
4621uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4622{
4623 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4624}
4625
4626uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4627{
4628 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4629}
4630
4631void AudioFlinger::MixerThread::cacheParameters_l()
4632{
4633 PlaybackThread::cacheParameters_l();
4634
4635 // FIXME: Relaxed timing because of a certain device that can't meet latency
4636 // Should be reduced to 2x after the vendor fixes the driver issue
4637 // increase threshold again due to low power audio mode. The way this warning
4638 // threshold is calculated and its usefulness should be reconsidered anyway.
4639 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4640}
4641
4642// ----------------------------------------------------------------------------
4643
4644AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004645 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4646 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004647 // mLeftVolFloat, mRightVolFloat
4648{
4649}
4650
Eric Laurentbfb1b832013-01-07 09:53:42 -08004651AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4652 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004653 ThreadBase::type_t type, bool systemReady)
4654 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004655 // mLeftVolFloat, mRightVolFloat
4656{
4657}
4658
Eric Laurent81784c32012-11-19 14:55:58 -08004659AudioFlinger::DirectOutputThread::~DirectOutputThread()
4660{
4661}
4662
Eric Laurent5850c4c2016-11-10 13:04:31 -08004663void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004664{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004665 float left, right;
4666
4667 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4668 left = right = 0;
4669 } else {
4670 float typeVolume = mStreamTypes[track->streamType()].volume;
4671 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004672 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004673 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4674 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4675 if (left > GAIN_FLOAT_UNITY) {
4676 left = GAIN_FLOAT_UNITY;
4677 }
4678 left *= v;
4679 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4680 if (right > GAIN_FLOAT_UNITY) {
4681 right = GAIN_FLOAT_UNITY;
4682 }
4683 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004684 }
4685
4686 if (lastTrack) {
4687 if (left != mLeftVolFloat || right != mRightVolFloat) {
4688 mLeftVolFloat = left;
4689 mRightVolFloat = right;
4690
4691 // Convert volumes from float to 8.24
4692 uint32_t vl = (uint32_t)(left * (1 << 24));
4693 uint32_t vr = (uint32_t)(right * (1 << 24));
4694
4695 // Delegate volume control to effect in track effect chain if needed
4696 // only one effect chain can be present on DirectOutputThread, so if
4697 // there is one, the track is connected to it
4698 if (!mEffectChains.isEmpty()) {
4699 mEffectChains[0]->setVolume_l(&vl, &vr);
4700 left = (float)vl / (1 << 24);
4701 right = (float)vr / (1 << 24);
4702 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004703 status_t result = mOutput->stream->setVolume(left, right);
4704 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004705 }
4706 }
4707}
4708
Phil Burk43b4dcc2015-06-09 16:53:44 -07004709void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4710{
4711 sp<Track> previousTrack = mPreviousTrack.promote();
Eric Laurent9cab7462016-11-10 13:05:20 -08004712 sp<Track> latestTrack = mLatestActiveTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004713
Eric Laurent0f0631e2015-07-06 18:01:25 -07004714 if (previousTrack != 0 && latestTrack != 0) {
4715 if (mType == DIRECT) {
4716 if (previousTrack.get() != latestTrack.get()) {
4717 mFlushPending = true;
4718 }
4719 } else /* mType == OFFLOAD */ {
4720 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4721 mFlushPending = true;
4722 }
4723 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004724 }
4725 PlaybackThread::onAddNewTrack_l();
4726}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004727
Eric Laurent81784c32012-11-19 14:55:58 -08004728AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4729 Vector< sp<Track> > *tracksToRemove
4730)
4731{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004732 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004733 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004734 bool doHwPause = false;
4735 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004736
4737 // find out which tracks need to be processed
Eric Laurent9cab7462016-11-10 13:05:20 -08004738 for (size_t i = 0; i < count; i++) {
4739 sp<Track> t = mActiveTracks[i].promote();
4740 // The track died recently
4741 if (t == 0) {
4742 continue;
4743 }
4744
Eric Laurent5850c4c2016-11-10 13:04:31 -08004745 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004746 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004747 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004748 continue;
4749 }
4750
Eric Laurent5850c4c2016-11-10 13:04:31 -08004751 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004752#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004753 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004754#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004755 // Only consider last track started for volume and mixer state control.
4756 // In theory an older track could underrun and restart after the new one starts
4757 // but as we only care about the transition phase between two tracks on a
4758 // direct output, it is not a problem to ignore the underrun case.
Eric Laurent9cab7462016-11-10 13:05:20 -08004759 sp<Track> l = mLatestActiveTrack.promote();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004760 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004761
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004762 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004763 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004764 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004765 doHwPause = true;
4766 mHwPaused = true;
4767 }
4768 tracksToRemove->add(track);
4769 } else if (track->isFlushPending()) {
4770 track->flushAck();
4771 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004772 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004773 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004774 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004775 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004776 if (last) {
4777 mLeftVolFloat = mRightVolFloat = -1.0;
4778 if (mHwPaused) {
4779 doHwResume = true;
4780 mHwPaused = false;
4781 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004782 }
4783 }
4784
Eric Laurent81784c32012-11-19 14:55:58 -08004785 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004786 // for all its buffers to be filled before processing it.
4787 // Allow draining the buffer in case the client
4788 // app does not call stop() and relies on underrun to stop:
4789 // hence the test on (track->mRetryCount > 1).
4790 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004791 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004792 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004793 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004794 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004795 minFrames = mNormalFrameCount;
4796 } else {
4797 minFrames = 1;
4798 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004799
Eric Laurentab5cdba2014-06-09 17:22:27 -07004800 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4801 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004802 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004803 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004804
4805 if (track->mFillingUpStatus == Track::FS_FILLED) {
4806 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004807 if (last) {
4808 // make sure processVolume_l() will apply new volume even if 0
4809 mLeftVolFloat = mRightVolFloat = -1.0;
4810 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004811 if (!mHwSupportsPause) {
4812 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004813 }
4814 }
4815
4816 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004817 processVolume_l(track, last);
4818 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004819 sp<Track> previousTrack = mPreviousTrack.promote();
4820 if (previousTrack != 0) {
4821 if (track != previousTrack.get()) {
4822 // Flush any data still being written from last track
4823 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004824 // Invalidate previous track to force a seek when resuming.
4825 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004826 }
4827 }
4828 mPreviousTrack = track;
4829
Eric Laurentd595b7c2013-04-03 17:27:56 -07004830 // reset retry count
4831 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004832 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004833 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004834 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004835 doHwResume = true;
4836 mHwPaused = false;
4837 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004838 }
Eric Laurent81784c32012-11-19 14:55:58 -08004839 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004840 // clear effect chain input buffer if the last active track started underruns
4841 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004842 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004843 mEffectChains[0]->clearInputBuffer();
4844 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004845 if (track->isStopping_1()) {
4846 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004847 if (last && mHwPaused) {
4848 doHwResume = true;
4849 mHwPaused = false;
4850 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004851 }
4852 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4853 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004854 // We have consumed all the buffers of this track.
4855 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004856 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004857 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004858 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4859 } else {
4860 audioHALFrames = 0;
4861 }
4862
Andy Hung818e7a32016-02-16 18:08:07 -08004863 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004864 if (mStandby || !last ||
4865 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004866 if (track->isStopping_2()) {
4867 track->mState = TrackBase::STOPPED;
4868 }
Eric Laurent81784c32012-11-19 14:55:58 -08004869 if (track->isStopped()) {
4870 track->reset();
4871 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004872 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004873 }
4874 } else {
4875 // No buffers for this track. Give it a few chances to
4876 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004877 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004878 if (--(track->mRetryCount) <= 0) {
4879 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004880 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004881 // indicate to client process that the track was disabled because of underrun;
4882 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004883 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004884 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004885 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4886 "minFrames = %u, mFormat = %#x",
4887 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004888 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004889 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004890 doHwPause = true;
4891 mHwPaused = true;
4892 }
Eric Laurent81784c32012-11-19 14:55:58 -08004893 }
4894 }
4895 }
4896 }
4897
Eric Laurentd1f69b02014-12-15 14:33:13 -08004898 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004899 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004900 for (size_t i = 0; i < mTracks.size(); i++) {
4901 if (mTracks[i]->isFlushPending()) {
4902 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004903 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004904 }
4905 }
4906 }
4907
4908 // make sure the pause/flush/resume sequence is executed in the right order.
4909 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4910 // before flush and then resume HW. This can happen in case of pause/flush/resume
4911 // if resume is received before pause is executed.
4912 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004913 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004914 status_t result = mOutput->stream->pause();
4915 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004916 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004917 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004918 flushHw_l();
4919 }
4920 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004921 status_t result = mOutput->stream->resume();
4922 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004923 }
Eric Laurent81784c32012-11-19 14:55:58 -08004924 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004925 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004926
4927 return mixerStatus;
4928}
4929
4930void AudioFlinger::DirectOutputThread::threadLoop_mix()
4931{
Eric Laurent81784c32012-11-19 14:55:58 -08004932 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004933 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004934 // output audio to hardware
4935 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004936 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004937 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004938 status_t status = mActiveTrack->getNextBuffer(&buffer);
4939 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004940 // no need to pad with 0 for compressed audio
4941 if (audio_has_proportional_frames(mFormat)) {
4942 memset(curBuf, 0, frameCount * mFrameSize);
4943 }
Eric Laurent81784c32012-11-19 14:55:58 -08004944 break;
4945 }
4946 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4947 frameCount -= buffer.frameCount;
4948 curBuf += buffer.frameCount * mFrameSize;
4949 mActiveTrack->releaseBuffer(&buffer);
4950 }
Andy Hung2098f272014-02-27 14:00:06 -08004951 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004952 mSleepTimeUs = 0;
4953 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004954 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004955}
4956
4957void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4958{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004959 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004960 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004961 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004962 return;
4963 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004964 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004965 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07004966 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004967 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004968 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004969 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004970 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004971 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004972 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004973 }
4974}
4975
Eric Laurentd1f69b02014-12-15 14:33:13 -08004976void AudioFlinger::DirectOutputThread::threadLoop_exit()
4977{
4978 {
4979 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004980 for (size_t i = 0; i < mTracks.size(); i++) {
4981 if (mTracks[i]->isFlushPending()) {
4982 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004983 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004984 }
4985 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004986 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004987 flushHw_l();
4988 }
4989 }
4990 PlaybackThread::threadLoop_exit();
4991}
4992
4993// must be called with thread mutex locked
4994bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4995{
4996 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004997 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004998
vivek mehta9cd7ad12016-03-17 00:18:29 -07004999 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5000 return !mStandby;
5001 }
5002
Eric Laurentd1f69b02014-12-15 14:33:13 -08005003 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5004 // after a timeout and we will enter standby then.
5005 if (mTracks.size() > 0) {
5006 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005007 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5008 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005009 }
5010
Eric Laurent5cff4032015-05-26 13:49:58 -07005011 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005012}
5013
Eric Laurent81784c32012-11-19 14:55:58 -08005014// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005015int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005016 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005017{
Eric Laurentad7dd962016-09-22 12:38:37 -07005018 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5019 return -1;
5020 }
Eric Laurent81784c32012-11-19 14:55:58 -08005021 return 0;
5022}
5023
5024// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005025void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005026{
5027}
5028
Eric Laurent10351942014-05-08 18:49:52 -07005029// checkForNewParameter_l() must be called with ThreadBase::mLock held
5030bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5031 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005032{
5033 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005034 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005035
Eric Laurent10351942014-05-08 18:49:52 -07005036 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005037
Eric Laurent10351942014-05-08 18:49:52 -07005038 AudioParameter param = AudioParameter(keyValuePair);
5039 int value;
5040 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5041 // forward device change to effects that have requested to be
5042 // aware of attached audio device.
5043 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005044 a2dpDeviceChanged =
5045 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005046 mOutDevice = value;
5047 for (size_t i = 0; i < mEffectChains.size(); i++) {
5048 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005049 }
5050 }
Eric Laurent81784c32012-11-19 14:55:58 -08005051 }
Eric Laurent10351942014-05-08 18:49:52 -07005052 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5053 // do not accept frame count changes if tracks are open as the track buffer
5054 // size depends on frame count and correct behavior would not be garantied
5055 // if frame count is changed after track creation
5056 if (!mTracks.isEmpty()) {
5057 status = INVALID_OPERATION;
5058 } else {
5059 reconfig = true;
5060 }
5061 }
5062 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005063 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005064 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005065 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005066 mStandby = true;
5067 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005068 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005069 }
5070 if (status == NO_ERROR && reconfig) {
5071 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005072 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005073 }
5074 }
5075
Eric Laurent42537be2016-01-08 17:16:42 -08005076 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005077}
5078
5079uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5080{
5081 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005082 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005083 time = PlaybackThread::activeSleepTimeUs();
5084 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005085 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005086 }
5087 return time;
5088}
5089
5090uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5091{
5092 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005093 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005094 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5095 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005096 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005097 }
5098 return time;
5099}
5100
5101uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5102{
5103 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005104 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005105 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5106 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005107 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005108 }
5109 return time;
5110}
5111
5112void AudioFlinger::DirectOutputThread::cacheParameters_l()
5113{
5114 PlaybackThread::cacheParameters_l();
5115
5116 // use shorter standby delay as on normal output to release
5117 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005118 // no delay on outputs with HW A/V sync
5119 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005120 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005121 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005122 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005123 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005124 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005125 }
Eric Laurent81784c32012-11-19 14:55:58 -08005126}
5127
Eric Laurente659ef42014-09-29 13:06:46 -07005128void AudioFlinger::DirectOutputThread::flushHw_l()
5129{
Phil Burk062e67a2015-02-11 13:40:50 -08005130 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005131 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005132 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005133}
5134
Eric Laurent81784c32012-11-19 14:55:58 -08005135// ----------------------------------------------------------------------------
5136
Eric Laurentbfb1b832013-01-07 09:53:42 -08005137AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005138 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005139 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005140 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005141 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005142 mDrainSequence(0),
5143 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005144{
5145}
5146
5147AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5148{
5149}
5150
5151void AudioFlinger::AsyncCallbackThread::onFirstRef()
5152{
5153 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5154}
5155
5156bool AudioFlinger::AsyncCallbackThread::threadLoop()
5157{
5158 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005159 uint32_t writeAckSequence;
5160 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005161 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005162
5163 {
5164 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005165 while (!((mWriteAckSequence & 1) ||
5166 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005167 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005168 exitPending())) {
5169 mWaitWorkCV.wait(mLock);
5170 }
5171
Eric Laurentbfb1b832013-01-07 09:53:42 -08005172 if (exitPending()) {
5173 break;
5174 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005175 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5176 mWriteAckSequence, mDrainSequence);
5177 writeAckSequence = mWriteAckSequence;
5178 mWriteAckSequence &= ~1;
5179 drainSequence = mDrainSequence;
5180 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005181 asyncError = mAsyncError;
5182 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005183 }
5184 {
Eric Laurent4de95592013-09-26 15:28:21 -07005185 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5186 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005187 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005188 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005189 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005190 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005191 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005192 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005193 if (asyncError) {
5194 playbackThread->onAsyncError();
5195 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005196 }
5197 }
5198 }
5199 return false;
5200}
5201
5202void AudioFlinger::AsyncCallbackThread::exit()
5203{
5204 ALOGV("AsyncCallbackThread::exit");
5205 Mutex::Autolock _l(mLock);
5206 requestExit();
5207 mWaitWorkCV.broadcast();
5208}
5209
Eric Laurent3b4529e2013-09-05 18:09:19 -07005210void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005211{
5212 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005213 // bit 0 is cleared
5214 mWriteAckSequence = sequence << 1;
5215}
5216
5217void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5218{
5219 Mutex::Autolock _l(mLock);
5220 // ignore unexpected callbacks
5221 if (mWriteAckSequence & 2) {
5222 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005223 mWaitWorkCV.signal();
5224 }
5225}
5226
Eric Laurent3b4529e2013-09-05 18:09:19 -07005227void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005228{
5229 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005230 // bit 0 is cleared
5231 mDrainSequence = sequence << 1;
5232}
5233
5234void AudioFlinger::AsyncCallbackThread::resetDraining()
5235{
5236 Mutex::Autolock _l(mLock);
5237 // ignore unexpected callbacks
5238 if (mDrainSequence & 2) {
5239 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005240 mWaitWorkCV.signal();
5241 }
5242}
5243
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005244void AudioFlinger::AsyncCallbackThread::setAsyncError()
5245{
5246 Mutex::Autolock _l(mLock);
5247 mAsyncError = true;
5248 mWaitWorkCV.signal();
5249}
5250
Eric Laurentbfb1b832013-01-07 09:53:42 -08005251
5252// ----------------------------------------------------------------------------
5253AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005254 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5255 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005256 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5257 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005258{
Eric Laurentfd477972013-10-25 18:10:40 -07005259 //FIXME: mStandby should be set to true by ThreadBase constructor
5260 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005261 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005262}
5263
Eric Laurentbfb1b832013-01-07 09:53:42 -08005264void AudioFlinger::OffloadThread::threadLoop_exit()
5265{
5266 if (mFlushPending || mHwPaused) {
5267 // If a flush is pending or track was paused, just discard buffered data
5268 flushHw_l();
5269 } else {
5270 mMixerStatus = MIXER_DRAIN_ALL;
5271 threadLoop_drain();
5272 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005273 if (mUseAsyncWrite) {
5274 ALOG_ASSERT(mCallbackThread != 0);
5275 mCallbackThread->exit();
5276 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005277 PlaybackThread::threadLoop_exit();
5278}
5279
5280AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5281 Vector< sp<Track> > *tracksToRemove
5282)
5283{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005284 size_t count = mActiveTracks.size();
5285
5286 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005287 bool doHwPause = false;
5288 bool doHwResume = false;
5289
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005290 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005291
Eric Laurentbfb1b832013-01-07 09:53:42 -08005292 // find out which tracks need to be processed
Eric Laurent9cab7462016-11-10 13:05:20 -08005293 for (size_t i = 0; i < count; i++) {
5294 sp<Track> t = mActiveTracks[i].promote();
5295 // The track died recently
5296 if (t == 0) {
5297 continue;
5298 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005299 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005300#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005301 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005302#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005303 // Only consider last track started for volume and mixer state control.
5304 // In theory an older track could underrun and restart after the new one starts
5305 // but as we only care about the transition phase between two tracks on a
5306 // direct output, it is not a problem to ignore the underrun case.
Eric Laurent9cab7462016-11-10 13:05:20 -08005307 sp<Track> l = mLatestActiveTrack.promote();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005308 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005309
Haynes Mathew George7844f672014-01-15 12:32:55 -08005310 if (track->isInvalid()) {
5311 ALOGW("An invalidated track shouldn't be in active list");
5312 tracksToRemove->add(track);
5313 continue;
5314 }
5315
5316 if (track->mState == TrackBase::IDLE) {
5317 ALOGW("An idle track shouldn't be in active list");
5318 continue;
5319 }
5320
Eric Laurentbfb1b832013-01-07 09:53:42 -08005321 if (track->isPausing()) {
5322 track->setPaused();
5323 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005324 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005325 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005326 mHwPaused = true;
5327 }
5328 // If we were part way through writing the mixbuffer to
5329 // the HAL we must save this until we resume
5330 // BUG - this will be wrong if a different track is made active,
5331 // in that case we want to discard the pending data in the
5332 // mixbuffer and tell the client to present it again when the
5333 // track is resumed
5334 mPausedWriteLength = mCurrentWriteLength;
5335 mPausedBytesRemaining = mBytesRemaining;
5336 mBytesRemaining = 0; // stop writing
5337 }
5338 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005339 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005340 if (track->isStopping_1()) {
5341 track->mRetryCount = kMaxTrackStopRetriesOffload;
5342 } else {
5343 track->mRetryCount = kMaxTrackRetriesOffload;
5344 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005345 track->flushAck();
5346 if (last) {
5347 mFlushPending = true;
5348 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005349 } else if (track->isResumePending()){
5350 track->resumeAck();
5351 if (last) {
5352 if (mPausedBytesRemaining) {
5353 // Need to continue write that was interrupted
5354 mCurrentWriteLength = mPausedWriteLength;
5355 mBytesRemaining = mPausedBytesRemaining;
5356 mPausedBytesRemaining = 0;
5357 }
5358 if (mHwPaused) {
5359 doHwResume = true;
5360 mHwPaused = false;
5361 // threadLoop_mix() will handle the case that we need to
5362 // resume an interrupted write
5363 }
5364 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005365 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005366
Eric Laurent3df841a2016-07-15 15:15:40 -07005367 mLeftVolFloat = mRightVolFloat = -1.0;
5368
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005369 // Do not handle new data in this iteration even if track->framesReady()
5370 mixerStatus = MIXER_TRACKS_ENABLED;
5371 }
5372 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005373 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005374 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005375 if (track->mFillingUpStatus == Track::FS_FILLED) {
5376 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005377 if (last) {
5378 // make sure processVolume_l() will apply new volume even if 0
5379 mLeftVolFloat = mRightVolFloat = -1.0;
5380 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005381 }
5382
5383 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005384 sp<Track> previousTrack = mPreviousTrack.promote();
5385 if (previousTrack != 0) {
5386 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005387 // Flush any data still being written from last track
5388 mBytesRemaining = 0;
5389 if (mPausedBytesRemaining) {
5390 // Last track was paused so we also need to flush saved
5391 // mixbuffer state and invalidate track so that it will
5392 // re-submit that unwritten data when it is next resumed
5393 mPausedBytesRemaining = 0;
5394 // Invalidate is a bit drastic - would be more efficient
5395 // to have a flag to tell client that some of the
5396 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005397 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005398 }
5399 // flush data already sent to the DSP if changing audio session as audio
5400 // comes from a different source. Also invalidate previous track to force a
5401 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005402 if (previousTrack->sessionId() != track->sessionId()) {
5403 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005404 }
5405 }
5406 }
5407 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005408 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005409 if (track->isStopping_1()) {
5410 track->mRetryCount = kMaxTrackStopRetriesOffload;
5411 } else {
5412 track->mRetryCount = kMaxTrackRetriesOffload;
5413 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005414 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005415 mixerStatus = MIXER_TRACKS_READY;
5416 }
5417 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005418 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005419 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005420 if (--(track->mRetryCount) <= 0) {
5421 // Hardware buffer can hold a large amount of audio so we must
5422 // wait for all current track's data to drain before we say
5423 // that the track is stopped.
5424 if (mBytesRemaining == 0) {
5425 // Only start draining when all data in mixbuffer
5426 // has been written
5427 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5428 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5429 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5430 if (last && !mStandby) {
5431 // do not modify drain sequence if we are already draining. This happens
5432 // when resuming from pause after drain.
5433 if ((mDrainSequence & 1) == 0) {
5434 mSleepTimeUs = 0;
5435 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5436 mixerStatus = MIXER_DRAIN_TRACK;
5437 mDrainSequence += 2;
5438 }
5439 if (mHwPaused) {
5440 // It is possible to move from PAUSED to STOPPING_1 without
5441 // a resume so we must ensure hardware is running
5442 doHwResume = true;
5443 mHwPaused = false;
5444 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005445 }
5446 }
Eric Laurente93cc032016-05-05 10:15:10 -07005447 } else if (last) {
5448 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5449 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005450 }
5451 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005452 // Drain has completed or we are in standby, signal presentation complete
5453 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005454 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005455 uint32_t latency = 0;
5456 status_t result = mOutput->stream->getLatency(&latency);
5457 ALOGE_IF(result != OK,
5458 "Error when retrieving output stream latency: %d", result);
5459 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005460 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005461 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005462 track->presentationComplete(framesWritten, audioHALFrames);
5463 track->reset();
5464 tracksToRemove->add(track);
5465 }
5466 } else {
5467 // No buffers for this track. Give it a few chances to
5468 // fill a buffer, then remove it from active list.
5469 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005470 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005471 uint64_t position = 0;
5472 struct timespec unused;
5473 // The running check restarts the retry counter at least once.
5474 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5475 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5476 running = true;
5477 mOffloadUnderrunPosition = position;
5478 }
5479 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005480 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5481 (long long)position, (long long)mOffloadUnderrunPosition);
5482 }
5483 if (running) { // still running, give us more time.
5484 track->mRetryCount = kMaxTrackRetriesOffload;
5485 } else {
5486 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5487 track->name());
5488 tracksToRemove->add(track);
5489 // indicate to client process that the track was disabled because of underrun;
5490 // it will then automatically call start() when data is available
5491 track->disable();
5492 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005493 } else if (last){
5494 mixerStatus = MIXER_TRACKS_ENABLED;
5495 }
5496 }
5497 }
5498 // compute volume for this track
5499 processVolume_l(track, last);
5500 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005501
Eric Laurentea0fade2013-10-04 16:23:48 -07005502 // make sure the pause/flush/resume sequence is executed in the right order.
5503 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5504 // before flush and then resume HW. This can happen in case of pause/flush/resume
5505 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005506 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005507 status_t result = mOutput->stream->pause();
5508 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005509 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005510 if (mFlushPending) {
5511 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005512 }
Eric Laurentfd477972013-10-25 18:10:40 -07005513 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005514 status_t result = mOutput->stream->resume();
5515 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005516 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005517
Eric Laurentbfb1b832013-01-07 09:53:42 -08005518 // remove all the tracks that need to be...
5519 removeTracks_l(*tracksToRemove);
5520
5521 return mixerStatus;
5522}
5523
Eric Laurentbfb1b832013-01-07 09:53:42 -08005524// must be called with thread mutex locked
5525bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5526{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005527 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5528 mWriteAckSequence, mDrainSequence);
5529 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005530 return true;
5531 }
5532 return false;
5533}
5534
Eric Laurentbfb1b832013-01-07 09:53:42 -08005535bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5536{
5537 Mutex::Autolock _l(mLock);
5538 return waitingAsyncCallback_l();
5539}
5540
5541void AudioFlinger::OffloadThread::flushHw_l()
5542{
Eric Laurente659ef42014-09-29 13:06:46 -07005543 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005544 // Flush anything still waiting in the mixbuffer
5545 mCurrentWriteLength = 0;
5546 mBytesRemaining = 0;
5547 mPausedWriteLength = 0;
5548 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005549 // reset bytes written count to reflect that DSP buffers are empty after flush.
5550 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005551 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005552
Eric Laurentbfb1b832013-01-07 09:53:42 -08005553 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005554 // discard any pending drain or write ack by incrementing sequence
5555 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5556 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005557 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005558 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5559 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005560 }
5561}
5562
Haynes Mathew George05317d22016-05-03 16:34:26 -07005563void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5564{
5565 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005566 if (PlaybackThread::invalidateTracks_l(streamType)) {
5567 mFlushPending = true;
5568 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005569}
5570
Eric Laurentbfb1b832013-01-07 09:53:42 -08005571// ----------------------------------------------------------------------------
5572
Eric Laurent81784c32012-11-19 14:55:58 -08005573AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005574 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005575 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005576 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005577 mWaitTimeMs(UINT_MAX)
5578{
5579 addOutputTrack(mainThread);
5580}
5581
5582AudioFlinger::DuplicatingThread::~DuplicatingThread()
5583{
5584 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5585 mOutputTracks[i]->destroy();
5586 }
5587}
5588
5589void AudioFlinger::DuplicatingThread::threadLoop_mix()
5590{
5591 // mix buffers...
5592 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005593 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005594 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005595 if (mMixerBufferValid) {
5596 memset(mMixerBuffer, 0, mMixerBufferSize);
5597 } else {
5598 memset(mSinkBuffer, 0, mSinkBufferSize);
5599 }
Eric Laurent81784c32012-11-19 14:55:58 -08005600 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005601 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005602 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005603 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005604 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005605}
5606
5607void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5608{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005609 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005610 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005611 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005612 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005613 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005614 }
5615 } else if (mBytesWritten != 0) {
5616 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5617 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005618 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005619 } else {
5620 // flush remaining overflow buffers in output tracks
5621 writeFrames = 0;
5622 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005623 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005624 }
5625}
5626
Eric Laurentbfb1b832013-01-07 09:53:42 -08005627ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005628{
5629 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005630 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005631 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005632 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005633 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005634}
5635
5636void AudioFlinger::DuplicatingThread::threadLoop_standby()
5637{
5638 // DuplicatingThread implements standby by stopping all tracks
5639 for (size_t i = 0; i < outputTracks.size(); i++) {
5640 outputTracks[i]->stop();
5641 }
5642}
5643
5644void AudioFlinger::DuplicatingThread::saveOutputTracks()
5645{
5646 outputTracks = mOutputTracks;
5647}
5648
5649void AudioFlinger::DuplicatingThread::clearOutputTracks()
5650{
5651 outputTracks.clear();
5652}
5653
5654void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5655{
5656 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005657 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5658 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5659 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5660 const size_t frameCount =
5661 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5662 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5663 // from different OutputTracks and their associated MixerThreads (e.g. one may
5664 // nearly empty and the other may be dropping data).
5665
5666 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005667 this,
5668 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005669 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005670 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005671 frameCount,
5672 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005673 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5674 if (status != NO_ERROR) {
5675 ALOGE("addOutputTrack() initCheck failed %d", status);
5676 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005677 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005678 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5679 mOutputTracks.add(outputTrack);
5680 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5681 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005682}
5683
5684void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5685{
5686 Mutex::Autolock _l(mLock);
5687 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5688 if (mOutputTracks[i]->thread() == thread) {
5689 mOutputTracks[i]->destroy();
5690 mOutputTracks.removeAt(i);
5691 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005692 if (thread->getOutput() == mOutput) {
5693 mOutput = NULL;
5694 }
Eric Laurent81784c32012-11-19 14:55:58 -08005695 return;
5696 }
5697 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005698 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005699}
5700
5701// caller must hold mLock
5702void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5703{
5704 mWaitTimeMs = UINT_MAX;
5705 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5706 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5707 if (strong != 0) {
5708 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5709 if (waitTimeMs < mWaitTimeMs) {
5710 mWaitTimeMs = waitTimeMs;
5711 }
5712 }
5713 }
5714}
5715
5716
5717bool AudioFlinger::DuplicatingThread::outputsReady(
5718 const SortedVector< sp<OutputTrack> > &outputTracks)
5719{
5720 for (size_t i = 0; i < outputTracks.size(); i++) {
5721 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5722 if (thread == 0) {
5723 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5724 outputTracks[i].get());
5725 return false;
5726 }
5727 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5728 // see note at standby() declaration
5729 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5730 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5731 thread.get());
5732 return false;
5733 }
5734 }
5735 return true;
5736}
5737
5738uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5739{
5740 return (mWaitTimeMs * 1000) / 2;
5741}
5742
5743void AudioFlinger::DuplicatingThread::cacheParameters_l()
5744{
5745 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5746 updateWaitTime_l();
5747
5748 MixerThread::cacheParameters_l();
5749}
5750
5751// ----------------------------------------------------------------------------
5752// Record
5753// ----------------------------------------------------------------------------
5754
5755AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5756 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005757 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005758 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005759 audio_devices_t inDevice,
5760 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005761#ifdef TEE_SINK
5762 , const sp<NBAIO_Sink>& teeSink
5763#endif
5764 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005765 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Eric Laurent9cab7462016-11-10 13:05:20 -08005766 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005767 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005768 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005769#ifdef TEE_SINK
5770 , mTeeSink(teeSink)
5771#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005772 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5773 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005774 // mFastCapture below
5775 , mFastCaptureFutex(0)
5776 // mInputSource
5777 // mPipeSink
5778 // mPipeSource
5779 , mPipeFramesP2(0)
5780 // mPipeMemory
5781 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005782 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005783{
Glenn Kastend7dca052015-03-05 16:05:54 -08005784 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5785 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005786
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005787 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005788
5789 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005790 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005791 size_t numCounterOffers = 0;
5792 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005793#if !LOG_NDEBUG
5794 ssize_t index =
5795#else
5796 (void)
5797#endif
5798 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005799 ALOG_ASSERT(index == 0);
5800
5801 // initialize fast capture depending on configuration
5802 bool initFastCapture;
5803 switch (kUseFastCapture) {
5804 case FastCapture_Never:
5805 initFastCapture = false;
5806 break;
5807 case FastCapture_Always:
5808 initFastCapture = true;
5809 break;
5810 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005811 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005812 break;
5813 // case FastCapture_Dynamic:
5814 }
5815
5816 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005817 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005818 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005819 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5820 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005821 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5822 void *pipeBuffer;
5823 const sp<MemoryDealer> roHeap(readOnlyHeap());
5824 sp<IMemory> pipeMemory;
5825 if ((roHeap == 0) ||
5826 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5827 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5828 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5829 goto failed;
5830 }
5831 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5832 memset(pipeBuffer, 0, pipeSize);
5833 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5834 const NBAIO_Format offers[1] = {format};
5835 size_t numCounterOffers = 0;
5836 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5837 ALOG_ASSERT(index == 0);
5838 mPipeSink = pipe;
5839 PipeReader *pipeReader = new PipeReader(*pipe);
5840 numCounterOffers = 0;
5841 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5842 ALOG_ASSERT(index == 0);
5843 mPipeSource = pipeReader;
5844 mPipeFramesP2 = pipeFramesP2;
5845 mPipeMemory = pipeMemory;
5846
5847 // create fast capture
5848 mFastCapture = new FastCapture();
5849 FastCaptureStateQueue *sq = mFastCapture->sq();
5850#ifdef STATE_QUEUE_DUMP
5851 // FIXME
5852#endif
5853 FastCaptureState *state = sq->begin();
5854 state->mCblk = NULL;
5855 state->mInputSource = mInputSource.get();
5856 state->mInputSourceGen++;
5857 state->mPipeSink = pipe;
5858 state->mPipeSinkGen++;
5859 state->mFrameCount = mFrameCount;
5860 state->mCommand = FastCaptureState::COLD_IDLE;
5861 // already done in constructor initialization list
5862 //mFastCaptureFutex = 0;
5863 state->mColdFutexAddr = &mFastCaptureFutex;
5864 state->mColdGen++;
5865 state->mDumpState = &mFastCaptureDumpState;
5866#ifdef TEE_SINK
5867 // FIXME
5868#endif
5869 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5870 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5871 sq->end();
5872 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5873
5874 // start the fast capture
5875 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5876 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005877 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005878#ifdef AUDIO_WATCHDOG
5879 // FIXME
5880#endif
5881
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005882 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005883 }
5884failed: ;
5885
5886 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005887}
5888
Eric Laurent81784c32012-11-19 14:55:58 -08005889AudioFlinger::RecordThread::~RecordThread()
5890{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005891 if (mFastCapture != 0) {
5892 FastCaptureStateQueue *sq = mFastCapture->sq();
5893 FastCaptureState *state = sq->begin();
5894 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5895 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5896 if (old == -1) {
5897 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5898 }
5899 }
5900 state->mCommand = FastCaptureState::EXIT;
5901 sq->end();
5902 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5903 mFastCapture->join();
5904 mFastCapture.clear();
5905 }
5906 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005907 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005908 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005909}
5910
5911void AudioFlinger::RecordThread::onFirstRef()
5912{
Glenn Kastend7dca052015-03-05 16:05:54 -08005913 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005914}
5915
Eric Laurent81784c32012-11-19 14:55:58 -08005916bool AudioFlinger::RecordThread::threadLoop()
5917{
Eric Laurent81784c32012-11-19 14:55:58 -08005918 nsecs_t lastWarning = 0;
5919
5920 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005921
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005922reacquire_wakelock:
5923 sp<RecordTrack> activeTrack;
Eric Laurent9cab7462016-11-10 13:05:20 -08005924 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005925 {
5926 Mutex::Autolock _l(mLock);
Eric Laurent9cab7462016-11-10 13:05:20 -08005927 size_t size = mActiveTracks.size();
5928 activeTracksGen = mActiveTracksGen;
5929 if (size > 0) {
5930 // FIXME an arbitrary choice
5931 activeTrack = mActiveTracks[0];
5932 acquireWakeLock_l(activeTrack->uid());
5933 if (size > 1) {
5934 SortedVector<int> tmp;
5935 for (size_t i = 0; i < size; i++) {
5936 tmp.add(mActiveTracks[i]->uid());
5937 }
5938 updateWakeLockUids_l(tmp);
5939 }
5940 } else {
5941 acquireWakeLock_l(-1);
5942 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005943 }
5944
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005945 // used to request a deferred sleep, to be executed later while mutex is unlocked
5946 uint32_t sleepUs = 0;
5947
5948 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005949 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005950 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005951
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005952 // activeTracks accumulates a copy of a subset of mActiveTracks
5953 Vector< sp<RecordTrack> > activeTracks;
5954
Glenn Kasten735f45f2014-08-18 15:51:59 -07005955 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005956 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005957
Glenn Kasten735f45f2014-08-18 15:51:59 -07005958 // reference to a fast track which is about to be removed
5959 sp<RecordTrack> fastTrackToRemove;
5960
Eric Laurent81784c32012-11-19 14:55:58 -08005961 { // scope for mLock
5962 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005963
Eric Laurent021cf962014-05-13 10:18:14 -07005964 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005965
Eric Laurent000a4192014-01-29 15:17:32 -08005966 // check exitPending here because checkForNewParameters_l() and
5967 // checkForNewParameters_l() can temporarily release mLock
5968 if (exitPending()) {
5969 break;
5970 }
5971
Eric Laurent5c25d562016-07-13 17:17:45 -07005972 // sleep with mutex unlocked
5973 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07005974 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07005975 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
5976 ATRACE_END();
5977 sleepUs = 0;
5978 continue;
5979 }
5980
Glenn Kasten2b806402013-11-20 16:37:38 -08005981 // if no active track(s), then standby and release wakelock
5982 size_t size = mActiveTracks.size();
5983 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005984 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005985 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005986 releaseWakeLock_l();
5987 ALOGV("RecordThread: loop stopping");
5988 // go to sleep
5989 mWaitWorkCV.wait(mLock);
5990 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005991 goto reacquire_wakelock;
5992 }
5993
Eric Laurent9cab7462016-11-10 13:05:20 -08005994 if (mActiveTracksGen != activeTracksGen) {
5995 activeTracksGen = mActiveTracksGen;
5996 SortedVector<int> tmp;
5997 for (size_t i = 0; i < size; i++) {
5998 tmp.add(mActiveTracks[i]->uid());
5999 }
6000 updateWakeLockUids_l(tmp);
6001 }
6002
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006003 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006004 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006005 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006006
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006007 activeTrack = mActiveTracks[i];
6008 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006009 if (activeTrack->isFastTrack()) {
6010 ALOG_ASSERT(fastTrackToRemove == 0);
6011 fastTrackToRemove = activeTrack;
6012 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006013 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006014 mActiveTracks.remove(activeTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006015 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006016 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006017 continue;
6018 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006019
6020 TrackBase::track_state activeTrackState = activeTrack->mState;
6021 switch (activeTrackState) {
6022
6023 case TrackBase::PAUSING:
6024 mActiveTracks.remove(activeTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006025 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006026 doBroadcast = true;
6027 size--;
6028 continue;
6029
6030 case TrackBase::STARTING_1:
6031 sleepUs = 10000;
6032 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006033 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006034 continue;
6035
6036 case TrackBase::STARTING_2:
6037 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006038 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006039 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006040 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006041 break;
6042
6043 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006044 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006045 break;
6046
6047 case TrackBase::IDLE:
6048 i++;
6049 continue;
6050
6051 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006052 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006053 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006054
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006055 activeTracks.add(activeTrack);
6056 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006057
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006058 if (activeTrack->isFastTrack()) {
6059 ALOG_ASSERT(!mFastTrackAvail);
6060 ALOG_ASSERT(fastTrack == 0);
6061 fastTrack = activeTrack;
6062 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006063 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006064
6065 if (allStopped) {
6066 standbyIfNotAlreadyInStandby();
6067 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006068 if (doBroadcast) {
6069 mStartStopCond.broadcast();
6070 }
6071
6072 // sleep if there are no active tracks to process
6073 if (activeTracks.size() == 0) {
6074 if (sleepUs == 0) {
6075 sleepUs = kRecordThreadSleepUs;
6076 }
6077 continue;
6078 }
6079 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006080
Eric Laurent81784c32012-11-19 14:55:58 -08006081 lockEffectChains_l(effectChains);
6082 }
6083
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006084 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006085
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006086 size_t size = effectChains.size();
6087 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006088 // thread mutex is not locked, but effect chain is locked
6089 effectChains[i]->process_l();
6090 }
6091
Glenn Kasten735f45f2014-08-18 15:51:59 -07006092 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006093 if (mFastCapture != 0) {
6094 FastCaptureStateQueue *sq = mFastCapture->sq();
6095 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006096 bool didModify = false;
6097 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006098 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6099 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6100 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6101 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6102 if (old == -1) {
6103 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6104 }
6105 }
6106 state->mCommand = FastCaptureState::READ_WRITE;
6107#if 0 // FIXME
6108 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006109 FastThreadDumpState::kSamplingNforLowRamDevice :
6110 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006111#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006112 didModify = true;
6113 }
6114 audio_track_cblk_t *cblkOld = state->mCblk;
6115 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6116 if (cblkNew != cblkOld) {
6117 state->mCblk = cblkNew;
6118 // block until acked if removing a fast track
6119 if (cblkOld != NULL) {
6120 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6121 }
6122 didModify = true;
6123 }
6124 sq->end(didModify);
6125 if (didModify) {
6126 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006127#if 0
6128 if (kUseFastCapture == FastCapture_Dynamic) {
6129 mNormalSource = mPipeSource;
6130 }
6131#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006132 }
6133 }
6134
Glenn Kasten735f45f2014-08-18 15:51:59 -07006135 // now run the fast track destructor with thread mutex unlocked
6136 fastTrackToRemove.clear();
6137
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006138 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6139 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6140 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6141 // If destination is non-contiguous, first read past the nominal end of buffer, then
6142 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006143
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006144 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006145 ssize_t framesRead;
6146
6147 // If an NBAIO source is present, use it to read the normal capture's data
6148 if (mPipeSource != 0) {
6149 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006150 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006151 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006152 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006153 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6154 // buffer size or at least for 20ms.
6155 size_t sleepFrames = max(
6156 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6157 if (framesRead <= (ssize_t) sleepFrames) {
6158 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6159 }
6160 if (framesRead < 0) {
6161 status_t status = (status_t) framesRead;
6162 switch (status) {
6163 case OVERRUN:
6164 ALOGW("overrun on read from pipe");
6165 framesRead = 0;
6166 break;
6167 case NEGOTIATE:
6168 ALOGE("re-negotiation is needed");
6169 framesRead = -1; // Will cause an attempt to recover.
6170 break;
6171 default:
6172 ALOGE("unknown error %d on read from pipe", status);
6173 break;
6174 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006175 }
6176 // otherwise use the HAL / AudioStreamIn directly
6177 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006178 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006179 size_t bytesRead;
6180 status_t result = mInput->stream->read(
6181 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006182 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006183 if (result < 0) {
6184 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006185 } else {
6186 framesRead = bytesRead / mFrameSize;
6187 }
6188 }
6189
Andy Hung3f0c9022016-01-15 17:49:46 -08006190 // Update server timestamp with server stats
6191 // systemTime() is optional if the hardware supports timestamps.
6192 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6193 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6194
6195 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006196 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006197 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006198 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006199 if (ret == NO_ERROR) {
6200 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6201 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6202 // Note: In general record buffers should tend to be empty in
6203 // a properly running pipeline.
6204 //
6205 // Also, it is not advantageous to call get_presentation_position during the read
6206 // as the read obtains a lock, preventing the timestamp call from executing.
6207 }
6208 }
6209 // Use this to track timestamp information
6210 // ALOGD("%s", mTimestamp.toString().c_str());
6211
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006212 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006213 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006214 // Force input into standby so that it tries to recover at next read attempt
6215 inputStandBy();
6216 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006217 }
6218 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006219 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006220 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006221 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006222
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006223 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006224 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006225 }
6226 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006227 {
6228 size_t part1 = mRsmpInFramesP2 - rear;
6229 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006230 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006231 (framesRead - part1) * mFrameSize);
6232 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006233 }
6234 rear = mRsmpInRear += framesRead;
6235
6236 size = activeTracks.size();
6237 // loop over each active track
6238 for (size_t i = 0; i < size; i++) {
6239 activeTrack = activeTracks[i];
6240
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006241 // skip fast tracks, as those are handled directly by FastCapture
6242 if (activeTrack->isFastTrack()) {
6243 continue;
6244 }
6245
Andy Hung73c02e42015-03-29 01:13:58 -07006246 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006247 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6248
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006249 enum {
6250 OVERRUN_UNKNOWN,
6251 OVERRUN_TRUE,
6252 OVERRUN_FALSE
6253 } overrun = OVERRUN_UNKNOWN;
6254
6255 // loop over getNextBuffer to handle circular sink
6256 for (;;) {
6257
6258 activeTrack->mSink.frameCount = ~0;
6259 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6260 size_t framesOut = activeTrack->mSink.frameCount;
6261 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6262
Andy Hung73c02e42015-03-29 01:13:58 -07006263 // check available frames and handle overrun conditions
6264 // if the record track isn't draining fast enough.
6265 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006266 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006267 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6268 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006269 overrun = OVERRUN_TRUE;
6270 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006271 if (framesOut == 0 || framesIn == 0) {
6272 break;
6273 }
6274
Andy Hung6770c6f2015-04-07 13:43:36 -07006275 // Don't allow framesOut to be larger than what is possible with resampling
6276 // from framesIn.
6277 // This isn't strictly necessary but helps limit buffer resizing in
6278 // RecordBufferConverter. TODO: remove when no longer needed.
6279 framesOut = min(framesOut,
6280 destinationFramesPossible(
6281 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006282 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6283 framesOut = activeTrack->mRecordBufferConverter->convert(
6284 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006285
6286 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6287 overrun = OVERRUN_FALSE;
6288 }
6289
6290 if (activeTrack->mFramesToDrop == 0) {
6291 if (framesOut > 0) {
6292 activeTrack->mSink.frameCount = framesOut;
6293 activeTrack->releaseBuffer(&activeTrack->mSink);
6294 }
6295 } else {
6296 // FIXME could do a partial drop of framesOut
6297 if (activeTrack->mFramesToDrop > 0) {
6298 activeTrack->mFramesToDrop -= framesOut;
6299 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006300 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006301 }
6302 } else {
6303 activeTrack->mFramesToDrop += framesOut;
6304 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6305 activeTrack->mSyncStartEvent->isCancelled()) {
6306 ALOGW("Synced record %s, session %d, trigger session %d",
6307 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6308 activeTrack->sessionId(),
6309 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006310 activeTrack->mSyncStartEvent->triggerSession() :
6311 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006312 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006313 }
6314 }
6315 }
6316
6317 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006318 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006319 }
6320 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006321
6322 switch (overrun) {
6323 case OVERRUN_TRUE:
6324 // client isn't retrieving buffers fast enough
6325 if (!activeTrack->setOverflow()) {
6326 nsecs_t now = systemTime();
6327 // FIXME should lastWarning per track?
6328 if ((now - lastWarning) > kWarningThrottleNs) {
6329 ALOGW("RecordThread: buffer overflow");
6330 lastWarning = now;
6331 }
6332 }
6333 break;
6334 case OVERRUN_FALSE:
6335 activeTrack->clearOverflow();
6336 break;
6337 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006338 break;
6339 }
6340
Andy Hung3f0c9022016-01-15 17:49:46 -08006341 // update frame information and push timestamp out
6342 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006343 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006344 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6345 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006346 }
6347
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006348unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006349 // enable changes in effect chain
6350 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006351 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006352 }
6353
Glenn Kasten93e471f2013-08-19 08:40:07 -07006354 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006355
6356 {
6357 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006358 for (size_t i = 0; i < mTracks.size(); i++) {
6359 sp<RecordTrack> track = mTracks[i];
6360 track->invalidate();
6361 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006362 mActiveTracks.clear();
Eric Laurent9cab7462016-11-10 13:05:20 -08006363 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006364 mStartStopCond.broadcast();
6365 }
6366
6367 releaseWakeLock();
6368
6369 ALOGV("RecordThread %p exiting", this);
6370 return false;
6371}
6372
Glenn Kasten93e471f2013-08-19 08:40:07 -07006373void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006374{
6375 if (!mStandby) {
6376 inputStandBy();
6377 mStandby = true;
6378 }
6379}
6380
6381void AudioFlinger::RecordThread::inputStandBy()
6382{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006383 // Idle the fast capture if it's currently running
6384 if (mFastCapture != 0) {
6385 FastCaptureStateQueue *sq = mFastCapture->sq();
6386 FastCaptureState *state = sq->begin();
6387 if (!(state->mCommand & FastCaptureState::IDLE)) {
6388 state->mCommand = FastCaptureState::COLD_IDLE;
6389 state->mColdFutexAddr = &mFastCaptureFutex;
6390 state->mColdGen++;
6391 mFastCaptureFutex = 0;
6392 sq->end();
6393 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6394 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6395#if 0
6396 if (kUseFastCapture == FastCapture_Dynamic) {
6397 // FIXME
6398 }
6399#endif
6400#ifdef AUDIO_WATCHDOG
6401 // FIXME
6402#endif
6403 } else {
6404 sq->end(false /*didModify*/);
6405 }
6406 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006407 status_t result = mInput->stream->standby();
6408 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006409
6410 // If going into standby, flush the pipe source.
6411 if (mPipeSource.get() != nullptr) {
6412 const ssize_t flushed = mPipeSource->flush();
6413 if (flushed > 0) {
6414 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6415 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6416 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6417 }
6418 }
Eric Laurent81784c32012-11-19 14:55:58 -08006419}
6420
Glenn Kasten05997e22014-03-13 15:08:33 -07006421// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006422sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006423 const sp<AudioFlinger::Client>& client,
6424 uint32_t sampleRate,
6425 audio_format_t format,
6426 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006427 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006428 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006429 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006430 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006431 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006432 pid_t tid,
6433 status_t *status)
6434{
Glenn Kasten74935e42013-12-19 08:56:45 -08006435 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006436 sp<RecordTrack> track;
6437 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006438 audio_input_flags_t inputFlags = mInput->flags;
6439
6440 // special case for FAST flag considered OK if fast capture is present
6441 if (hasFastCapture()) {
6442 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6443 }
6444
6445 // Check if requested flags are compatible with output stream flags
6446 if ((*flags & inputFlags) != *flags) {
6447 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6448 " input flags (%08x)",
6449 *flags, inputFlags);
6450 *flags = (audio_input_flags_t)(*flags & inputFlags);
6451 }
Eric Laurent81784c32012-11-19 14:55:58 -08006452
Glenn Kasten90e58b12013-07-31 16:16:02 -07006453 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006454 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006455 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006456 // we formerly checked for a callback handler (non-0 tid),
6457 // but that is no longer required for TRANSFER_OBTAIN mode
6458 //
Glenn Kasten74105912014-07-03 12:28:53 -07006459 // frame count is not specified, or is exactly the pipe depth
6460 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006461 // PCM data
6462 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006463 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006464 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006465 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006466 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006467 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006468 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006469 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006470 hasFastCapture() &&
6471 // there are sufficient fast track slots available
6472 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006473 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006474 // check compatibility with audio effects.
6475 Mutex::Autolock _l(mLock);
6476 // Do not accept FAST flag if the session has software effects
6477 sp<EffectChain> chain = getEffectChain_l(sessionId);
6478 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006479 audio_input_flags_t old = *flags;
6480 chain->checkInputFlagCompatibility(flags);
6481 if (old != *flags) {
6482 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6483 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006484 }
6485 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006486 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006487 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6488 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006489 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006490 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006491 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006492 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006493 frameCount, mFrameCount, mPipeFramesP2,
6494 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6495 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006496 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006497 }
6498 }
6499
6500 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006501 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006502 // fast track: frame count is exactly the pipe depth
6503 frameCount = mPipeFramesP2;
6504 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6505 *notificationFrames = mFrameCount;
6506 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006507 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6508 // or 20 ms if there is a fast capture
6509 // TODO This could be a roundupRatio inline, and const
6510 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6511 * sampleRate + mSampleRate - 1) / mSampleRate;
6512 // minimum number of notification periods is at least kMinNotifications,
6513 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6514 static const size_t kMinNotifications = 3;
6515 static const uint32_t kMinMs = 30;
6516 // TODO This could be a roundupRatio inline
6517 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6518 // TODO This could be a roundupRatio inline
6519 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6520 maxNotificationFrames;
6521 const size_t minFrameCount = maxNotificationFrames *
6522 max(kMinNotifications, minNotificationsByMs);
6523 frameCount = max(frameCount, minFrameCount);
6524 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6525 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006526 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006527 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006528 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006529
Glenn Kasten15e57982013-09-24 11:52:37 -07006530 lStatus = initCheck();
6531 if (lStatus != NO_ERROR) {
6532 ALOGE("createRecordTrack_l() audio driver not initialized");
6533 goto Exit;
6534 }
Eric Laurent81784c32012-11-19 14:55:58 -08006535
6536 { // scope for mLock
6537 Mutex::Autolock _l(mLock);
6538
6539 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006540 format, channelMask, frameCount, NULL, sessionId, uid,
6541 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006542
Glenn Kasten03003332013-08-06 15:40:54 -07006543 lStatus = track->initCheck();
6544 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006545 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006546 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006547 goto Exit;
6548 }
6549 mTracks.add(track);
6550
6551 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6552 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6553 mAudioFlinger->btNrecIsOff();
6554 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6555 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006556
Eric Laurent05067782016-06-01 18:27:28 -07006557 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006558 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6559 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6560 // so ask activity manager to do this on our behalf
6561 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6562 }
Eric Laurent81784c32012-11-19 14:55:58 -08006563 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006564
Eric Laurent81784c32012-11-19 14:55:58 -08006565 lStatus = NO_ERROR;
6566
6567Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006568 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006569 return track;
6570}
6571
6572status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6573 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006574 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006575{
6576 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6577 sp<ThreadBase> strongMe = this;
6578 status_t status = NO_ERROR;
6579
6580 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006581 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006582 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006583 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006584 triggerSession,
6585 recordTrack->sessionId(),
6586 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006587 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006588 // Sync event can be cancelled by the trigger session if the track is not in a
6589 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006590 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006591 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006592 } else {
6593 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006594 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006595 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006596 }
6597 }
6598
6599 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006600 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006601 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006602 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6603 if (recordTrack->mState == TrackBase::PAUSING) {
6604 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006605 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006606 } else {
6607 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006608 }
6609 return status;
6610 }
6611
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006612 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6613 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6614 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006615 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006616 mActiveTracks.add(recordTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006617 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006618 status_t status = NO_ERROR;
6619 if (recordTrack->isExternalTrack()) {
6620 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006621 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006622 mLock.lock();
6623 // FIXME should verify that recordTrack is still in mActiveTracks
6624 if (status != NO_ERROR) {
6625 mActiveTracks.remove(recordTrack);
Eric Laurent9cab7462016-11-10 13:05:20 -08006626 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006627 recordTrack->clearSyncStartEvent();
6628 ALOGV("RecordThread::start error %d", status);
6629 return status;
6630 }
Eric Laurent81784c32012-11-19 14:55:58 -08006631 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006632 // Catch up with current buffer indices if thread is already running.
6633 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6634 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6635 // see previously buffered data before it called start(), but with greater risk of overrun.
6636
Andy Hung73c02e42015-03-29 01:13:58 -07006637 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006638 // clear any converter state as new data will be discontinuous
6639 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006640 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006641 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006642 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006643 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006644 ALOGV("Record failed to start");
6645 status = BAD_VALUE;
6646 goto startError;
6647 }
Eric Laurent81784c32012-11-19 14:55:58 -08006648 return status;
6649 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006650
Eric Laurent81784c32012-11-19 14:55:58 -08006651startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006652 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006653 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006654 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006655 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006656 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006657 return status;
6658}
6659
Eric Laurent81784c32012-11-19 14:55:58 -08006660void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6661{
6662 sp<SyncEvent> strongEvent = event.promote();
6663
6664 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006665 sp<RefBase> ptr = strongEvent->cookie().promote();
6666 if (ptr != 0) {
6667 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6668 recordTrack->handleSyncStartEvent(strongEvent);
6669 }
Eric Laurent81784c32012-11-19 14:55:58 -08006670 }
6671}
6672
Glenn Kastena8356f62013-07-25 14:37:52 -07006673bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006674 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006675 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006676 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006677 return false;
6678 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006679 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006680 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006681 // signal thread to stop
6682 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006683 // do not wait for mStartStopCond if exiting
6684 if (exitPending()) {
6685 return true;
6686 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006687 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006688 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006689 // if we have been restarted, recordTrack is in mActiveTracks here
6690 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006691 ALOGV("Record stopped OK");
6692 return true;
6693 }
6694 return false;
6695}
6696
Glenn Kasten0f11b512014-01-31 16:18:54 -08006697bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006698{
6699 return false;
6700}
6701
Glenn Kasten0f11b512014-01-31 16:18:54 -08006702status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006703{
6704#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6705 if (!isValidSyncEvent(event)) {
6706 return BAD_VALUE;
6707 }
6708
Glenn Kastend848eb42016-03-08 13:42:11 -08006709 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006710 status_t ret = NAME_NOT_FOUND;
6711
6712 Mutex::Autolock _l(mLock);
6713
6714 for (size_t i = 0; i < mTracks.size(); i++) {
6715 sp<RecordTrack> track = mTracks[i];
6716 if (eventSession == track->sessionId()) {
6717 (void) track->setSyncEvent(event);
6718 ret = NO_ERROR;
6719 }
6720 }
6721 return ret;
6722#else
6723 return BAD_VALUE;
6724#endif
6725}
6726
6727// destroyTrack_l() must be called with ThreadBase::mLock held
6728void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6729{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006730 track->terminate();
6731 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006732 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006733 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006734 removeTrack_l(track);
6735 }
6736}
6737
6738void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6739{
6740 mTracks.remove(track);
6741 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006742 if (track->isFastTrack()) {
6743 ALOG_ASSERT(!mFastTrackAvail);
6744 mFastTrackAvail = true;
6745 }
Eric Laurent81784c32012-11-19 14:55:58 -08006746}
6747
6748void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6749{
6750 dumpInternals(fd, args);
6751 dumpTracks(fd, args);
6752 dumpEffectChains(fd, args);
6753}
6754
6755void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6756{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006757 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006758
Glenn Kasten44182c22015-03-05 17:12:23 -08006759 dumpBase(fd, args);
6760
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006761 AudioStreamIn *input = mInput;
6762 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6763 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6764 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006765 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006766 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006767 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006768 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006769 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006770
Glenn Kasten2f90c512015-12-02 11:40:09 -08006771 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6772 // while we are dumping it. It may be inconsistent, but it won't mutate!
6773 // This is a large object so we place it on the heap.
6774 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6775 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6776 copy->dump(fd);
6777 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006778}
6779
Glenn Kasten0f11b512014-01-31 16:18:54 -08006780void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006781{
6782 const size_t SIZE = 256;
6783 char buffer[SIZE];
6784 String8 result;
6785
Marco Nelissenb2208842014-02-07 14:00:50 -08006786 size_t numtracks = mTracks.size();
6787 size_t numactive = mActiveTracks.size();
6788 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006789 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006790 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006791 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006792 RecordTrack::appendDumpHeader(result);
6793 for (size_t i = 0; i < numtracks ; ++i) {
6794 sp<RecordTrack> track = mTracks[i];
6795 if (track != 0) {
6796 bool active = mActiveTracks.indexOf(track) >= 0;
6797 if (active) {
6798 numactiveseen++;
6799 }
6800 track->dump(buffer, SIZE, active);
6801 result.append(buffer);
6802 }
Eric Laurent81784c32012-11-19 14:55:58 -08006803 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006804 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006805 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006806 }
6807
Marco Nelissenb2208842014-02-07 14:00:50 -08006808 if (numactiveseen != numactive) {
6809 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6810 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006811 result.append(buffer);
6812 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006813 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006814 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006815 if (mTracks.indexOf(track) < 0) {
6816 track->dump(buffer, SIZE, true);
6817 result.append(buffer);
6818 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006819 }
Eric Laurent81784c32012-11-19 14:55:58 -08006820
6821 }
6822 write(fd, result.string(), result.size());
6823}
6824
Andy Hung73c02e42015-03-29 01:13:58 -07006825
6826void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6827{
6828 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6829 RecordThread *recordThread = (RecordThread *) threadBase.get();
6830 mRsmpInFront = recordThread->mRsmpInRear;
6831 mRsmpInUnrel = 0;
6832}
6833
6834void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6835 size_t *framesAvailable, bool *hasOverrun)
6836{
6837 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6838 RecordThread *recordThread = (RecordThread *) threadBase.get();
6839 const int32_t rear = recordThread->mRsmpInRear;
6840 const int32_t front = mRsmpInFront;
6841 const ssize_t filled = rear - front;
6842
6843 size_t framesIn;
6844 bool overrun = false;
6845 if (filled < 0) {
6846 // should not happen, but treat like a massive overrun and re-sync
6847 framesIn = 0;
6848 mRsmpInFront = rear;
6849 overrun = true;
6850 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6851 framesIn = (size_t) filled;
6852 } else {
6853 // client is not keeping up with server, but give it latest data
6854 framesIn = recordThread->mRsmpInFrames;
6855 mRsmpInFront = /* front = */ rear - framesIn;
6856 overrun = true;
6857 }
6858 if (framesAvailable != NULL) {
6859 *framesAvailable = framesIn;
6860 }
6861 if (hasOverrun != NULL) {
6862 *hasOverrun = overrun;
6863 }
6864}
6865
Eric Laurent81784c32012-11-19 14:55:58 -08006866// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006867status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006868 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006869{
Andy Hung73c02e42015-03-29 01:13:58 -07006870 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006871 if (threadBase == 0) {
6872 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006873 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006874 return NOT_ENOUGH_DATA;
6875 }
6876 RecordThread *recordThread = (RecordThread *) threadBase.get();
6877 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006878 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006879 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006880 // FIXME should not be P2 (don't want to increase latency)
6881 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006882 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006883 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006884 front &= recordThread->mRsmpInFramesP2 - 1;
6885 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006886 if (part1 > (size_t) filled) {
6887 part1 = filled;
6888 }
6889 size_t ask = buffer->frameCount;
6890 ALOG_ASSERT(ask > 0);
6891 if (part1 > ask) {
6892 part1 = ask;
6893 }
6894 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006895 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006896 buffer->raw = NULL;
6897 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006898 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006899 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006900 }
6901
Andy Hung57446612015-04-19 23:56:46 -07006902 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006903 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006904 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006905 return NO_ERROR;
6906}
6907
6908// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006909void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6910 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006911{
Glenn Kasten85948432013-08-19 12:09:05 -07006912 size_t stepCount = buffer->frameCount;
6913 if (stepCount == 0) {
6914 return;
6915 }
Andy Hung73c02e42015-03-29 01:13:58 -07006916 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6917 mRsmpInUnrel -= stepCount;
6918 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006919 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006920 buffer->frameCount = 0;
6921}
6922
Andy Hung97a893e2015-03-29 01:03:07 -07006923AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6924 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6925 uint32_t srcSampleRate,
6926 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6927 uint32_t dstSampleRate) :
6928 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6929 // mSrcFormat
6930 // mSrcSampleRate
6931 // mDstChannelMask
6932 // mDstFormat
6933 // mDstSampleRate
6934 // mSrcChannelCount
6935 // mDstChannelCount
6936 // mDstFrameSize
6937 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006938 mResampler(NULL),
6939 mIsLegacyDownmix(false),
6940 mIsLegacyUpmix(false),
6941 mRequiresFloat(false),
6942 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006943{
6944 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6945 dstChannelMask, dstFormat, dstSampleRate);
6946}
6947
6948AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6949 free(mBuf);
6950 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006951 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006952}
6953
6954size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6955 AudioBufferProvider *provider, size_t frames)
6956{
Andy Hungd330ee42015-04-20 13:23:41 -07006957 if (mInputConverterProvider != NULL) {
6958 mInputConverterProvider->setBufferProvider(provider);
6959 provider = mInputConverterProvider;
6960 }
6961
6962 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006963 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6964 mSrcSampleRate, mSrcFormat, mDstFormat);
6965
6966 AudioBufferProvider::Buffer buffer;
6967 for (size_t i = frames; i > 0; ) {
6968 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006969 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006970 if (status != OK || buffer.frameCount == 0) {
6971 frames -= i; // cannot fill request.
6972 break;
6973 }
Andy Hungd330ee42015-04-20 13:23:41 -07006974 // format convert to destination buffer
6975 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006976
6977 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6978 i -= buffer.frameCount;
6979 provider->releaseBuffer(&buffer);
6980 }
6981 } else {
6982 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6983 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6984
Andy Hungd330ee42015-04-20 13:23:41 -07006985 // reallocate buffer if needed
6986 if (mBufFrameSize != 0 && mBufFrames < frames) {
6987 free(mBuf);
6988 mBufFrames = frames;
6989 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6990 }
Andy Hung97a893e2015-03-29 01:03:07 -07006991 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006992 memset(mBuf, 0, frames * mBufFrameSize);
6993 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6994 // format convert to destination buffer
6995 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006996 }
6997 return frames;
6998}
6999
7000status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7001 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7002 uint32_t srcSampleRate,
7003 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7004 uint32_t dstSampleRate)
7005{
7006 // quick evaluation if there is any change.
7007 if (mSrcFormat == srcFormat
7008 && mSrcChannelMask == srcChannelMask
7009 && mSrcSampleRate == srcSampleRate
7010 && mDstFormat == dstFormat
7011 && mDstChannelMask == dstChannelMask
7012 && mDstSampleRate == dstSampleRate) {
7013 return NO_ERROR;
7014 }
7015
Andy Hungdb4c0312015-05-06 08:46:52 -07007016 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7017 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7018 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007019 const bool valid =
7020 audio_is_input_channel(srcChannelMask)
7021 && audio_is_input_channel(dstChannelMask)
7022 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7023 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7024 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7025 ; // no upsampling checks for now
7026 if (!valid) {
7027 return BAD_VALUE;
7028 }
7029
7030 mSrcFormat = srcFormat;
7031 mSrcChannelMask = srcChannelMask;
7032 mSrcSampleRate = srcSampleRate;
7033 mDstFormat = dstFormat;
7034 mDstChannelMask = dstChannelMask;
7035 mDstSampleRate = dstSampleRate;
7036
7037 // compute derived parameters
7038 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7039 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7040 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7041
Andy Hungd330ee42015-04-20 13:23:41 -07007042 // do we need to resample?
7043 delete mResampler;
7044 mResampler = NULL;
7045 if (mSrcSampleRate != mDstSampleRate) {
7046 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7047 mSrcChannelCount, mDstSampleRate);
7048 mResampler->setSampleRate(mSrcSampleRate);
7049 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7050 }
7051
7052 // are we running legacy channel conversion modes?
7053 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7054 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7055 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7056 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7057 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7058 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7059
7060 // do we need to process in float?
7061 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7062
7063 // do we need a staging buffer to convert for destination (we can still optimize this)?
7064 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7065 if (mResampler != NULL) {
7066 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7067 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007068 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007069 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7070 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007071 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7072 } else {
7073 mBufFrameSize = 0;
7074 }
7075 mBufFrames = 0; // force the buffer to be resized.
7076
Andy Hungd330ee42015-04-20 13:23:41 -07007077 // do we need an input converter buffer provider to give us float?
7078 delete mInputConverterProvider;
7079 mInputConverterProvider = NULL;
7080 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7081 mInputConverterProvider = new ReformatBufferProvider(
7082 audio_channel_count_from_in_mask(mSrcChannelMask),
7083 mSrcFormat,
7084 AUDIO_FORMAT_PCM_FLOAT,
7085 256 /* provider buffer frame count */);
7086 }
7087
7088 // do we need a remixer to do channel mask conversion
7089 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7090 (void) memcpy_by_index_array_initialization_from_channel_mask(
7091 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007092 }
7093 return NO_ERROR;
7094}
7095
Andy Hungd330ee42015-04-20 13:23:41 -07007096void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7097 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007098{
Andy Hungd330ee42015-04-20 13:23:41 -07007099 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007100 if (mBufFrameSize != 0 && mBufFrames < frames) {
7101 free(mBuf);
7102 mBufFrames = frames;
7103 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7104 }
Andy Hungd330ee42015-04-20 13:23:41 -07007105 // do we need to do legacy upmix and downmix?
7106 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007107 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007108 if (mIsLegacyUpmix) {
7109 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7110 (const float *)src, frames);
7111 } else /*mIsLegacyDownmix */ {
7112 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7113 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007114 }
Andy Hungd330ee42015-04-20 13:23:41 -07007115 if (mBuf != NULL) {
7116 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7117 frames * mDstChannelCount);
7118 }
7119 return;
7120 }
7121 // do we need to do channel mask conversion?
7122 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007123 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007124 memcpy_by_index_array(dstBuf, mDstChannelCount,
7125 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7126 if (dstBuf == dst) {
7127 return; // format is the same
7128 }
7129 }
7130 // convert to destination buffer
7131 const void *convertBuf = mBuf != NULL ? mBuf : src;
7132 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7133 frames * mDstChannelCount);
7134}
7135
7136void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7137 void *dst, /*not-a-const*/ void *src, size_t frames)
7138{
7139 // src buffer format is ALWAYS float when entering this routine
7140 if (mIsLegacyUpmix) {
7141 ; // mono to stereo already handled by resampler
7142 } else if (mIsLegacyDownmix
7143 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7144 // the resampler outputs stereo for mono input channel (a feature?)
7145 // must convert to mono
7146 downmix_to_mono_float_from_stereo_float((float *)src,
7147 (const float *)src, frames);
7148 } else if (mSrcChannelMask != mDstChannelMask) {
7149 // convert to mono channel again for channel mask conversion (could be skipped
7150 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007151 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007152 downmix_to_mono_float_from_stereo_float((float *)src,
7153 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007154 }
Andy Hungd330ee42015-04-20 13:23:41 -07007155 // convert to destination format (in place, OK as float is larger than other types)
7156 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7157 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7158 frames * mSrcChannelCount);
7159 }
7160 // channel convert and save to dst
7161 memcpy_by_index_array(dst, mDstChannelCount,
7162 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7163 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007164 }
Andy Hungd330ee42015-04-20 13:23:41 -07007165 // convert to destination format and save to dst
7166 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7167 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007168}
7169
Eric Laurent10351942014-05-08 18:49:52 -07007170bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7171 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007172{
7173 bool reconfig = false;
7174
Eric Laurent10351942014-05-08 18:49:52 -07007175 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007176
Eric Laurent10351942014-05-08 18:49:52 -07007177 audio_format_t reqFormat = mFormat;
7178 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007179 // 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 -07007180 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7181
7182 AudioParameter param = AudioParameter(keyValuePair);
7183 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007184
7185 // scope for AutoPark extends to end of method
7186 AutoPark<FastCapture> park(mFastCapture);
7187
Eric Laurent10351942014-05-08 18:49:52 -07007188 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7189 // channel count change can be requested. Do we mandate the first client defines the
7190 // HAL sampling rate and channel count or do we allow changes on the fly?
7191 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7192 samplingRate = value;
7193 reconfig = true;
7194 }
7195 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007196 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007197 status = BAD_VALUE;
7198 } else {
7199 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007200 reconfig = true;
7201 }
Eric Laurent10351942014-05-08 18:49:52 -07007202 }
7203 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7204 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007205 if (!audio_is_input_channel(mask) ||
7206 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007207 status = BAD_VALUE;
7208 } else {
7209 channelMask = mask;
7210 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007211 }
Eric Laurent10351942014-05-08 18:49:52 -07007212 }
7213 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7214 // do not accept frame count changes if tracks are open as the track buffer
7215 // size depends on frame count and correct behavior would not be guaranteed
7216 // if frame count is changed after track creation
7217 if (mActiveTracks.size() > 0) {
7218 status = INVALID_OPERATION;
7219 } else {
7220 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007221 }
Eric Laurent10351942014-05-08 18:49:52 -07007222 }
7223 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7224 // forward device change to effects that have requested to be
7225 // aware of attached audio device.
7226 for (size_t i = 0; i < mEffectChains.size(); i++) {
7227 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007228 }
Eric Laurent81784c32012-11-19 14:55:58 -08007229
Eric Laurent10351942014-05-08 18:49:52 -07007230 // store input device and output device but do not forward output device to audio HAL.
7231 // Note that status is ignored by the caller for output device
7232 // (see AudioFlinger::setParameters()
7233 if (audio_is_output_devices(value)) {
7234 mOutDevice = value;
7235 status = BAD_VALUE;
7236 } else {
7237 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007238 if (value != AUDIO_DEVICE_NONE) {
7239 mPrevInDevice = value;
7240 }
Eric Laurent10351942014-05-08 18:49:52 -07007241 // disable AEC and NS if the device is a BT SCO headset supporting those
7242 // pre processings
7243 if (mTracks.size() > 0) {
7244 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7245 mAudioFlinger->btNrecIsOff();
7246 for (size_t i = 0; i < mTracks.size(); i++) {
7247 sp<RecordTrack> track = mTracks[i];
7248 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7249 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007250 }
7251 }
7252 }
Eric Laurent10351942014-05-08 18:49:52 -07007253 }
7254 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7255 mAudioSource != (audio_source_t)value) {
7256 // forward device change to effects that have requested to be
7257 // aware of attached audio device.
7258 for (size_t i = 0; i < mEffectChains.size(); i++) {
7259 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007260 }
Eric Laurent10351942014-05-08 18:49:52 -07007261 mAudioSource = (audio_source_t)value;
7262 }
Glenn Kastene198c362013-08-13 09:13:36 -07007263
Eric Laurent10351942014-05-08 18:49:52 -07007264 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007265 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007266 if (status == INVALID_OPERATION) {
7267 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007268 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007269 }
7270 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007271 if (status == BAD_VALUE) {
7272 uint32_t sRate;
7273 audio_channel_mask_t channelMask;
7274 audio_format_t format;
7275 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7276 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7277 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7278 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7279 status = NO_ERROR;
7280 }
Eric Laurent81784c32012-11-19 14:55:58 -08007281 }
Eric Laurent10351942014-05-08 18:49:52 -07007282 if (status == NO_ERROR) {
7283 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007284 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007285 }
7286 }
Eric Laurent81784c32012-11-19 14:55:58 -08007287 }
Eric Laurent10351942014-05-08 18:49:52 -07007288
Eric Laurent81784c32012-11-19 14:55:58 -08007289 return reconfig;
7290}
7291
7292String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7293{
Eric Laurent81784c32012-11-19 14:55:58 -08007294 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007295 if (initCheck() == NO_ERROR) {
7296 String8 out_s8;
7297 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7298 return out_s8;
7299 }
Eric Laurent81784c32012-11-19 14:55:58 -08007300 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007301 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007302}
7303
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007304void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007305 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7306
7307 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007308
7309 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007310 case AUDIO_INPUT_OPENED:
7311 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007312 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007313 desc->mChannelMask = mChannelMask;
7314 desc->mSamplingRate = mSampleRate;
7315 desc->mFormat = mFormat;
7316 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007317 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007318 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007319 break;
7320
Eric Laurent73e26b62015-04-27 16:55:58 -07007321 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007322 default:
7323 break;
7324 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007325 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007326}
7327
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007328void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007329{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007330 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7331 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007332 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007333 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007334 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007335 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7336 result = mInput->stream->getFrameSize(&mFrameSize);
7337 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7338 result = mInput->stream->getBufferSize(&mBufferSize);
7339 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007340 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007341 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007342 // 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 -07007343 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007344 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007345 // A larger value should allow more old data to be read after a track calls start(),
7346 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007347 //
7348 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007349 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007350 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007351 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007352 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007353
7354 // TODO optimize audio capture buffer sizes ...
7355 // Here we calculate the size of the sliding buffer used as a source
7356 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7357 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7358 // be better to have it derived from the pipe depth in the long term.
7359 // The current value is higher than necessary. However it should not add to latency.
7360
Glenn Kasten85948432013-08-19 12:09:05 -07007361 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007362 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7363 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7364 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007365
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007366 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7367 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007368}
7369
Glenn Kasten5f972c02014-01-13 09:59:31 -08007370uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007371{
7372 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007373 uint32_t result;
7374 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7375 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007376 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007377 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007378}
7379
Eric Laurent4c415062016-06-17 16:14:16 -07007380// hasAudioSession_l() must be called with ThreadBase::mLock held
7381uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007382{
Eric Laurent81784c32012-11-19 14:55:58 -08007383 uint32_t result = 0;
7384 if (getEffectChain_l(sessionId) != 0) {
7385 result = EFFECT_SESSION;
7386 }
7387
7388 for (size_t i = 0; i < mTracks.size(); ++i) {
7389 if (sessionId == mTracks[i]->sessionId()) {
7390 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007391 if (mTracks[i]->isFastTrack()) {
7392 result |= FAST_SESSION;
7393 }
Eric Laurent81784c32012-11-19 14:55:58 -08007394 break;
7395 }
7396 }
7397
7398 return result;
7399}
7400
Glenn Kastend848eb42016-03-08 13:42:11 -08007401KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007402{
Glenn Kastend848eb42016-03-08 13:42:11 -08007403 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007404 Mutex::Autolock _l(mLock);
7405 for (size_t j = 0; j < mTracks.size(); ++j) {
7406 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007407 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007408 if (ids.indexOfKey(sessionId) < 0) {
7409 ids.add(sessionId, true);
7410 }
7411 }
7412 return ids;
7413}
7414
7415AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7416{
7417 Mutex::Autolock _l(mLock);
7418 AudioStreamIn *input = mInput;
7419 mInput = NULL;
7420 return input;
7421}
7422
7423// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007424sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007425{
7426 if (mInput == NULL) {
7427 return NULL;
7428 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007429 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007430}
7431
7432status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7433{
7434 // only one chain per input thread
7435 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007436 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007437 return INVALID_OPERATION;
7438 }
7439 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007440 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007441 chain->setInBuffer(NULL);
7442 chain->setOutBuffer(NULL);
7443
7444 checkSuspendOnAddEffectChain_l(chain);
7445
Eric Laurent1b928682014-10-02 19:41:47 -07007446 // make sure enabled pre processing effects state is communicated to the HAL as we
7447 // just moved them to a new input stream.
7448 chain->syncHalEffectsState();
7449
Eric Laurent81784c32012-11-19 14:55:58 -08007450 mEffectChains.add(chain);
7451
7452 return NO_ERROR;
7453}
7454
7455size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7456{
7457 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7458 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007459 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007460 chain.get(), mEffectChains.size(), this);
7461 if (mEffectChains.size() == 1) {
7462 mEffectChains.removeAt(0);
7463 }
7464 return 0;
7465}
7466
Eric Laurent1c333e22014-05-20 10:48:17 -07007467status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7468 audio_patch_handle_t *handle)
7469{
7470 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007471
7472 // store new device and send to effects
7473 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007474 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007475 for (size_t i = 0; i < mEffectChains.size(); i++) {
7476 mEffectChains[i]->setDevice_l(mInDevice);
7477 }
7478
7479 // disable AEC and NS if the device is a BT SCO headset supporting those
7480 // pre processings
7481 if (mTracks.size() > 0) {
7482 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7483 mAudioFlinger->btNrecIsOff();
7484 for (size_t i = 0; i < mTracks.size(); i++) {
7485 sp<RecordTrack> track = mTracks[i];
7486 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7487 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7488 }
7489 }
7490
7491 // store new source and send to effects
7492 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7493 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007494 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007495 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007496 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007497 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007498
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007499 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007500 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7501 status = hwDevice->createAudioPatch(patch->num_sources,
7502 patch->sources,
7503 patch->num_sinks,
7504 patch->sinks,
7505 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007506 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007507 char *address;
7508 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7509 address = audio_device_address_to_parameter(
7510 patch->sources[0].ext.device.type,
7511 patch->sources[0].ext.device.address);
7512 } else {
7513 address = (char *)calloc(1, 1);
7514 }
7515 AudioParameter param = AudioParameter(String8(address));
7516 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007517 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007518 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007519 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007520 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007521 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007522 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007523 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007524
Eric Laurente8726fe2015-06-26 09:39:24 -07007525 if (mInDevice != mPrevInDevice) {
7526 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7527 mPrevInDevice = mInDevice;
7528 }
Eric Laurent296fb132015-05-01 11:38:42 -07007529
Eric Laurent1c333e22014-05-20 10:48:17 -07007530 return status;
7531}
7532
7533status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7534{
7535 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007536
7537 mInDevice = AUDIO_DEVICE_NONE;
7538
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007539 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007540 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7541 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007542 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007543 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007544 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007545 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007546 }
7547 return status;
7548}
7549
Eric Laurent83b88082014-06-20 18:31:16 -07007550void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7551{
7552 Mutex::Autolock _l(mLock);
7553 mTracks.add(record);
7554}
7555
7556void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7557{
7558 Mutex::Autolock _l(mLock);
7559 destroyTrack_l(record);
7560}
7561
7562void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7563{
7564 ThreadBase::getAudioPortConfig(config);
7565 config->role = AUDIO_PORT_ROLE_SINK;
7566 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7567 config->ext.mix.usecase.source = mAudioSource;
7568}
Eric Laurent1c333e22014-05-20 10:48:17 -07007569
Glenn Kasten63238ef2015-03-02 15:50:29 -08007570} // namespace android